question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
67,955,733
67,956,387
Check if number is a tribonacci number
Tribonacci numbers are defined as below. I am trying to write a program that checks if a number is a tribonacci number. I have wrote the function, but how can I acctually check if the number is a trib number with this? Because when I enter 45, it wont return anything. T0=0 T1=1 T2=2 Tn=Tn-1 + Tn-2 + Tn-3 (for n>2) int ...
Other than memoization + recursion, an old style approach is to use a while loop and stop if the value >=n: #include <iostream> bool trib(int n) { if (n == 0 || n == 1 || n == 2) {return true;} int a = 0, b = 1, c = 2, d = a+b+c; while(d < n) { a = b; b = c; c = d; d = a+b+c; } if (d ==...
67,955,853
67,959,333
Is it legal for a compiler to ignore an #include directive?
As I understand, when compiling a compilation unit, the compiler's preprocessor translates #include directives by expanding the contents of the header file1 specified between the < and > (or ") tokens into the current compilation unit. It is also my understanding, that most compilers support the #pragma once directive ...
Is it legal for a compiler to completely ignore an #include directive if it has previously encountered a #pragma once directive or include guard pattern in this header? Of course it is! It is even legal for the compiler to ignore all your source files and header files so long as behavior of the generated code is the ...
67,955,877
67,956,084
Clear strings from process memory
To improve the security of my application, I am trying to delete string data from the process memory, but since there is little information about this on the Internet, I could not write a working code. Can anyone help me? My pasted code: void MemoryStringsClear() { HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FAL...
There are some problems with your approach (my idea for a solution is further down): Most of the strings listed are environment variables All of the programs that run on your computer have access to those. They are copied to the memory space of every program on startup so every program knows where to look for certain f...
67,956,477
67,956,622
Parameterized constructors of derived class in C++
There are two classes. One is derived from a base class. Both of these classes have parameterized constructors. #include<string> #include<iomanip> //declaring parent class class parent { protected: int a; public: parent(int x); void displayx(); }; //declaring child class class child:public parent { privat...
The constructor of your child class can take two values - one for a and one for b, and you can pass the first one to the parent constructor: class child : public parent { // ... public: child(int x, int y); // ... }; child::child(int x, int y) : parent(x) { b = y; std::cout << "child \n"; } int main() { ...
67,956,586
67,956,680
Is constructor called in before the data members in C++
Hello i am new to learning C++. Is constructor created in the order i create it in the class or is it always called first before anything else is created in the class. #include <iostream> using namespace std; class NonStatic { public: int no = 2; NonStatic():no(0) { } }; int main() { ...
For int no = 2;, no is initialized as 2 via default member initializer. For NonStatic():no(0) {}, no is initialized as 0 via member initializer list. Then the default member initializer is ignored, for NonStatic obj1;, obj1.no will be initialized as 0 as the result. If a member has a default member initializer and als...
67,956,658
67,956,770
Checking if characters length in string is same or not
I am trying to write a program that checks if characters of created word are in different length. for example word: PAABBBMMMM it should print Yes, because P was printed 1 time, A was printed 2 times, B was printed 3 Times, m was printed 4 times. If the word was for e.g PAABB it should print no, because AA and BB is s...
With the condition if (s[i] != s[0]), you're just checking if each character is equal to the first character, which makes no sense. You can use a std::map to count the frequency of each character, then use std::set to check the uniqueness of each frequency: #include <iostream> #include <string> #include <map> #include ...
67,956,830
67,956,841
what is the best way to move the elements: the whole vector or move + erase for the elements?
I'm wondering how best to move elements from one vector to another .Let's say you can do this : std::vector<int> v(10); std::fill(std::begin(v), std::end(v), 5); std::vector<int> move_v = std::move(v); And then everything works as I thought: std::size(v) prints 0, and in another vector the elements appeared. On the ot...
In the first example, you're moving the whole vector at once. This is presumably what you want. Just copy a couple of pointers, you're done. O(1) complexity and everything is good. In the second example, you're moving every element individually. This means that you're trying to move integers, which is the same as copyi...
67,956,885
67,956,967
Why is if statement not working in c++ function?
In this code I can find an element in vector and can print it's indices too.But if i give an input lets say 1 which is not a vector element,it doesn't print output as "Element Not Found.".The if statement after while loop is not working. #include<bits/stdc++.h> using namespace std; void search(vector<vector<int>> v,int...
The v[i][j] will continue to iterate until the subscript returns any non-zero value, (even if it is way out of the valid boundaries). You should introduce this condition into the loop: while(i < v[0].size() && j >= 0) ...; It would be also sane to at least introduce check for v being empty. I also want to bring attent...
67,957,135
67,964,036
function pointer with vector and class
In the purpose of my homework, I learned pointer to function and lambda function. I create a class Rectangle that contain width and length and calculate area. One of the question is to create a class MyVector that is a derived class of stl vector and contain function called func that take in parameter a Boolean functio...
You'll need to make a few changes to the implementation of func(): template <class T> bool MyVector<T>::func(bool(*cmp)(const T&)) { typename MyVector<T>::iterator it; for (it = this->begin(); it < this->end(); it++) if (cmp(*it)) return true; return false; } The main differences betwe...
67,957,464
67,957,580
Checking the availability of a word within a phrase, in a given position
Please let me know how can I check whether the first word of a given string is "echo" ,ignoring if any spaces before the word. Example: string hello = " echo hello hihi"; if(startwith(hello, "echo") { //some code here } Please help me if possible
string_view has a similar functionality. Just skip the white space and use that. #include <string> #include <string_view> using std::string, std::string_view; constexpr bool StartsWithSkipWs(string_view const str, string_view const prefix) noexcept { auto begin = str.find_first_not_o...
67,957,835
67,958,522
CListCTrl - How to Align Text from specify Column?
I'm trying to align the header text to center while body data will align to left. This's my illustrations: In the OnInitDialog event, I added the column as follows: mylistCtrl.Create(WS_CHILD | WS_VISIBLE | LVS_REPORT, CTRLrect, &m_cTab, IDC_ctrlist); mylistCtrl.InsertColumn(1, L"Column1", LVCFMT_LEFT, 50); then I try...
Try to do it in this way: HDITEM hdi{ 0 }; hdi.mask = HDI_TEXT | HDI_FORMAT; pHeader->GetItem(1, &hdi) hdi.fmt |= HDF_CENTER; pHeader->SetItem(1, &hdi); pHeader->ModifyStyle(0, HDS_HOTTRACK); // optional Of course, you have to assure that you have your text as valid inside your header control.
67,957,912
67,960,008
Is there a way to display integer data inside a QTableWidget as hexadecimal?
I have a class that inherits from QTableWidget called InsnTable and one of its columns has integral data... I want to display the integers as 32-bit hexadecimal values. Is there an easy way to do so? I think of storing the data as QStrings instead of int and convert integers to hexadecimal accordingly... The problem wi...
sure: you can in the part where you do: QVariant::fromValue(addr) give a string formatted as hexadecimal, you need something like this to convert a number into a hex QString uint decimal = 255; QString hexadecimal{}; hexadecimal.setNum(decimal,16); at the end the code can looks like: void InsnTable::insertInsn(const ...
67,958,321
67,970,227
how to use Apache Arrow to do "a + b + c*5 + d*3"?
I got the idea of using pre-defined functions to do this: calculate "a + b", "c * 5", "d * 3" and then add the result. But this way seems generate a lot of code. Is there any better methods to do this? By the way, does Apache Arrow use SIMD by default(c++ version)? If not, how can I make it use SIMD?
PyArrow doesn't currently override operators in Python, but you can easily call the arithmetic compute functions. (functools.reduce is used here since the addition kernel is binary, not n-ary.) PyArrow automatically uses SIMD, based on what flags it was compiled with. It should use the 'highest' SIMD level supported by...
67,958,748
67,961,991
Specifying a concept for an object with a member function that returns a constrained value
I am trying to wrap my mind around C++ 20 concept and constraint by porting some of my old code. struct Status { std::string status; std::time_t statusDate; }; struct CurrentStatusStack { std::vector<Status> statusVec; std::vector<std::filesystem::path> ticketPathVec; }; void setBar(CurrentStatusStack...
A concept is not a type, so it can’t appear as a container element type—neither in the type of an object (this is why you have to use std::vector<std::any> to approximate std::vector<std::copyable>) nor in the type for your concept ContainerOf. Moreover, you can’t use a concept as a template argument, so you can’t hav...
67,958,844
67,959,560
How to find character arry location of individual elements in c++
#include <iostream> #include <cstring> using namespace std; int main(){ char first_name[20] {}; cout << "Enter Your First Name : "; cin >> first_name; cout << "Hi "<< &first_name <<", Welcome to C++ Programming."; return 0; } if I write &first_name it is giving the memory location of first element...
OK, so @mnhaouas answer explained why it does not work but there are ways around it. First, old and dirty C style, which should be avoided for production code. std::cout << (void *) &first_name[4] << "\n"; Again this should be used for debugging or playing around. C++ is way stricter about converting pointers, but thi...
67,958,892
67,958,967
Why does MSVC /I option not find the directory?
I have a very basic project structure: project ├───lib │ └───SDL │ └───SDL.h ├───src │ └───Main.cpp // Main.cpp #include <SDL\SDL.h> int main() {} From the project directory I run the command CL /I\lib src\Main.cpp, which says src\Main.cpp(1): fatal error C1083: Cannot open include file: 'SDL\SDL.h': No...
Use: /I.\lib or: /Ilib To refer to a relative path.
67,958,980
67,959,029
return *this causing major frustration
I've been using C for about a year and finally decided to learn C++. I'm trying to implement my own linked list class like this: #include <cstdio> #include <cstdlib> struct linked_list_node { int value; struct linked_list_node* next; }; class LinkedList { linked_list_node* head; public: LinkedList add...
Your add function was returning a copy of LinkedList. Since you didn't provide a copy constructor, you were using the compiler-generated one which simply copies the members element-by-element. When you copy pointers, there's a huge danger of doing a double free or trying to use a pointer after it's been freed. There's...
67,958,985
67,960,657
Wrapping a C++ Member Function Pointer (Emscripten)
I would like to create a wrapper around a C++ member function, which does some additional tasks before calling the actual member function. I'm working with Emscripten and my example below is using the .function function. Let's say I have a class called SomeClass (which I don't "own", i.e. it's coming from a third party...
I figured it out. Emscripten seems to be design with such a use-case in mind and offers a specialization of the RegisterClassMethod struct for std::function. Using the following code, I can achieve what I want to do. class_<SomeClass>("SomeClass") .function("test", std::function<void(SomeClass&)>([](SomeClass& s) { ...
67,959,239
67,959,591
What is complexity of std::common_type?
I wrote my std::common_type implementation: template <typename Head, typename... Tail> struct my_common_type { using type = typename my_common_type<Head, typename my_common_type<Tail...>::type>::type; }; template <typename T, typename U> struct my_common_type<T, U> { using type = std::remove_reference_t<decltype(t...
When applying common_type to three or more template arguments, common_type<T1, T2, R...>::type is defined to be common_type_t<C, R...> where C is common_type_t<T1, T2>. If T1 and T2 don't have a common type then the type typedef doesn't exist. This means that common_type is defined to work from left to right on its arg...
67,959,390
67,959,769
Array prints random symbols
I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output #include <stdlib.h> #include <stdio.h> int main(){ int i = 0; char list1[7]; char list2[7]...
#include <stdlib.h> //Need string.h library to use strcopy #include <string.h> #include <stdio.h> #define MAX_CHAR_SIZE 10 int main(){ //We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a str...
67,959,584
67,959,684
C#-like generic, template type constraint in C++
I have a piece of C# code as below: class Foo<T> where T : TClass { // body } Is there any standard method I can achieve that generic type constraint in C++
C++ has std::is_base_of, which can be used with SFINAE (C++17 and earlier) or requirements (C++20). C++20 also adds the concept std::derived_from. C++17: #include <type_traits> #include <cstddef> template<class T, std::enable_if_t<std::is_base_of_v<TClass, T>, std::nullptr_t> = nullptr> class Foo { // Body }; C++...
67,960,047
67,960,154
What happens exactly when casting from a base class to derived one?
In the below code, why does the compiler agree on casting a base class to a derived class knowing the object is purely a base one? How can print2() be called although it's a derived function? Can you tell me please what happens exactly from the point of view of a compiler/memory manager? #include <iostream> using name...
This is undefined behavior, no diagnostic required. A compiler has no obligation to report a compilation error for every possible programming bug. The only required diagnostic is when the program is ill-formed. There's nothing technically wrong with the static_cast itself, with that statement alone. It follows all the ...
67,960,050
67,960,782
"this" gets resetted C++
I am trying to make a class like string(for learning purposes) and i have the following files var.cpp: #include "var.hpp" var::var(){} var::var(const char* v) { (*this) = v; } var var::operator=(const char*& v) { if(string_var) { free((void*)string_var); string_var = NULL; } if(!v) r...
Your problem is that you are missing proper copy/move constructors and you are returning *this by value. Your compiler makes a copy constructor for you which makes shallow copies and messes up your frees (you end up killing things that have already been killed). Change the return type of your assignment operator to var...
67,960,179
67,960,302
Trouble tokenising a string
I am a beginner with C++ and am trying to tokenise a string such that Tokenise("45+3") = {"45","+","3"} Where the output is a vector, here is my attempt: #include <iostream> #include <cmath> #include <vector> using namespace std; vector <string> Tockenise(string input){ vector <string> Tocken_list; std::strin...
Your problem is here: previous_digit[i] = input[i]; previous_digit is of size 0 at that point. The subscript operator [] does not perform bounds check which is why you get a segfault instead of a well defined exception (accessing an out of bounds element). You should use std::string::push_back to add an element to pre...
67,961,296
67,961,383
How does c++ determine whether an integer literal fit int type or not?
I know the standard says if the integer literal does not fit the int, it tries unsigned int, and so forth, per section 2.14.2 Table 6 in the standard. My question is: what's the criteria to determine it fits or not? Why do both std::is_signed<decltype(0xFFFFFFFF)>::value std::is_signed<decltype(0x80000000)>::value give...
You don't need to look at "bit representation" to check if the number fits or not. Assuming sizeof(int) == 4, int can represent numbers from -231 to 231-1 inclusive. 0x80000000 is 231, which is 1 larger than the maximum value.
67,961,464
67,963,406
Append the file extension in the file name if not given, in C++
I'm new to C++. I want to get the fileName as command line argument. User has to enter a fileName. If the user enter the filename without the file extension, then the program should add the the extension to the fileName. I'm writing my code in C++. Is there a function or any method to achieve this?
if (!(fileName.find_last_of('.') != std::string::npos)) { fileName.append(".ext"); }
67,961,779
67,962,210
Code size concerns with variadic templates
I am creating an algorithm that deals with many different user defined types at once. Each of these types will be assumed to have a func1 and func2 that will be the interface for MyAlgorithm. I can do this using variadic templates: template <typename... Args> class MyAlgorithm{ // interact with Args using func1 and...
Type erase a type T to be called by func1/func2. struct proxy_ref{ void* pdata=0; void(*pfunc1)(void*)=0; void(*pfunc2)(void*)=0; template<class T> proxy_ref(T&& t): pdata((void*)std::addressof(t)), pfunc1([](void*pvoid){ ((T*)pvoid)->func1(); }), pfunc2([](void*pvoid){ ((T*)pvoid)...
67,961,986
67,962,328
Why we need to put parenthesis when giving a template type
Hello I am trying to understand this piece of code: vector<int> a = {5, 3, 6, 1, 7}; sort(a.begin(), a.end(), greater<int>()); for(int i : a) cout << i << " "; cout << endl; Why I need to put parenthesis after the greater. This greater is a structure defined which is like this: /// One of the @link comparison_functors...
Why we need to put parenthesis when giving a template type sort(a.begin(), a.end(), greater()); std::greater is a class template. std::greater<int> is an instance of that class template, and is a type (more specifically, a class type). std::greater<int>() is a temporary object (an instance of the type that is the ins...
67,962,155
67,962,338
Weird namespace concept in c++
I came across this: template<class T> using PQ = priority_queue<T>; I was not able to understand what is going on so I tried to go to the source code and replicate this myself: template<class T> class I_Love_You { public: static void print() { cout << "Hello StackOverflow!" << endl; } }; template<...
template<class T> using PQ = priority_queue<T>; priority_queue is a templated type, so we always have to specify a type for it. If we make a alias for it, PQ, priority_queue still needs to know it's type. So we declare PQ a template, and pass the value that is passed to PQ to priority_queue.
67,962,170
67,962,358
Why does my variadic template instantiation not work?
I am revisiting C++ after a long hiatus, and I would like to use templates to design the known "map" function -- the one which applies a function to every element of a collection. Disregarding the fact my map doesn't return anything (a non-factor here), I have managed to implement what I wanted if the function passed t...
A simple way to fix this would be to deduce the non-type template parameter for the function, and reorder the template parameter list template <typename C, auto fn, typename ... T> void map(const C & c, T ... args) { for(auto i : c) { fn(i, args...); } } and then call it like this map<some_container_t...
67,962,227
67,962,258
static_assert failed because value type is destructible for std::vector
I have a very simple program. Not sure why static_assert(is_destructible<_Value_type>::value fails. <source>:16:12: required from here /opt/compiler-explorer/gcc-8.1.0/include/c++/8.1.0/bits/stl_construct.h:133:21: error: static assertion failed: value type is destructible static_assert(is_destructible<_Value_...
static_assert failed because value type is destructible for std::vector No, the assert fails because the value type is not destructible. Can some once explain why destructor is causing an issue ? If you declare a private destructor, then the class is not destructible (outside of the member functions of the class). ...
67,962,488
67,962,530
Attempt to create a variadic C++ input function
Recently I've been doing some CP stuff and grew bored of using cin in C++. So I thought I could at least create a cleaner input function. So I'm stuck here. #include <bits/stdc++.h> using namespace std; void read() {} template <typename T, typename... Type> void read(T var1, Type... var2) { cin >> var1; read...
The issue is your arguments to read are passed by value, so the variables in main are never modified. You need to take the arguments by reference instead. You can also use fold-expressions to make read much cleaner template <typename... Ts> void read(Ts & ...vs) { (std::cin >> ... >> vs); } demo Also, please get...
67,962,538
67,962,734
std::mutex :: when the lock acquired thread gets killed what would happen to other waiting threads with respect to std::mutex locks
Multiple threads are trying to access a critical area and assume we use std::mutex to lock it. Now one of the thread acquired the lock and after sometime if it gets killed .. what would be the system behavior? Similar to pthread mutex robust do we have anything for std::mutex?
Similar to pthread mutex robust do we have anything for std::mutex? No we don't. Not on the systems, I know about, anyway. On POSIX systems, the 'robustness' of a mutex has to be set when the mutex is created. Since the mutex is created by the std::mutex constructor, and this has no 'robustness' parameter, this is ...
67,962,752
68,133,976
Changing qml style at runtime
i've started to learn qt and qml and get to some trouble - i wanted to change style of qml file in runtime by getting value(style name) from combobox, i've found the solution and found this as a bug: QTBUG-68567: Document how to change the style at run-time https://bugreports.qt.io/browse/QTBUG-68567 But i have trouble...
The solution is to create a new class, that will be main class of app, where will be as private variables declarated QGuiApplication, QQmlEngine and this class will have method that's reloading engine, where will be executed step by step instruction from this link https://bugreports.qt.io/browse/QTBUG-68567
67,963,188
67,963,913
What is a placement new?
I have some questions about placement new: int x; int* p = new(&x) int{10}; std::cout << x; // 10 When we say placement new, do we refer to new expression or operator new (function)? void* operator new(std::size_t, void*. int); // is this a placement new? I am so confused! sometimes I find "new operator" other ti...
What is a placement new? It constructs a dynamic object into provided area of storage. When we say placement new, do we refer to new expression Yes, but specifically to a new expression where the placement parameter has not been omitted. "Placement syntax" is also used to refer to this. or operator new (function)?...
67,963,332
67,963,901
MVC design pattern QT
I am currently trying to implement a MVC design pattern. I prefer an approach where the model and the view are independent from each other as well as from the controller. As shown in the image. I understand that this topic has been talked about before but based on the research I am still not entirely sure how I should ...
A typical solution can be, the view has data members exposed using Q_PROPERTY(set, get and notify). View doesn't need to know the controller at all. View is an independent object owned by the controller. For one spinbox, the view declaration can be namespace Ui { class View; } class View: public QMainWindow { ...
67,963,794
67,963,872
How can I make an "Unless condition" in an IF statement c++
I'm making blackjack in C++ and I'm nearing the end! I'm making my winning and loss statements. But my issue is that I need my if statements to determine not only whether or not the dealer's/players hand is greater or less than one another it needs to check if either has gone over 21. So having the if statements determ...
In Blackjack, if both the player and the dealer get more than 21 (which is called "busting"), then the player loses and the dealer wins. Therefore, you must design the logic accordingly: if ( //player busted, or playerTotal > 21 || //dealer not busted and dealer has more points than player ( dealerTota...
67,964,300
67,964,483
How do i use array to display all 5 information of batsman
this is the question:Create an array of object to display the information of five batsmen.what i encountered is after compiling it displays same information 5 times how do i fix that. #include<iostream> using namespace std; class batsman{ private: string first_n; string last_n; int runs_made; int no_of_...
the reason that it display same information 5 times is that in getvalue function you are looping 5 time and in every loop you are get value from user and after that store those value in some variable but in every loop you are store value in same variable therefore you are override previous stored value so in order to d...
67,964,336
67,979,556
what the the fastest way to save multi-layer map?
I want to build a key-value container to save data. i can build a three-level unordered_map to map it, the key will be <int, <int, <int>>>, but i think it's slow. So, I want to map <int, int, int> into a unique int. then i can save it in one-level unordered_map For example: assume the three key is called a, b, c, a's r...
unordered_map expects a hash function returning size_t, so if you're compiling a 64-bit application (as most people do except in some embedded environments), you can combine the integers trivially: size_t encode(int a, int b, int c) { return a + (b * 10'000) + (c * 10'000 * 1'000'000); } If your hash table uses a ...
67,966,538
67,971,759
calling a __host__ function from a __host__ __device__ functon is not allowed
I am trying to use thrust with Opencv classes. The final code will be more complicated including using device memory but this simple example does not build successfully. #include <thrust/host_vector.h> #include <thrust/device_vector.h> //#include <thrust/copy.h> #include <thrust/remove.h> #include <cuda.h> #include <c...
As pointed out in the comments, for the code you have shown, you are getting a warning and this warning can be safely ignored. For usage in CUDA device code: For a C++ class to be usable in CUDA device code, any relevant member functions that will be used explicitly or implicitly in CUDA device code, must be marked wit...
67,966,826
67,966,976
c++, what happens when an lvalue is passed to T&&?
#include <bits/stdc++.h> #include <vector> template <typename T> void g(T&& val) { std::vector<T> v; } int main() { // g(2); int i; g(i); } When g(2) is called, it complies, but when g(i) is called, the complier has a lot of errors. Some of the errors are pasted as follows: forming pointer to refer...
1: A forwarding reference, and g(2) makes T an int g(i) makes T an int& 2: You can't have arrays of references (new T&[x]). You could use std::remove_cvref_t to get the type int out of T: #include <type_traits> template <typename T> void g(T&& val) { using type = std::remove_cvref_t<T>; // type is int std::...
67,967,037
67,967,764
In a diamond inheritance structure, is there a way to cast between the branches?
I have a diamond inheritance structure in my code in which I have a pointer to the bottom object. I tried to case this to a pointer to the left of the two diamond sides, cast it again to the top of the diamond, and again to the right side. But apparently, C++ kind of remembers the order of casting and things don't work...
As inheritance is not virtual (for A), you have "Y" inheritance (2 A), A A | | B1 B2 \ / C not a diamond (1 A). Avoid C-cast which might result in reinterpret_cast, and most reinterpret_cast usage leads to Undefined Behavior (UB). You might use dynamic_cast in your case to have expected behavior (...
67,967,211
67,967,468
C++ template parameter: to find out if a parameter exists in parameter list during compilation time
I have a struct Robot: template<typename... FeatureList> struct Robot { Robot() = default; }; That it can be configured with a few features (a few structs are used as token here): struct CanWalk { }; struct CanNotWalk { }; struct CanFly { }; struct CanNotFly { }; Robot<CanWalk, CanFly> robot_A = Robot<CanWalk, C...
You could add a feature test type trait: #include <type_traits> template<class Feature, class... FeatureList> struct has_feature { static constexpr bool value = (std::is_same_v<Feature, FeatureList> || ...); }; template<class Feature, class... FeatureList> inline constexpr bool has_feature_v = has_feature<Feature...
67,967,306
67,968,701
Why is copying or assigning objects of this class considered dangerous?
From "C++ Concurrency in Action" by Anthony Williams. The author defines a thread_guard class which, is passed a reference to a std::thread upon construction, and upon destruction, attempts to join() that same thread. Here is the definition class thread_guard { std::thread& t; public: explicit thread_gu...
The std::thread object that the thread_guard guards is held by reference. Therefore, if the thread_guard object outlives the std::thread object, then there is a dangling reference, and the call to t.joinable() is undefined behaviour. Making thread_guard non-copyable makes it harder to end up in this scenario: since the...
67,967,424
67,967,564
Pointer as template argument - how to declare pointer to const inside template
When a pointer type is passed as argument to template parameter T, how do I declare a pointer to const type? Both const T and T const become const pointer to type, whereas I need to declare a pointer to const type. template<typename ValueType> class TestClass { public: void TestMethod(const ValueType x) { /...
You can create a trait that does it. template <typename T> struct add_inner_const { using type = const T; }; template <typename T> struct add_inner_const<T*> { using type = const T*; }; template <typename T> using add_inner_const_t = typename add_inner_const<T>::type; template<typename ValueType> class TestClass { p...
67,967,637
67,967,860
Get reference on class from in-class struct method
I have this code: //.h class A { struct B { void SomeMethod(); } B b; } //.cpp void A::B::SomeMethod() { //here will be code } Can i get the link to the object of class A from SomeMethod()? Because this return reference on struct object b. Maybe answer can be pretty easy to find, but I can't ...
From the design (B being private member of A) looks like the user shall only have the access to A class interfaces. Then what about just passing a parent class pointer to the method: class A { struct B { void SomeMethod(A* parent); }; B b; public: void callSomeMethod() { b.SomeMethod(this); } ...
67,967,849
67,969,384
Can changing a value from X to X in C++ lead to a data race?
I have code that works with large data blocks having different layouts. The layout will determine which part of the data is fixed, and which data is not fixed. Once data is fixed in a block, it normally doesn't change anymore. So all code reading data will always see the same data. However, other services may make c...
Is this a data race? Yep. Is it allowed to overwrite a memory address with exactly the same value if other threads can read the data at the same time? Not explicitly - and that's not the only issue, either. If your compiler actually performs a single 8-byte load, you have a real (ie, not even potentially just theor...
67,968,070
67,968,341
When to use std::make_shared_for_overwrite?
C++20 introduces new function std::make_shared_for_overwrite() in addition to std::make_shared(): https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared Why old make_shared was not enough and in what situation one needs to use new function?
std::make_shared() value initialises the object(s) it creates, which might be an unnecessary step if you intend to assign values over them later. std::make_shared_for_overwrite() default initialises the object(s) it creates. The difference only matters for (sub-)objects of fundamental types, where there is no initialis...
67,968,404
67,968,550
use a function parameter as template parameter
template<unsigned int size> struct Vec { Vec() = default; }; auto build_vec(unsigned int size) { return Vec<size>(); } int main() { auto vec = build_vec(5); return 0; } This program doesn't compile as non-type template argument is not a constant expression. Basically, the size parameter sent into bui...
No, this is not possible. A functions parameter is not known at compile time. The common way to signal that size must be known at compile time is to make the function a template and size a template parameter: template<unsigned int size> struct Vec { Vec() = default; }; template <unsigned int size> auto build_vec()...
67,968,441
67,969,610
C++: wntdll.pdb not loaded correctly on class destruction with operator
Note: I'm using the visual studio community 2019 C++14 compiler. It seems that the following program is trying to delete an empty location. I'm trying to delete a custom vector class after calling the + operator on it... Here is the code: class Vector { public: Vector(const double* t, int dim) : m_dim(dim) { ...
Thanks for @AlZ23z and @Ted Lyngmo for answers. The rule of three must be applied saying that there must be a =operator, copy constructor and destructor for the function. Vector(const Vector&); ~Vector(); void operator=(const Vector&); void Vector::operator=(const Vector& v) { for (int i = 0; i < m_dim; i++) { ...
67,969,172
67,972,331
Find lowest real value in complex vector
How can I find the smallest positive real number in a complex vector of size N by 1 in Eigen3? For example, in this case I'd like to find the value 3.64038. #include <Eigen/Dense> #include <iostream> using namespace std; using namespace Eigen; int main() { MatrixXd m(4, 4); m << 1, 0, 1, 1, 0, 2, 0, 1,...
One option is to create a logical array and then call Eigen::select on it. Inspired by https://forum.kde.org/viewtopic.php?f=74&t=91378 In this case: Eigen::VectorXcd v = m.eigenvalues(); // minimum positive real value with zero imaginary part Eigen::Array<bool,Eigen::Dynamic,1> cond1 = (v.imag().array() == 0); Eigen:...
67,969,759
67,969,804
Can I make a constructor in C++ of different data types?
I have a class which has multiple data members of different data types. I was wondering if I can create and initialize an object using a constructor. class test { public: int a; string b; float c; test (int x, string y, float z); }; int main() { test t1(10,"Hello"...
The fact that it doesn't work is not really what we do on StackOverflow. You should provide an error message. With that said, I suppose you are getting an error from the linker because your constructor does not include a definition, but only a declaration. Here's a working example: https://godbolt.org/z/r89cf86s3 #incl...
67,970,038
67,970,107
What advantages does C++20's std::source_location have over the pre-defined macros __FILE__, __LINE__ and __FUNCTION__?
In my current project, I have used: Log(__LINE__, __FUNCTION__, message); But the new C++20 utility class std::source_location comes with functions line(), column(), file_name(), function_name(), which do the same thing. So, the new C++20 way would be: log(std::string message,const std::source_location& location = std...
Pre-C++20 you had to choose between being verbose (passing __LINE__, __FILE__, __func__ to each call manually) and using a macro to do that for you. std::source_location gives you a nice calling syntax without a macro. There are no other hidden advantages. Note that both Clang, GCC, and MSVC have the same non-standard ...
67,970,403
67,970,458
How to handle C char* defines in C++
I am porting some C code to C++ right now. The C code is using multiple defines like: #define IPADDRESS "fd9e:21a7:a92c:2323::1" The problem that i have is that when i am calling C functions with the defines that are now in the C++ file i get: warning: ISO C++ forbids converting a string constant to ‘char*’ I don't wan...
The problem is that string literals "this is a string literal" are of type char[] in C but const char[] in C++. So if you have sloppily written C code which doesn't use const correctness of function parameters, that code will break when ported to C++. Because you can't pass a const char* to a function expecting char*. ...
67,970,600
67,981,406
VSCode: Do we need to install extensions in order to use the Go to Definition?
I'm using VSCode 1.56.2 on Windows, without any extension installed. I'm using VSCode for C++. The problem is that the go to definition, Go to declaration, Go To Type Definition, Go to References and Go to implementations are disabled and I cannot use them. I'm new VSCode. Do I need to install special extensions? If so...
Yes, for each additional language you want to use in vscode, besides a few built-in ones like Javascript, Typescript, JSON and Markdown, you need to install an extension, which supports that language. Search for the particular language in the extension list in vscode or in the vscode marketplace.
67,970,640
67,970,721
Proof for the time complexity in big O of a inserting unique numbers in a list
I was writing a simple loop in C++ and was wondering what the time complexity would be. My intuition tells me that it is O(n*log(n)) but I couldn't come up for a proof for the n*log(n) std::vector<int> nums{1,2,3,4,5,1,1,1,1,3,3,3,3}; std::vector<int> unique_nums; // get all unique nums for(auto n: nums) { if(std...
Worst case is when the input has only unique numbers. In that case, the equivalent is: for(auto n: nums) { std::find(unique_nums); // we already know that it is not found // because input is unique numbers unique_nums.push_back(n); // and we have to push_back anyhow } std::find ...
67,970,747
67,973,533
ignore template parameter in type matching
This is my current program: #include <type_traits> template<class Feature, class... FeatureList> struct has_feature { static constexpr bool value = (std::is_same_v<Feature, FeatureList> || ...); }; template<class Feature, class... FeatureList> inline constexpr bool has_feature_v = has_feature<Feature, FeatureList...
I see three challenges here: you need to extract a specific trait (CanWalk), regardless of its parameters, from a parameter pack you need to ignore extra copies of the same trait you need to set a default trait (CanNotWalk) if that trait is not present I don't know a better way to do this than recursively: // definit...
67,970,880
67,971,546
DEXT crashes on macOS 10.15.7
I successfully built and ran Apple's sample Communicateing Between a DriverKit Extension and a Client App on macOS 11, meaning I can install the DEXT and also control it via it's client. On macOS 10.15.7 though, I can build it and install the DEXT, but the DEXT crashes. The output of systemextensionsclt: systemextensio...
The missing symbol __ZN8OSAction18CreateWithTypeNameEP8OSObjectyymP8OSStringPPS_ refers to OSAction::CreateWithTypeName(OSObject*, unsigned long long, unsigned long long, unsigned long, OSString*, OSAction**). This function is only available from Big Sur/macOS 11.0/DriverKit 20.0 onwards. You should probably use the au...
67,971,662
67,971,702
error in c++ matrix*vector multiplication
I need a function that multiply a matrix and a vector (Matrix*vector) It takes in a matrix A and a vector B, with int describing the dimensions. Somehow it isn't running correctly. Any help?? void Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows) { if (ACols !=BRows) { ret...
It seems you mean for (int i = 0; i < ARows; i++) { res[i] = 0; for (int j = 0; j < ACols; j++) { res[i] += A[i][j]*B[j]; } } It would be better if the function returns a boolean value that signals whether the function execution was successful for example bool Multiply(double *res, double **A, ...
67,971,938
67,972,332
C++ delete operator and destructor:what do they actually do and what are the differences of the two?
I am trying to figure out in C++ the difference between delete operator and destructor and I tried use the following two snippets (I use visual studio 2019 to compile them) : code 1: #include <stdio.h> class A { public: A() { a = new int; *a = 42; b = 33; } ~A() { printf("destruc...
delete myA; is a delete expression. If myA is not nullptr, it will first call the destructor of the object pointed to by myA (if the pointed type has a destructor), then it will release the storage used by the object which was previously allocated by a new expression. myA->~A(); explicitly calls the destructor of the o...
67,972,262
67,973,313
Assigning value only works outside the loop
I am learning CPP (first language) and I am trying to reverse a linked list. this code is not working node* reverse(node** head){ node* previous=NULL; node* current=*head; node* nextptr=current->next; while(current!=NULL){ current->next=previous; previous=current; current=nextptr...
Why does the second code snippet works while the first one doesn't ? The first snippet doesn't check before it dereferences potentially null pointers. Because you are using a null pointer to indicate the end of the list, it always dereferences a null pointer, and so has undefined behaviour. The second snippet never d...
67,972,273
67,972,377
Curl data from Steam community market
I've been trying to fetch data from steam community market , Code : #include <iostream> #include <string> #include <curl/curl.h> static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } int main(...
curl doesn't follow redirects by default, and the site you mention uses those. I had to turn on CURLOPT_FOLLOWLOCATION to make it work: curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // redirects // bonus: curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1L); // corp. proxies etc. Possible output: {"success":true...
67,972,468
67,972,613
Elegant solution to VS code C/C++ include path for both intelliSense and building project
How to create task.json and launch.json for building and debugging a C/C++ project, that parameters can be loaded automatically from c_cpp_configuration.json? (parameters such as include path, compiler path) Enviroments: windows 10.0.19041 VS Code 1.52.1 VS Code extension: ms-vscode.cpptools 1.2.2 Lets say I have the...
Here's what I do: uninstall Microsoft's C/C++ extension and replace it with Clangd for code completion and Native Debug for debugging. I had better experience with those two, including easier configuration. Clangd is configured by a single file called compile_commands.json, which is just a list of compiler flags for ea...
67,972,939
67,973,102
Lambda-function as a parameter
I am working with lambdas for the first time. I am supposed to write a function walk() which takes a lambda function as a parameter. In the header I declared said function as: template<class T> void walk(T operation) const; We are supposed to define the function in an .inl, which I have done like this: template<cl...
You have instantiated Sea::Grid2D<int> - that is, T is int - which gives you: void Sea::Grid2D<int>::walk(int operation) const { for(auto a : Sea::Grid2D<int>::grid) { operation(a); } } which fairly obviously has a typing problem - the type of the operation should not be the same as the type of your gr...
67,973,135
67,973,362
Why operator= is not working for standard types with template placement new?
So ~T() works even for standard types (which are not classes/structs) I assumed operator=(const T &) also can be valid as the default method, but it's not: #include <new> template <class T> void foo(T el) { alignas(T) unsigned char buf[sizeof(T)]; T *ptr = new (buf) T(el); // error: request for member 'operator=...
Yes. The standard defines "pseudo-destructor calls", so that something like ptr->~T() or ref.~T() is valid for built-in scalar types (§[expr.prim.id.dtor]): An id-expression that denotes the destructor of a type T names the destructor of T if T is a class type (11.4.6), otherwise the id-expression is said to name a p...
67,973,410
67,973,635
make function pointer in class dependent on initialized value
I want to create an object, and during initialisation choose a function to perform some calculation. For a polynomial of order N, some function has to be called, defined as someFunN. Now I am able to do this with a function pointer. I do this by a huge if block in the constructor, if (order == 2) SolveFun = &someFu...
You're probably looking for a lookup table: #include <iostream> void say_hello() {std::cout << "Hello!\n";} void say_bye() {std::cout << "Bye!\n";} void say_thanks() {std::cout << "Thanks!\n";} int main(void) { int n = /*something 0-2*/; void (*says[])() = {say_hello, say_bye, say_thanks}; void (*spee...
67,973,497
67,975,074
Calling shell script from system c++ function making the shell script running as different user
I am using the system c++ call to execute the shell script the caller program is running as root but the shell sctipt which is called form the c++ code is running as different user. How can I make sure the shell script should also run as root user like the c++ binary. I don't want to rely on using sudo command as it ca...
A few bits of documentation to start: From man 3 system's caveats section: Do not use system() from a privileged program (a set-user-ID or set-group-ID program, or a program with capabilities) because strange values for some environment variables might be used to subvert system integrity. For example, PATH could be m...
67,973,597
67,975,246
Does this class satisfy the Allocator requirement?
I made a custom allocator, but my code didn't compile on msvc and I'm not sure if my implementation satisfies the Allocator requirement (disregarding actual behavior of function implementations here). Here is a minimal example that reproduces the error on Visual Studio (16.11 P1 and 16.10): #include <memory> #include <...
It does not. An allocator rebound to a different value type must be constructible from the original allocator - this is the A a(b) row in the requirements you linked. Your type fails that requirement.
67,973,802
67,981,344
Variadic template queries
I am trying to understand below code. Copied directly from Jason Turner youtube video #include <iostream> #include <sstream> #include <vector> template<typename ...T> std::vector<std::string> print(const T& ...t) { std::vector<std::string> retval; std::stringstream ss; (void)std::initializer_list<int>{ ...
T and t are parameter packs. There are two primary ways of using a pack: a fold expression (in C++17 and newer) and just a regular pack expansion. A fold expression would look like this: ((ss.str(""), ss << t, retval.push_back(ss.str())), ...); Fold expression repeats its operand for each pack element, inserting some ...
67,973,945
67,974,140
Expected ')' before token inline assembly error
I would like to learn some inline assembly programming, but my first cod snippet does not work. I have a string and I would like to assign the value of the string to the rsi register. Here is my code: string s = "Hello world"; const char *ystr = s.c_str(); asm("mov %1,%%rsi" :"S"(ystr) :"%rsi" //clo...
You left out a : to delimit the empty outputs section. So "S"(ystr) is an input operand in the outputs section, and "%rsi" is in the inputs section, not clobbers. But as an input it's missing the (var_name) part of the "constraint"(var_name) syntax. So that's a syntax error, as well as a semantic error. That's the i...
67,974,056
67,974,589
How can I print "ABCDabcd" with these class constructors?
I have the following code: #include <iostream> using namespace std; class A { public: A() { cout << "A"; } A(const A&) { cout << "a"; } }; class B : public virtual A { public: B() { cout << "B"; } B(const B&) { cout << "b"; } }; class C : public virtual A { public: C() { cout << "C"; } C(...
The ABCD portion of the output you see is being printed by the default constructors of A, B, C, and D. When main() constructs the D object, it is invoking D's default constructor, which invokes A, B, and C's default constructors. The abcd portion of the output that is missing is printed by the copy constructors of A, ...
67,974,238
67,974,315
How to interpolate a value in one range into another
I have 2 double values which can go from let's say start value 62.243 to end value 79.495. I have another 2 double values which can go from let's say start value 4.456 to end value 7.687. double start_1 = 62.243; double end_1 = 79.495; double start_2 = 4.456; double end_2 = 7.687; Now if I a value picked between star...
For a number value_between_start_1_and_end_1, lambda = (value_between_start_1_and_end_1 - start_1) / (end_1 - start_1) tells you how far you are along the 1-line. 0 means you're at start_1, 1 means you're at end_1. Then use start_2 + lambda * (end_2 - start_2) to get the corresponding position along the 2-line. I've ...
67,974,399
67,975,169
what is the Time Complextity of a below function?
#include <iostream> using namespace std; bool isPrime(int n){ if(n == 1 || n == -1) return false else if (n ==2 || n == 3) return true; else if((n+1)%6 == 0 || (n-1)%6 == 0) return true; return false; } int main() { int n{0}; cin >> n; cout << isPrime(n) ...
It only does a handful of divisibility checks and has no loops or recursion, thus it is simply O(1) and is not a correct prime number check. The third check makes very little sense. Why would a number be prime if it is one away from a multiple of 6? I mean it happens to work for 5 and 7, for 11 and 13, and for 17 and 1...
67,974,443
67,974,505
Problem in using hash tables as the solution to this problem
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks...
There are 2*n numbers to read and process, but you processed only n numbers. Process 2*n numbers to fix.
67,974,510
68,283,814
Why boost property tree xml serializer cannot preserve multi-line values?
I am working with boost property tree (v.1.72.5) to read and write xml files. I know that according to the documentation: The XML storage encoding does not round-trip perfectly. A read-write cycle loses trimmed whitespace, low-level formatting information, and the distinction between normal data and CDATA nodes. Comme...
As @sehe has mentioned in the comments, it is how the boost property tree has been implemented. I think the best workaround to avoid this problem is to always use the boost::property_tree::xml_parser::trim_whitespace attribute and also assign the values to an specific tag. With this apprach, my xml file would always be...
67,974,722
67,974,792
How to use Templated methods in C++?
In my header file, I have two different kind of objects ImageFrame and `PointCloudFrame. These are then defined with a std::variant as such struct ImageFrame{ }; struct PointCloudFrame{ }; using SensorFrame = std::variant<std::shared_ptr<ImageFrame>, std::shared_ptr<PointCloudFrame>>...
template <class ImageFrame> std::string getFrameBin(const ImageFrame& image_frame) { std::string x; return x; } Means the same thing as template <class T> std::string getFrameBin(const T& image_frame) { std::string x; return x; } So you are defining your template twice. If you mean to make specializations for...
67,974,876
67,974,914
C++: How to acces static member of templated class without template arguments
I have this code: #include <iostream> template <typename T> class Test { public: // Some code... static int member; }; int main() { std::cout << Test::member; } This of course doesn't work, because penultimate line is missing template arguments for Test. But since member doesn't depend on T, i want to ...
You could give Test a default value for the template parameter like template <typename T = void> class Test { and then you would access the member like std::cout << Test<>::member; but you can't get rid of the <> enterly.
67,975,209
67,975,359
Check if static property exists on the class?
How can i check, that some class, passed as a template argument, have some static property on it? Like ::size template<class Header> class Reader { // e.g. Header::size }; My concept is that each Header class must implement a size property that will be read by the Reader class. The Reader class, in turn, will r...
Simply use a concept: template <class T> concept HasSize = requires(T) { T::size; }; template <HasSize Header> struct Reader { // Use Header::size };
67,975,214
67,976,026
Wrapping Windows Thread API
My goal is to wrap Windows Thread API with my own struct. Specifically, I want to use function_impl() as a wrapper for function() and have each instance of Thread create a Windows thread with it's own function(). #include <functional> #include <windows.h> struct Thread { std::function<void()> function; HANDLE ...
As far as I understand, the problem is that function_impl() needs to be static for this to work In your example, yes. but why When function_impl() is a class method without static, it will have a hidden this parameter that affects its signature, making it incompatible with what CreateThread() is expecting. is ther...
67,975,241
67,987,296
Copy elision and operator overloading with C++
I have a struct such as: struct A { double x,y; vector<double> vec; }; I would like to overload operators such as the plus operator so that I can perform operations such as: A a,b,c,d; //do work to set up the four structs. Then: d = a + b + c; Performance is important because these operations will be perfo...
Thank you to Joel Filho for the suggestion to use expression templates, and the reference to the relevant Wikipedia article. That approach in the Wikipedia article worked, although it had to be modified slightly for my particular case, because I am using named class members, instead of implementing a vector. Below is a...
67,975,283
67,975,523
Can I create an integral_constant from a loop variable?
I try to extract all single blocks from a block matrix. However the BlockMatrixClass from the library I am using only allows access through the following indices: Dune::index_constant<0>(), Dune::index_constant<1>(),... They resolve to std::integral_constant<long unsigned int, 0>(). How I can alter the following code t...
Iterating over a compile time sequence is not a completely solved problem since they all rely on various workaround and there is many ways to do it. My preferred way is to use an index sequence, and unroll it using fold expressions: Simply define this: template<typename T, T... S, typename F> constexpr void for_sequenc...
67,975,598
67,975,681
Argument-dependent lookup for templates in C++20
The program as follows compiles fine in C++20: #include <memory> struct A{ virtual ~A() = default; }; struct B: A {}; int main() { std::shared_ptr<A> p = std::make_shared<B>(); auto x = dynamic_pointer_cast<A>(p); } But in C++17 it produces an error: <source>: In function 'int main()': <source>:9:14: error:...
https://en.cppreference.com/w/cpp/language/adl Although a function call can be resolved through ADL even if ordinary lookup finds nothing, a function call to a function template with explicitly-specified template arguments requires that there is a declaration of the template found by ordinary lookup (otherwise, it is ...
67,975,845
67,975,982
How do write a templated free function depending on return type
I have a problem related to type deduction from a function return value. First, some context, to show what I expect. Say I have this function template: template <typename T1, typename T2> T1 foo( T2 t ) { T1 a = static_cast<T1>(t); // dummy conversion, return a; // just there to use t } then, ...
Convert the return type rather than deduce it You can create a conversion proxy object for your return type. This moves the return type deduction into a template conversion operation instead. template <typename T> struct foofoo { T t_; foofoo (T t) : t_(t) {} template <typename U> operator U () const { ...
67,976,005
67,976,335
Return pointer to flatbuffer from a method
I have a class like this, is it valid to return flatbuffer pointer even though builder is created on stack class Foo { uint8_t* serialize() { flatbuffers::FlatBufferBuilder builder(1024); .... .... return builder.GetBufferPointer(); } } From documentation here https://google.github.io/flatbu...
No, this will not work, you're using GetBufferPointer which is a naked pointer to memory owned by FlatBufferBuilder, which will be deallocated upon leaving the function. Like the docs you quote say, you must use ReleaseBufferPointer instead. Or make a copy, though that is obviously less efficient. Better yet to structu...
67,976,089
67,976,220
Swapping Characters inside an array C++
I'm looking to make a series of flashing lights and I want them to appear on the same line. Something like this O * O * O * O * O * O * Title O * O * O * O * O * O * I want these characters to swap positions to make it look like lights that are flashing char Lights[10] = { 'O','*','O','*','O','*','O','*','O',...
Well given your example char Array[10] = {O,*,O,*,O,*,O,*,O,*} You could just print them once from beginning once from the end. void printForward(char arr[10]) { for (int i = 9; i >= 0; i--) { std::cout << arr[i]; } std::cout << std::endl; } void printBack(char arr[10]) { for (int i = 0; i < 1...
67,976,160
69,106,376
How to generate CMakeLists.txt in Clion when I create project from existing sources?
Idk how to make it automaticly - the only option is to specify where the file is - not to generate it, but I don't wan't to write it by my own, because there are too many source files to include.
Here are the steps that helped me: (Optional) If you have a CMakeLists.txt file in your project already but it's incomplete, delete it first. Click on Tools > CMake > Unload CMake Project. Open a source file and you will be presented with the option of selecting a new CMakeLists.txt file or creating a new one. Select ...
67,976,254
68,076,145
ImGui Window doesn't show on DLL Injection
Current Goal: Trying to inject custom code into DirectX11 Games to display windows. Expected Result: ImGui Demo Window should show up after injection but should not be interactable Result Got: ImGui Demo Window doesn't show up or display anything on injection. Things I have tried: Making a custom Imgui window and rei...
The problem was getting the current D3D11RenderTargetView or creating my own D3D11RenderTargetView. Adding parts of the function below or creating a whole new function and adding it to Present Init should fix the problem of ImGui not displaying. bool GetDeivceContextRenderTarget(IDXGISwapChain* pSwapChain) { HRESUL...
67,976,305
67,976,757
Converting Boost ptree node to XML string
I am using boost (version 1.70.0) property tree. Is there a way to convert a node to XML string including the node itself, not just node's children? If I have this XML: <Root> <SomeOtherElement>..</SomeOtherElement> <Collection> <Item Attr1=".." attr2="" /> <Item Attr1=".." attr2="" /> </Collection> </R...
You can create a helper property tree to hold nothing but the extracted one. This involves some additional copying, but should otherwise work just fine: auto node = pt.get_child("Root.Collection"); ptree extraction{}; extraction.put_child("Root.Collection", node); boost::property_tree::write_xml(std::cout, extraction...
67,976,313
67,976,550
Redefine location type in C++ Bison?
The standard version of Bison makes it quite simple to redefine the location type by making sure the following four fields are available: customsourcelocation.h struct CustomSourceLocation { int first_line; int first_column; int last_line; int last_column; }; parser.y ... %define api.location.type {CustomSourc...
Thanks to rici for pointing out the answer. A location.hh file will be generated when using the %locations option, which can be modified and included as fit.
67,976,712
67,977,413
C++ thread writes continuously and read at unknown time
I am trying to get the following scenario to work, but have not been successful so far. I have 2 threads, a worker (that writes) and a reader. The worker continuously modifies the values of a class "someClassToModify". The Reader makes a read access every x seconds (unknown) and reads the current state of the class som...
So, first of all you should note that threads switch at random. That means that worker can do something multiple times before even a single reader gets chance to do anything. Second thing is that reader can access function and for example come to 3rd line and then the context switch happens. You want to avoid that. The...
67,976,765
67,977,042
Calling member function via pointer C++, object is null?
I have a pointer to a ListNode object sum_ptr, which points to sum. When I call the append method via sum_ptr, I get a segfault. Looking at gdb, I am seeing that "this" is 0x0 in the call to append, which does not make sense. Does anyone know why the sum object would be null at the point at which the append method is c...
The reason of the problem is the following. You declared a node using the default constructor. ListNode sum; It seems that the default constructor sets the data member next to nullptr and the data member val to the value INT_MIN (that does not make a sense). Then you are calling the member function append the first t...
67,976,917
67,977,019
Copying an array stored in one class to another class
I have a situation where I need to copy an array of pointers stored in a class to another class. Following the second answer to this question, I have created this reproducible example of what I am trying to do in my actual project. #include <iostream> #include <iterator> struct A{}; class Something { public: stat...
void CopyPointers(const A* pA[Something::nItems]) is equivalent to void CopyPointers(const A** pA); pA is not an array but a pointer. The fix is to use pointer arithmetic instead: void CopyPointers(const A* pA[]) { std::copy(pA, pA + Something::nItems, std::begin(pACopy)); }
67,976,927
67,977,073
code for extracting numbers outside parenthesis doesn't work
I'm trying to write a simple program that extracts the numbers and operands outside the last pair of parenthesis, i'm trying to achieve this by employing a simple recursive function, however, my code is printing nothing. What's wrong with the code? class Puller{ private: std::vector<std::string> container; ...
The problem is with the wrong stopping condition which is leading to an infinite recursion in this line if(x[y] != '('){. You just need to put that condition in the end or you can ignore it all. void sep(std::string x, int y){ if(x[y] == '('){ container.push_back(cache); cache.clear(...
67,977,119
67,977,161
How to access the class member functions from a weak pointer in C++?
I am a complete newbie to smart pointers, and I have never dealt with weak_ptr in C++. I have a function in class Y, that takes in as parameter a weak_ptr of class X. Inside the function in class Y, I need to access the member functions of class X through the weak_ptr. For reference, here is a rough class definition: Y...
You need to convert it to a shared_ptr first, using .lock(): int foo(std::weak_ptr<X> x) { std::shared_ptr<X> y = x.lock(); // Or `auto y = x.lock();`. y->do_stuff(); } The rationale is that a weak_ptr doesn't hold ownership (unlike shared_ptr), so if you could dereference it directly, there would be a risk of...
67,977,384
67,977,418
Does memory allocated on the stack get cleared out when freed?
If we allocate memory on the stack like so: void foobar() { int arr[10]; } After foobar() exits, the reference to this memory block (arr) is lost. But is it zeroed out?
But is it set to zero? No / maybe. There are no guarantees about the "value" of unallocated memory. Nor is there any way guaranteed by the standard to observe that hypothetical "value". From an information security perspective: If you store private information in an object, then you should assume that the information...
67,977,932
67,993,782
Calculate number of points per decade from logarithmic range
I have a range of base-10 logarithmically spaced points and I need to calculate the #points-per-decade for the points. Based on this section from wikipedia we have #decades = log10(start / stop). From this we should be able to calculate #points-per-decade as #points / #decades. However this does not give the right an...
My way of calculating #points-per-decade was incorrect So based on the last equation in the calculations section of the wikipedia article we have: step-size = 10^(1 / #points-per-decade) since we know the step-size we can re-arrange to 1/#points-per-decade * ln(10)=ln(step-size) and finally solve for #points-per-decade...
67,978,118
67,978,334
Random ID generator and check if it allready registered
I'm trying to create a random ID generator, my problem is I don't know how to check if it already exists. I have a std::vector which I use to store the IDs (Client is my class): vector <Client> registeredIDs; The function for the ID generator is this: string Client::GenerateID() { srand(time(NULL)); string dig...
Your CheckID() function is fine, though because it returns a bool, you should be returning true/false rather than 1/0. But, your GenerateID() function has several issues: You are calling srand() to re-seed the RNG each time GenerateID() is called. That means every time GenerateID() is called within a 1-second period ...
67,978,595
67,979,557
How do I add linker commands to Microsoft Visual Studio project?
I am writing a short program that uses the MPIR (Multiple Precision Integers and Rationals) library. In the manual it states that your program must link against the following library, and that the command would look something like this on a typical Unix system: g++ mycxxprog.cc -lmpirxx -lmpir How do I do this for Mic...
I suggest you could follow the following steps: 1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Directories) 2,Add the path to the .lib file to the Additional Library Directories (property -> linker -> General -> Additional Library Directories) ...
67,978,940
67,980,315
Find the character at the `k`th location in the infinite string
I am trying to solve a problem: Given two strings, s and t, we can form a string x of infinite length, as: a. Append s to x 1 time; b. Append t to x 2 times; c. Append s to x 3 times; d. Append t to x 4 times; and so on... Given k, find the kth character (1 indexed) in the resultant infinite string x. For e.g., if s =...
The string looks like sttsssttttsssssttttttssssssstttttttt... Group the string into substrings like (stts)(ssttttss)(sssttttttsss)(ssssttttttttssss)(sssss... Let len(s) = a len(t) = b len(s+t) = c Group 1: stts -> length = 2*c. Group 2: ssttttss -> length = 4*c. Group 3: sssttttttsss -> length = 6*c. Continuing the ...
67,979,228
67,979,333
In C++, does initializing a global variable with itself have undefined behaviour?
int i = i; int main() { int a = a; return 0; } int a = a surely has undefined behaviour (UB), and more details on it is in Is reading an uninitialized value always an undefined behaviour? Or are there exceptions to it?. But what about int i = i? In C++ we are allowed to assign nonconstant values to globals. i is...
Surprisingly, this is not undefined behavior. Static initialization [basic.start.static] Constant initialization is performed if a variable or temporary object with static or thread storage duration is constant-initialized. If constant initialization is not performed, a variable with static storage duration or thread ...