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
69,124,964
69,125,070
Deep Copy of an Object that contains a Pointer to Pointers
I am trying to make a copy constructor for an Object that contains a pointer, that pointer refers to other pointers etc. The following code is a Binary Tree. BTree.h { public: vertex* root; BTree() { root = NULL; }; ~BTree() { delete root; root = nullptr; }; BTree(...
I don't have time to check your complete code. But the root = new vertex(*p_BTree.root); in your copy constructor would be a problem if root is nullptr. And your vertex manages resources (it has a delete in the destructor), but does not follow the rule of three/five. So as soon as a copy of an instance of vertex is cre...
69,125,886
69,126,056
Unexpected Behavior With Pthread, Barriers, and Sharing Array
I have a program which uses MPI + Pthread. I'm stuck on implementing pthreads to share an array for read/writes. I made mock code here, which mimics the issue. #include <iostream> #include <unistd.h> #include <pthread.h> struct args { double* array; int start; int stop; double myVal; double* row;...
In your loop, you create a struct args object, and then you pass the address of this object to pthread_create. The object is then immediately "destroyed" at the end of the loop iteration, and a new one is created at the next iteration, however, the newly created thread still has a reference to this old "destroyed" obje...
69,126,138
69,127,287
does `sizeof(std::max_align_t)` have actual meaning?
C++ introduces std::max_align_t as std::max_align_t is a trivial standard-layout type whose alignment requirement is at least as strict (as large) as that of every scalar type. (from http://en.cppreference.com/w/cpp/types/max_align_t) but without saying about the size of it. (I also checked c++ draft). But both gcc a...
Every type has a size, and that size must be at least its alignment (and will be a multiple of its alignment, just like any type). Therefore, sizeof(max_align_t) will be no smaller than alignof(max_align_t). Exactly what this size will be beyond that is not specified and ultimately means nothing. The cppreference page ...
69,126,159
69,126,330
Error: anonymous function String & type of reference can't bind to const string type of initial value
Operation void CServiceList::GetAllState(string & retStateString) { for_each ( m_servicemap.begin(), m_servicemap.end(), [retStateString](const pair<string, CService*> & x) { CService* instance = x.second; instance->GetServerState(retStateString);//Error red line ...
I don't think you understand what you are doing or what is the issue. In first, you capture the string by copy. Since the lambda's operator () is always marked const the captured string cannot be passes by reference. Only by const reference or pass a copy. Were you to capture the string by reference [&retStateString] t...
69,126,478
69,126,600
Confusion with C++20 concepts: constructible_from constraint on member type
(Question arises from toying with concepts; don't take this to be a consequential engineering choice or anything.) I'm trying to specify that a type satisfying a concept must have a member type, and that member type must be constructible in a certain way. As a minimal example, it must be constructible from 3 integers. ...
The std::constructible_from in your requires clause will only check the validity of std::constructible_from and will not evaluate it, you should use extra requires to check: template <typename T> concept Foo = requires { typename T::TypeLikeThreeIntegers; requires std::constructible_from<typename T::TypeLikeThreeIn...
69,126,584
69,126,632
c++ compiler optimized out my bool check function
I found some wired results when I am doing JNI development. Here is my test code: #include <stdint.h> #include <iostream> #define JNI_FALSE 0 #define JNI_TRUE 1 typedef uint8_t jboolean; inline jboolean bool2jboolean( bool b ) { return b ? JNI_TRUE : JNI_FALSE; } void test(bool *b) { volatile jboolean t = ...
You intentionally lied to the compiler, telling it that the memory for a was a legal bool, even though C++ specifically says a bool can only be true or false. The compiler under high optimization realized that true was 1 and false was 0, matching the JNI_TRUE and JNI_FALSE respectively, so it could just copy the value ...
69,127,070
69,127,100
What do I need to fix? C++
The question goes as follows: Given integer suppliedSpoons, output: "Full bin" if the number of spoons is greater than 38 and less than or equal to 55. "Jumbo bin" if the number of spoons is greater than 103 and less than 115. "Not efficient to ship" otherwise. I have the following code: #include <iostream> using name...
You need to add else if instead of if second time. like this #include <iostream> using namespace std; int main() { int suppliedSpoons; cin >> suppliedSpoons; if((suppliedSpoons > 38) && (suppliedSpoons <= 55)){ cout << "Full bin\n"; } else if((suppliedSpoons > 103) && (suppliedSpoons <...
69,127,127
69,127,147
C++ Check whether the user input is float or not
I just wanna check if the user input is float or not, if the user input a string then i want them to do certain action, it can be done with integer, but when i change it into float. it will give a message. error: invalid operands of types 'bool' and 'float' to binary 'operator>>'| so this is my code down below. #inclu...
The unary operator ! has a higher precedence than >>, so the expression !std::cin >> num is parsed as (!std::cin) >> num which attempts to call operator>>(bool, float). No such overload is defined, hence the error. It looks like you meant to write !(std::cin >> num) Note that your code only "worked" when num was an...
69,127,792
69,127,893
Can you tell me if my implementation of Insertion Sort is correct? It's working but something feels fishy
It's working but my teacher didn't agreed. Said that my number of iterations will be more. But how?? void InsertionSort(int arr[], int size) { for (int i = 1; i < size; i++) { int flag = 1; int val = arr[i]; for(int j = i-1; j>=0; j--) //keep swapping till i...
Either at least change this code snippet if(val < arr[j]) { int temp = arr[j]; arr[j] = val; arr[i] = temp; i--; //decrementing i so we keep going left until the condition is false flag = 0; } the following way if(val < arr[j]) { int temp = arr[j]; arr[j] = val; arr[j+1] = temp; ...
69,127,956
69,128,319
Statically stored set of strings
I have some string comparison logic in my program, e.g: std::unordered_set<std::string> relational_operators{ "==", "!=", ">", "<", ">=", "<=" }; bool is_relational(std::string token) { relational_operators.contains(token); } if (is_relational(token)) { // ...do stuff } All values of set ...
Give that you're apparently not planning to modify the set of strings at run-time, I'd probably use an std::array<std::string, N> to hold them, then use std::binary_search to do the search. From a theoretical viewpoint, you get O(log N) lookups either way--but in reality, the array is likely to give enough better cache...
69,127,974
69,128,027
Why is std::max not working for string literals?
I am trying to find the maximum of two strings and it is giving me the correct answer in the first case (when passing std::string variables) but giving an error in the second case (when passing direct strings). #include<bits/stdc++.h> using namespace std; int main() { // Case 1 string str1 = "abc", str2 = "abc...
In your second case, std::cout << std::max("abc", "abcd") << std::endl; they are string literals, in which "abc" has type char const [4] and "abcd" has type char const [5]. Therefore, in the function call std::max("abc", "abcd"), the std::max has to deduce auto max(char const (&a)[4], char const (&b)[5]) { return ...
69,128,457
69,128,852
Can I create multiple constructors with the same arguments
Im new to C++ and I am curious to know if you can create multiple constructors with the same arguments. Say for example I have this class in which I have patients and I have their name and their age. I know I can create a constructor like this: class hospital { hospital(){ setname("John"); setage(24); } p...
In your problem you have two concepts, which you are trying to mix. hospitals and patients. So it makes sense to model them as two distinct classes. This way you can model a patient as something that has an age and a name. And a hospital as something that "contains" patients. Give the patient a contructor where you can...
69,128,914
69,129,181
Is possible to print variables values to Debug without specifying their types?
I'm printing the value of variables to DebugView. There is any 'easier' way to print their value other than manually specifying the % VarTYPE Currently doing it this way: WCHAR wsText[255] = L""; wsprintf(wsText, L"dwExStyle: %??? lpClassName: %??? lpWindowName: %??? ...", dwExStyle, lpClassName, lpWindowName, dwStyle,...
Yes use string streams, they're more safe then wsprintf too (buffer overruns). And for unknown types you can overload operator <<. #include <Windows.h> #include <string> #include <sstream> int main() { DWORD dwExStyle{ 0 }; std::wstringstream wss; wss << L"dwExtStyle : " << dwExStyle << ", lpClassName: "; ...
69,129,785
69,129,978
Virtual destructor makes it necessary to export the interface on VS2017
I have a C++ interface, let's call it IX with a few methods: class IX { public: virtual void foo() = 0; virtual void bar() = 0; } this interface is located inside a library (dll), but considering the fact that it includes no implementation, it has not been exported. But, If I want to add a virtual destructor to ...
Making something pure virtual doesn't mean it doesn't have an implementation. Its totally legal (and sometimes useful) to have an implementation of a pure virtual function. In the case of foo() = 0; you dont explicitly call IX::foo() anywhere, so not having an implementation is ok. It cant be implicitly called as it'l...
69,129,870
69,130,819
Cannot push value at priority_queue in the allocated instance
Can anyone explain below code's problem? Thanks #include <queue> #include <stdlib.h> using namespace std; struct Person { priority_queue<int> pq; }; int main(void) { Person* person = (Person*)malloc(sizeof(Person)); person->pq.push(1);// error here return 0; }
Don't use malloc in C++ (as stated above it will only allocate memory), avoid new and delete if you can. #include <queue> //#include <stdlib.h> <== do not include in C++ #include <memory> struct Person { std::priority_queue<int> pq; }; int main(void) { Person* person_ptr = new Person(); person_ptr->pq....
69,129,948
69,130,027
Why vector push_back call twice in C++?
In the following program, I have created 3 object of class Person and pushed that object into vector container. After that, the display function is called using a range based for loop and printing the name and age. #include <iostream> #include <vector> #include <iterator> #include <functional> using namespace std; ...
When you define the vector: vector<Person> per(3); you set the size to 3, which means three default-constructed elements will be created and added to the vector. You then add three more, so you have a total of six elements in the vector. If you only want your three elements there are a few alternatives: Reserve the m...
69,130,349
69,132,036
Achieving the effect of 'volatile' without the added MOV* instructions?
I have a piece of code that must run under all circumstances, as it modifies things outside of its own scope. Let's define that piece of code as: // Extremely simplified C++ as an example. #include <iostream> #include <map> #include <cstdint> #if defined(__GNUC__) || defined(__GNUG__) || defined(__clang__) #include <x8...
Inasmuch as you assert in comments that you are most interested in a narrow answer to the question ... Is there a way to achieve the effect of volatile, without the MOV instructions of volatile? ... the only thing we can say is that C and C++ do not specify the involvement of MOV or any other specific assembly instru...
69,130,383
69,130,576
Passing constructor with parameters to another constructor as argument
I have a struct Point, which has a constructor with parameters and a class called Circle. struct Point{ int x, y; Point(){} Point(int ox, int oy) : x(ox),y(oy){} }; class Circle{ public: Point obj; int radius; Circle(Point pt(int ox, int oy), int raza) : obj.x(ox), obj.y(oy), radius(raza) {...
You can do that like this : class Point { public: Point(int x, int y) : m_x(x), m_y(y) { } private: int m_x{ 0 }; int m_y{ 0 }; }; class Circle { public: Circle(const Point& pt, int raza) : m_point{ pt }, m_radius{ raza } { } private: Point m_point...
69,130,396
69,136,032
UE4 using a Function as parameter with it's own parameters, C++
I am trying to set a timer, and use a function with in. I read the timer documentation and figured out how it works. You setting a timer with a timer_handler and a function to execute. Here's the problem. I can only give function without parameters. GetWorldTimerManager().SetTimer(timer_handle1, this, &actor_class:Foo,...
Use the overload of SetTimer that takes in a lambda. Then call your function with parameters inside the lambda. GetWorld()->GetTimerManager().SetTimer( timer_handle1, [&]() { this->Foo(123); }, 2.f, false, 1.f);
69,130,991
69,131,051
Can enclosing class access nested class?
I have the following code: #include <iostream> #include <string> class enclose { private: int x; public: enclose(void) { x = 10; }; ~enclose(void) { }; class nested1 { public: void printnumber(enclose p); }; }; void enclose::neste...
Can enclosing class access nested class? Yes, if the enclosing class have an instance (an object) of the nested class. A class is a class is a class... Nesting doesn't matter, you must always have an instance of the class to be able to call a (non-static) member function.
69,131,054
69,131,332
SFINAE doesn't pick the right overload resolution
I am trying to solve a relatively easy excursive involving SFINAE. My goal is to find best way of sorting for particular type T. There are 3 cases for me: 1. type T supports `sort` function 2. type T supports range i.e. have begin and end functions (lets not include comparability at this point) 3. type T is not s...
Actually SFINAE apply to all of your types: A doesn't have sort()/begin()/end() B doesn't have begin()/end() and doesn't have public sort(). std::vector<int> doesn't have sort(), and &std::vector<int>::begin (similar for end) is ambiguous, as there are several overloads (const and non-const method). I would do someth...
69,131,148
69,131,183
Accessing an instance of a class defined in main in another class
The problem i've been facing is related to accessing an instance of a class, I'll explain it through a series of code snipets: If I have a class Foo defined as defined below: class Foo { public: Foo(){x=5} private: int x; } And I create an instance of that object in main as follows: int main(){ Foo a; } I the...
The most natural way would be to pass the Foo object as an argument to the Bar constructor: Bar(Foo a) { std::cout << a.x << '\n'; } For the updated question, I might pass the object as a constant reference instead of by value: Bar(Foo const& a) : copy{ a } { } This will initialize the member variable copy t...
69,131,825
69,131,878
getting invalid ouput after std::move of an element from std::list
I'm trying to understand about std::move. In my code I'm moving an element from std::list<struct Data> where struct Data internally contains two std::string fields, but I'm not getting expected output. This is my code: #include <iostream> #include <string> #include <list> struct Data { std::string topic {}; st...
The issue here is you are not actually moving anything. When you call std::move, nothing is actually moved. What it does do is converts the lvalue that you have into an rvalue, so that it can then be move constructed or move assigned from. That's not what you are doing here though. You use Data&& d1 = std::move(dat...
69,131,918
69,132,705
Boost undefined symbol when building .so library with CMake
I'm building a shared library (.so) on Linux with CMake which uses Boost 1.75.0. In CMakeLists.txt, Boost is added the following way: find_package(Boost REQUIRED COMPONENTS system chrono filesystem date_time log iostreams program_options) and added to the target: target_link_libraries(mytarget PUBLIC ${Boost_LIBRARIES...
Enabling INTERPROCEDURAL_OPTIMIZATION in CMake solved the problem: set_target_properties(mytarget PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE) Now, the symbol is properly linked: $ nm -g libmytarget.so | grep filesystem_error4what 00000000001cfe22 T _ZNK5boost10filesystem16filesystem_error4whatEv But I still don't k...
69,131,981
69,133,855
OpenMP reduction: min gives incorrect result
I want to use an OpenMP reduction in a parallel region, outside a for loop. According to the OpenMP reference, reduction clauses can be used in parallel regions, so no for loop or sections should be necessary. However, when using an OpenMP reduction (min:...) in a parallel region, I'm getting incorrect results. If I us...
You're using a feature that is not yet supported by the compiler. If you compile your code with -Wall you will see that GCC 10.3.0 shows this warning: red.cc:15: warning: ignoring ‘#pragma omp reduction’ [-Wunknown-pragmas] 15 | #pragma omp reduction (min:minVar) | red.cc:24: warning: ignoring ‘#pragm...
69,132,133
69,132,823
No matching function for call to ‘student::student()’ error
What is wrong with the following code with respect to inheritance? Getting no matching function for call to ‘student::student()’ error. class student { private: string firstname; string lastname; public: student(string fname, string lname) { firstname = fname; lastname = lname; } string getname() {...
It looks like you might be a Python programmer, so here is your code, re-written in that langage class student: def __init__(self, fname, lname): self.firstname = fname; self.lastname = lname; @property def name(self): return self.firstname + self.lastname class undergraduate(stude...
69,132,181
69,132,255
How to validate the input in vector
I tried to validate the user input using a vector in c++. I almost searched for a possible solution but I can't find the solution. #include <iostream> #include <cstdlib> #include <vector> using namespace std; int main() { std::vector<int> selectFloor = {}; int maxfloor, currentfloor = 1, select, i, k, inputFlo...
if(selectFloor.begin(),selectFloor.end(),inputFloor) This if condition is an expression with two comma operators where each operand is evaluated from left to right and each except the last one is discarded. Since the first two operands don't have side effects their evaluation does nothing and the above is equivalent ...
69,132,291
69,132,691
How to print whole stack in C++ in without popping out elements and without loop?
in Java we can print a stack like Stack<Integer> s = new Stack<>(); System.out.print(s); How to do the same in C++, without popping element and without a loop?
std::stack doesn't have any public function to let you iterate over it. But std::stack use std::deque as it's data structure: GCC: https://code.woboq.org/gcc/libstdc++-v3/include/bits/stl_stack.h.html#98 MSVC: https://github.com/microsoft/STL/blob/main/stl/inc/stack#L21 Clang: https://github.com/llvm/llvm-proje...
69,133,024
69,133,146
Program crash in wstringstream
My program is crashing in the wstringstream line, I think it's because sometimes it searches for a msg that doesn't exist inside of wmTranslation, how I could 'fix' this? const char* TranslateMessage(int Msg) { static std::map<int, const char*> wmTranslation = { {0, "WM_NULL" }, {1, "WM_CREATE" }, ...
Looking up a key that doesn't exist adds an entry for the key, with a default value (the null pointer in your case). Check if the key exists first, then return the relevant value. const char* TranslateMessage(int Msg) { static std::map<int, const char*> wmTranslation = { {0, "WM_NULL" }, {1, "WM_CRE...
69,133,254
69,133,441
Does LLVM have a tool for demangling Microsoft C++ mangling?
I use LLVM on windows and I wonder if there is a command line tool to demangle MSVC C++ mangling. I am talking about command line tool like llvm-cxxfilt. I see some commits in LLVM, but not sure if those are exposed as some tool or it is just C++ API. I tried looking for llvm-undname mentioned in those commits in my LL...
Visual Studio comes with a command line tool called undname.exe which will undecorate (demangle) the name. q.v. https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-160
69,133,877
72,473,944
How to build a cross-platform C++ library in Windows and Linux
I am a Linux user and a beginner in C++. I am developing a small library with the following structure src main.cpp makefile include Inputs.h GenerateTabValues.h Prototypes.h data TabNodes.csv TabWeights.csv output test1 Results.txt test2 ... In Linux I usually compile C++ using gcc and, when I have mul...
Use either MSVC or MinGW-w64, and make sure not to mix them. But if you come from a Linux world you should stick with MinGW-w64 and maybe even consider MSYS2 which gives you a bash shell. Check out my a minimal example for a cross-platform library here: https://github.com/brechtsanders/ci-test That project has both Mak...
69,134,101
69,134,971
How to call setProcessMitigationPolicy using JNA
I'm trying to convert this piece of C++ code into Java code via JNA: PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY signaturePolicy = {}; signaturePolicy.MicrosoftSignedOnly = true; SetProcessMitigationPolicy(ProcessSignaturePolicy, &signaturePolicy, sizeof(signaturePolicy)); I already have the function SetProcessMitigati...
The SetProcessMitigationPolicy function has three arguments. BOOL SetProcessMitigationPolicy( PROCESS_MITIGATION_POLICY MitigationPolicy, PVOID lpBuffer, SIZE_T dwLength ); The first argument is a PROCESS_MITIGATION_POLICY enumeration. This is a simple integer (starting at...
69,134,285
69,134,464
How to convert uint16_t number to ASCII HEX?
What is the best way to convert a unsigned 16 bit integer into ASCII HEX? I'm trying to integrate my Arduino with a serial communication protocol that expects the payload as an array of 2 byte ASCII HEX values. I'd like to be able to store each character of the HEX representation in a char array since the full message ...
static const char *digits = "0123456789ABCDEF"; char *toHex(char *buff, uint16_t val, int withNULL) { buff[0] = digits[(val >> 12)]; buff[1] = digits[((val >> 8) & 0xf)]; buff[2] = digits[((val >> 4) & 0xf)]; buff[3] = digits[(val & 0xf)]; if(withNULL) buff[4] = 0; return buff; } char *toHex1(...
69,134,439
69,134,596
Difficulty in passing function pointer of a class member function
In trying to implement a suggested answer here in my own context, I am running into a compilation error. Consider code: #include <iostream> class SIMPLE { public: SIMPLE() { for (int i = 0; i < 5; i++) val[i] = 5; }; int retval(int index) { return val[index]; } private: int val[5]; }; void print_array_of_...
You can't pass a non-static member function pointer as a regular function pointer. Member functions have access to the this pointer, and the way they get that is via an invisible implicit function parameter. You need to have the object on which to call the function, and the function itself, be bound together, which a...
69,134,656
69,135,234
Reducing the time complexity of recursive Fibonacci like function in c++
I have been trying to code a solution for a problem in c++. This has to be solved using recursion only The modulo 10000000007 is not the issue the code takes longer with/without it The problem: Davis likes to climb each staircase 1, 2, or 3 steps at a time. Given the respective heights for each of the n staircases, fin...
You can start adding memoization, to avoid most of the recursive calls. long long ways(long long n) { // Memoization requires to store the previously calculated values. static std::map<long long, long long> mem{ {1, 1}, {2, 2}, {3, 4} }; // I'm using std::map, but I don't want to use operator[]...
69,134,667
69,136,250
How to assign a reference to a shared pointer to another shared pointer
I am refactoring some code which uses raw pointers to use shared pointers instead. In the original code, there is a raw pointer to a list object, let's call it EntityList I have typedefed a shared pointer to an EntityList in the EntityList.h file, as follows: using EntityList_ptr = std::shared_ptr<EntityList>; In the ...
Just as you replaced EntityList* with EntityList_ptr elsewhere in your code, you can do the exact same thing here. EntityList** would simply become EntityList_ptr*, eg: setList (int type) { EntityList_ptr* list; if (type == 0) { list = &typeZeroList; } else if (type ==1) { list = &typeOneLi...
69,135,271
69,136,151
Binary search in an array works after rewriting it in the exact same way
I'm performing a binary search in an array, looking for a specific value inside of it. When I wrote the code the first time, my for loop for sorting the array in ascending order always added a 0 right in the middle of it so that I could not search for the last element of the array, since the middle part got now replace...
Don’t write using namespace std;. You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc. (See SF.7.) int Temp, Size, Low = 0, High, Mid, Key, Found = 0; Don't declare variables before they are ready to be initialized. Don't gang together multiple variable declarations...
69,135,645
69,135,711
Do function templates have a lower priority than functions of the same resolved type?
This is closely related to my previous question, but I thought it distinct enough to warrant another post. This is a fairly pure form of the ambiguity to which I am referencing: template<typename T> class Class { public: Class() = default; template<typename U> Class(Class<U> &) {} }; This class has two po...
When you have a template specialization and a regular function, the regular function is considered better then the specialization if everything else is equal (same signature). This is covered in [over.match.best.general]/2 Given these definitions, a viable function F 1 is defined to be a better function than another ...
69,136,086
69,146,300
Expected ambiguity error on clang is not present
This needs little explanation, but I'm expecting to get an ambiguity error from the following C++ code, however my compiler gives me different results that are apparently not part of the standard. Environment: Windows Clang++ version 12.0.0 Clang++ target = x86_64-pc-windows-msvc #include <iostream> void print(int x...
Turned out I had to add -fno-ms-compatibility to my clang compiler flags to switch off MSVC compatibility.
69,136,319
69,136,491
Unknown Error after building dlib for c++ properly, while importing it
Hi after successfully building dlib for c++ flowing this video https://www.youtube.com/watch?v=BKGkA_K1KPA&list=WL&index=2&t=148s I created the Debug part of it and then created my cpp file with just this line: #include <dlib/image_processing.h> on running it, I got this error.. Can someone pls help... 1>Test.cpp 1>C:\...
Test.obj : error LNK2001: unresolved external symbol USER_ERROR__missing_dlib_all_source_cpp_file__OR__inconsistent_use_of_DEBUG_or_ENABLE_ASSERTS_preprocessor_directives I'm guessing that there's some tricks in the library to generate an error message whose symbol name reads as the desired error string, which is "mi...
69,136,795
69,137,145
Overloading comparison operators for result types of three-way comparison operators
In C++20 we got a new three-way comparison operator <=> , which typically returns std::strong_ordering or std::partial_ordering types. And if class A has operator <=>, then the comparison of its objects a1 < a2 is interpreted as (a1 <=> a2) < 0. But can the user overload comparison operators, taking the first argument ...
The standard doesn't say anything about the unspecified type in strong_ordering's comparisons, other than that it accepts the literal 0 exactly (and using anything else is undefined). In particular, it doesn't specify the kind of implicit conversion sequence involved in converting the literal 0 to the parameter's type....
69,137,002
69,137,855
C++ wrapper for bound member function on resource constrained MCU
I am trying to implement a pointer to member function wrapper where the return type and parameter types are known but the class type of the member function is not known. This is for a C++ project targeting resource constrained (No heap allocation/c++ standard library) microprocessor. The following code seems to work (y...
A simple, compiler-independent solution: template <typename Signature> struct member_cb; template <typename Ret, typename... Args> struct member_cb<Ret(Args...)> { template <typename T, Ret (T::*func)(Args...)> static Ret wrapper(void *object, Args&&... args) { T *o = reinterpret_cast<T *>(object); ...
69,137,577
69,138,302
Registry query information gives incorrect values
With the code bellow i have been trying to query value information under a certain registry key. I'm just interested in the amount of values, value name length and value size. But when i run the code it only gives the correct value for number of values. The other values are too long and incorrect. If i lengthen the val...
The lpcbMaxValueLen parameter outputs the size of the longest data expressed in bytes. The longest data in your example is Hello, which as a Unicode string (the format the Registry internally stores strings in) is 6 characters, counting the null terminator, and so is 12 bytes in size (2 bytes per character). So maxVa...
69,137,688
69,138,476
Range-v3: How to use actions::insert with a map
I've seen this example question on how to use ranges::actions::insert with a vector but I couldn't get it working with a map container. Would someone show me how to use it in this case, please? I'm trying, using the ranges actions::insert function to insert all the elements of map m into map r. This is not the final re...
There are several things wrong here. // This line effectively makes a copy of m into v. // This is not the final required opertation but it does prove the insert syntax. auto v = m | ranges::actions::insert(r, r.end(), push_r); You cannot pipe into ranges::actions::insert. ranges::actions::insert returns the result ...
69,137,789
69,137,985
Cannot initialize object with returning value of a function.. Why?
I wrote this simple code to understand the functionality of copy constructor in c++. When I initialize "obj2" with "obj1" directly it is working fine. But when I try to initialize "obj2" with the returning object from the function "func()" it is showing an error: error: cannot bind non-const lvalue reference of type '...
You have defined this constructor: MyInt(MyInt& obj) { this->x = obj.x; cout<< "copy constructor called" << endl; } The parameter MyInt& obj is a reference, and it is not const. This indicates that you wish to be able to both read from it and write to it. C++ will protect you from certain mistakes by not allow...
69,138,092
69,138,112
Why isn't sizeof() printing 16 bytes instead of 8?
Pretty simple program, I'm just testing the sizeof() function and trying to see if it works. If sizeof() really does return things in terms of bits, when I had these two elements, shouldn't it return 16 instead of 8? Since long long is 8 bytes in C++ and I have two elements? int main() { long long whatever[] = {0}...
This is undefined behavior long long whatever[] = {0}; std::cout << whatever[0] << std::endl; whatever[2] = 10; // BAD The code statically initializes whatever as an array of one element. Then you assign a value to whatever[2]. The only valid index in that array is 0. Assigning anything to index 1 or 2 overwrites t...
69,138,352
69,214,679
Qt QMessageBox show buttons without color
I've created an QMessageBox with customized buttons and they are showing up in gray as the image bellow: Running on Linux is fine! But on Raspberry it gives me in trouble. The snippet of code that I wrote is the following: #include "alertmessage.h" #include <QDebug> #include <QAbstractButton> #include <QCoreApplicati...
I solved it, each OS has some default styles and Qt will search for they to look more "native". Taking that into account I need to force my application to take a Style different from the raspberry standards styles. The snipe of code that solved that: QApplication app(argc, argv); qDebug() << QStyleFactory::keys(); //S...
69,138,921
69,139,279
C++ Inheritance & Virtual Functions Where Base Parameters require Replacement with Derived Ones
I have looked high and low for answers to this question - here on this forum and on the general internet. While I have found posts discussing similar topics, I am at a point where I need to make some design choices and am wondering if I am going about it the right way, which is as follows: In C++ I have created 3 data ...
The LSP means operations on a reference to base class must work and have the same semantics as operations on both base and derived class instances when those operations are referentially polymorphic. Your example fails this test. The base isGreaterThan claims to work on all dataStructure, but it does not. I would make...
69,139,163
69,140,588
How can I display two shapes instead of one by using C++ OpenGL Glut?
I started to use OpenGL / glut for C++ and I am stuck on being able to display two objects in the window rather than one. So, for the first shape it draws a house-like shape with a square and triangle on the top, with anti-aliasing. The second shape, is supposed to be the same, but does not have anti-aliasing. For now,...
If you want to draw lines, you must use Line primitives instead of Point primitives. The first mesh is not displayed because you clear the framebuffer before drawing the second mesh. Move glClear and glFlush in the render function and use the primitive type GL_LINE_LOOP: void withAntiAliasing() { glEnable(GL_LINE_S...
69,139,365
69,146,151
Build error in building of a project has the INET reference
I want to simulate a project including the INET reference, but the following error has generated. How to fix it? . . . Creating executable: ../out/clang-debug/src/D2DCommunication_dbg /usr/bin/ld: cannot find -lINET_dbg clang: error: linker command failed with exit code 1 (use -v to see invocation) make[1]: *** [../out...
It seems that you have built INET in release mode, while the project referenced to INET is built in debug mode. However, both projects must be built in the same mode. Assuming that you need debug mode, in Eclipse right click in INET, chose Build Configurations, then Set Active and select gcc-debug or debug.
69,139,519
69,154,754
Communication link in radio Medium with OMNET++ and INET
In a Wireless environment and according to the wireless communication principle, the data is broadcasted to every node and only the designated node receives it. All other nodes ignore the data. (See the picture below) Picture : WSN communication But for a particular needs, I want to hide all others data transmission li...
To be precise: all nodes receive the packet in the communication range but only the destination node is passing it up from the link layer to the network layer. The rest of the nodes are receiving it also, but they are dropping it in the link layer. What you are after is to visualize communication on link layer (as oppo...
69,139,801
69,162,291
How do I use OCIEnvNlsCreate() to always get CHAR and NCHAR data back in UTF8 encoding?
Currently I'm using OCIEnvCreate() to create an OCI session handle to communicate with Oracle databases. I'd like to explicitly use UTF8 rather than relying on whatever client locale has been set, and I gather that I need to use OCIEnvNlsCreate() to do this. But there's something I don't understand. Here's the signatur...
Either try to call setenv() in C++ code before calling OCIEnvCreate(). Or check Metalink NOTE.93358.1 SCRIPT: Where to Find Specifications of Character Encoding: Create the "dectohex" function first by referencing the above Note:67533.1 prior to running the query below. set pages 1000 col nls_charset_id for 9999 col h...
69,140,157
69,141,080
print each char of string array with double pointer in C++
The program is expected to print each char of the string array. #include <iostream> #include <string> using namespace std; int main() { const char* numbers[10]{"One", "Too", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Zero"}; /* This version did not work. Why? for ...
Two things - First, in this loop expression, you don't need to dereference the ptr after incrementing it - *ptr++. for (const char** ptr = numbers; *ptr != nullptr; *ptr++) ^^ *ptr++ will be grouped as - *(ptr++), which means, (post)increment the ptr and dereference th...
69,140,185
69,140,248
Behavior of std::cin on failure
New to C++ and I was checking the behavior of cin on unexpected inputs and wrote the following code #include <iostream> using std::cout; using std::endl; using std::cin; int main() { int num = -1; cin >> num; cout << num << "\n"; char alph = 'z'; cin >> alph; cout << alph << "\n"; ...
The very link you cited explains what's happening: https://www.learncpp.com/cpp-tutorial/stdcin-and-handling-invalid-input/ When the user enters input in response to an extraction operation, that data is placed in a buffer inside of std::cin. When the extraction operator is used, the following procedure happens: If t...
69,140,292
69,140,791
Declaring template functions with dependent types of arguments in C++20
In C++20, a template function can be declared in a simplified way using auto keyword and omitting template<class T> prefix. But if the second/third/… argument type of a template function depends on the first template argument type, is the declaration with auto equivalent? Consider an old-style template example: templat...
Yes, this is an MSVC bug, but g and f are not the same here because g deduces only from its first argument (which may or may not be what you want).
69,140,368
69,140,596
C++ Stop while loop at the end of the line (enter Key)
Task: Create program to read given text file and print into another text file all lines containing given substring. Reading from files should be carried out line per line. My code: #include <bits/stdc++.h> #include <iostream> #include <fstream> using namespace std; int main(){ fstream file; // required for input f...
The issue is that you are reading word by word. A stream uses "\n" as a token seperater. Hence it is ignored during word reading. Use getline standard function to get a line. #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; int main(){ string inputFileName = "inputF...
69,140,443
69,140,812
Why WOL(WakeOnLan) Is Releated To Operating System?
Wikipedia says: Wake-on-LAN (WoL) is an Ethernet or Token Ring computer networking standard that allows a computer to be turned on or awakened by a network message. But, in another section: Responding to the magic packet ... Most WoL hardware functionally is typically blocked by default and needs to be enabled in us...
The OS is involved only to the extent that there's not a standardized way to enable WoL for all hardware. Therefore, you typically need a device driver for the specific hardware to be able to enable the hardware's capability. Loading the OS usually gives you such a device driver. Running ethtool every startup should be...
69,140,599
69,140,678
OpenGL clips an object for no apparent reason
I'm trying to visualize a simple quad made of -1 to 1 vertices along x and y axis. Why opengl clips the object? The code seems correct to me glm::mat4 m = glm::translate(glm::mat4{1.0f}, toGlmVec3(objectPosition)); glm::mat4 v = glm::lookAtLH(toGlmVec3(cameraPosition), toGlmVec3(objectPosition), glm::vec3(0, 1, 0)); gl...
The object is clipped by the near and far plane of the Orthographic projection. If you don't explicitly set an projection matrix, the projection matrix is the Identity matrix. The near plane far pane are at +/- 1. Use glm::ortho to define a different projection matrix. e.g.: glm::mat4 p = glm::ortho(-1, 1, -1, 1, -10, ...
69,140,621
69,140,939
What's the difference between vector<vector<int>> vec and vector<vector<int>> vec(n)?
I was trying to access vector elements today, so when I used vector<vector<int>> vec and then added elements to it. I was able to access those elements like vec[1][2]. But when I use vector<vector<int>> vec(n) and then added elements, I was not able to access the elements using vec[1][2]. I keep getting a segmentation ...
I think I can guess what the problems is... When you use the constructor with an argument: vector<vector<int>> vh(n); you create a vector with the size n, it means it will already have n elements, where each element will be a default-constructed vector<int>. Which means that each vector will be empty. Then you push ba...
69,140,785
69,140,816
Storing local char array vs. raw string literal as class member
Let's say I've got this simple code: class Foo { private: const char* str; public: void Set(const char* c) { str = c; } const char* Get() const { return str; } }; Foo f; void func1() { // Please note: Comments of the answer below refer to const char* localStr. // I posted the wrong code. cons...
But what is happening with f.Set("Hello world!");? String literals have static storage duration. Storing char array as class member To be clear, the member of your class is not an array. It is a pointer. const char* localStr = "Hello world!"; //f.Set(localStr); // Of course, does not work, std::cout prints ga...
69,140,786
69,140,852
Why didn't initialization call the assignment operator
See the following codes #include <iostream> #include <vector> #include <list> using namespace std; struct X { X() { std::cout << "X() " << std::endl; } X(const X &) { std::cout << "X(const X &) " << std::endl; } X &operator=(const X &) { std::cout << "operator= "<< std::endl; return *this;} }; X f5() { X x; ...
When returning a temporary object that is immediately assigned to another object, the compiler is allowed to do an optimization called copy elision: https://en.cppreference.com/w/cpp/language/copy_elision. That avoids the extra construction.
69,141,971
69,142,359
How to query the number of completion handlers waiting on a strand in Boost ASIO?
Is there a simple way to determine the number of completion handlers waiting on a particular Boost ASIO strand? I am aware, that that number will only be approximate in a multithreaded environment, as it can always happen, that a completion handler finishes in the nanosecond just after that counter got queried, but bef...
There's no way for that. Keep in mind that strands are like hash buckets: queues can (and will) be shared among different strands beyond a reasonable number of unique strands. I think with executors I suspect one can easily make an executor that tracks the on_work_started/on_work_finished calls. I don't have an example...
69,142,174
69,142,250
Should std::apply only apply to std::tuple?
The function signature of std::apply does not constrain the template parameter Tuple to be a specialization of std::tuple, so it can still accept a tuple-like objects that defines std::tuple_size_v (godbolt): #include <tuple> #include <utility> #include <array> int main() { std::apply([](int, int) {}, std::array{0, ...
20.5.5 Calling a function with a tuple of arguments I highly doubt that the section titles are normative. The actual function is described as being equivalent to the reference implementation, which uses get and tuple_size_v to inspect the "tuple" parameter. Cppreference concurs.
69,142,495
69,142,673
While loop working perfectly in Insertion sort, but For loop is not working as expected in place of while loop
I tried using for loop, but it gives a wrong answer. When I used a while loop in its place the sorting is done as expected. Can someone help me debug? Note : It doesn't throw an compilation error, just gives a wrong ans when using for loop. And I have tried running on different IDE's and even tried dry running the for ...
Both are not equivalent, if you look at this: while (j >= 0 && arr[j] > element) { arr[j + 1] = arr[j]; j = j - 1; } It stops as soon as arr[j] > element. But this does not: for( ; j >= 0 ; j--) { if(arr[j] > element){ arr[j + 1] = arr[j]; } } As it continue t...
69,142,854
69,142,956
How to get persistent input in SDL2 c++
So I noticed that when getting input with SDL_GetKeyboardState(NULL), when holding a specific button, it is going to first write outlets say a, and after 1 second its gonna continue aaaaaaaa normally. I want to when I hold the button a that it automatically goes aaaaaa. Here is a video if you don't understand my poor e...
You're misusing SDL_GetKeyboardState(nullptr). It should be used in the main loop, not in the event loop: while (gameRunning) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) gameRunning = false; } const std::uint8_t *keystates = SDL_GetKeyboardState...
69,143,171
69,143,448
Is there a Windows Message for when any pixel in the window changes?
I'm trying to execute an action when a pixel changes in a window by using SetWindowsHookEx. I can successfully recieve Windows messages, but most messages are called while no screen updates occur, and some messages are called more than once on one pixel. // WH_GETMESSAGE doesn't call the callback for some reason... Set...
There is no message that notifies a client about the change of a pixel's color. This wouldn't really be useful either: Clients are in charge of drawing to the window's (client) area. If they need to know when a pixel changes color, it can monitor the state itself. If you need to monitor the change of a pixel's color in...
69,143,882
69,151,345
Why did one linked list's end node change from NULL to another list's next node?
The first function, linkAndMove, is used for basic linking together and moving point process. The Union function is used for finding all numbers in linked lists la and lb (without repeats) My test example: la {1,3} lb{3,5} But in the last when la point to NULL, and lb point to 5. After first function linkAndMove, the l...
I found the reason. Because in function linkAndMove, the pointer finNode is connected to the list la's node. In preivous codes, using node's next to connect pNode, so changed the la's end node from NULL to that node. The solution I found is create new node for list lc, that cannot infect the orignal data list la. Codes...
69,143,913
69,144,480
C++: Which weak atomic to use for buffers that receive async. RDMA transfers?
The Derecho system (open-source C++ library for data replication, distributed coordination, Paxos -- ultra-fast) is built around asynchronous RDMA networking primitives. Senders can write to receivers without pausing, using RDMA transfers into receiver memory. Typically this is done in two steps: we transfer the data...
An atomic counter, whatever its type, will not guarantee anything about memory not controlled by the CPU. Before the RDMA transfer starts, you need to ensure the CPU's caches for the RDMA region are flushed and invalidated, and then of course not read from or write to that region while the RDMA transfer is ongoing. Whe...
69,143,991
69,144,223
C++20 Formatter Template Redefinition Error
What I am trying to do: define two fmt::formatter templates, one for types that derive from std::exception and one for types that derive from std::array<char, N> so that I can pass these types as parameters to a logging function that uses fmt::format(). Problem: when I define only one of the formatter templates, everyt...
This: template<std::size_t arrayLen> template<typename T> concept CharArray = std::is_base_of_v<std::array<char, arrayLen>, T>; is not a valid declaration. I'm surprised the compiler does not flag that as being obviously ill-formed (reported as 102289). You only get one template head for a concept (the only place you ...
69,144,275
69,144,857
Visitor pattern for tree mutation and shared pointer problem
I'm trying to implement visitor pattern for n-ary tree mutation. Currently i'm stuck with shared pointers. Mutator operates on each tree node and can return either pointer to a node itself w/o any changes, or a pointer to a copy of modified node (original node cannot be modified directly). But obviously i can't build a...
As it is tagged C++20, I'd suggest to use std::variant and std::visit instead. Otherwise, you can inherit from std::enable_shared_from_this, which allows to create shared_ptr from within methods of X. You can also use mutate not to do the actual mutation, but to return appropriate function object that does the mutation...
69,144,529
69,165,633
Vulkan HPP with cmake
I'm trying to include vulkan hpp library using cmake with fetch_content (I want to automate this and I don't want the user to manually install vulkan, if this is a wrong approach let me know because I'm just starting with cmake) as shown in the following code snippet include(FetchContent) FetchContent_Declare( ...
The repository you specified does not actually contain the Vulkan headers. Use this instead. It provides a CMakeLists.txt file which adds the headers to a library called Vulkan::Headers so you can just add the subdirectory and then link to them using target_link_libraries(example PRIVATE Vulkan::Headers). But why would...
69,144,605
69,144,784
Ignore zero in std::min and calculate minimum of other numbers
Minimum of non-zero numbers: #include <iostream> #include <algorithm> int main() { double s1 = 1000; double s2 = 400; double s3 = 300; double s4 = 10; double minimum = std::min({s1, s2, s3, s4}); std::cout<<minimum<<"\n"; ...
The std::min works as it should work if you have special requirements, you could pass a compare function with the following signature: bool cmp(const Type1 &a, const Type2 &b); as the second std::min function argument (the Compare template parameter): #include <iostream> #include <algorithm> int main() { double s...
69,144,995
69,145,097
C++ Set Window Text issue
Ok, I have a file.txt which has this contents: xzline1\n xzline2\n When I run it, the window contains this: xzline1\nxzline2\n and not xzline1 xzline2 Not recognizing the \n new line characters, not sure why. My window is defined like this LPCWSTR recordin; HWND hEdit; hEdit = CreateWindow(TE...
Classic Windows common controls wants DOS line endings, \r\n. Convert all those \n chars to be \r\n. Probably can just do this as a quick hack: std::wstring stemp = s2ws(buffer.str()); // quick and dirty string copy with DOS to to unix conversions std::wstring stemp2; for (char ch : stemp) { if (ch == '\n') {...
69,145,457
69,145,536
Using this with array of pointer in class constructor c++
I tried to assign an array of pointer to nullptr. class ToyBox { private: Toy *toyBox[5]; int numberOfItems; public: ToyBox() { this->numberOfItems = 0; this->toyBox = {} } } An error throw at this in this->toyBox: expression must be a modifiable lvalueC/C++(137) Any suggestion to corrected?
You can only Initialize arrays in that way: Assign a single value to array. But in the constructor you could/must use Member Initialize List: class ToyBox { private: Toy *toyBox[5]; int numberOfItems; public: ToyBox() : toyBox{nullptr} , numberOfItems(0) { } }; With C++, It's better to use std::a...
69,145,522
69,145,954
Constexpr doesn't get evaluated when computed using const variable outside function
I present two code snippets, one of them compiles and the other doesn't. The one that doesn't compile: class Solution { public: const int MAX_NUM = 100; const int MAX_SIZE = 200; bool canPartition(vector<int>& nums) { bitset<(MAX_NUM*MAX_SIZE)/2 + 1> bits(1); int sum = 0; ...
The problem is that since Templates are evaluated at compile time, their arguments cannot be anything that the compiler can't "predict". In your first code the member variables MAX_NUM and MAX_SIZE are const values, meaning they cannot be changed after an instance of the class Solution is made and they are initialized....
69,145,688
69,151,508
Is the value representation of integral types implementation-defined or unspecified?
To quote from N4868 6.8.2 paragraph 5: Each value x of an unsigned integer type with width N has a unique representation... Notably, it avoids specifying "value representation" or "object representation," so it's not clear if either is intended here. Later on (in the index of implementation-defined behavior), N4868 d...
After bringing this up as an editorial issue, the correct answer appears to be that the integral representation is "none of the above." It is simply left unspecified, and is not called out as such because the "unspecified" label is only generally applied to behavior.
69,145,701
69,146,535
How to solve “access denied” error trying to create a message queue?
Only happens when the code is called from .NET. When the same code is compiled as a C++ console app, or called from a C++ console app, it runs without errors. The following code compiles a C++ DLL called from .NET, and it prints “mq_open failed, code 1, message Operation not permitted”: extern "C" __attribute__((visibi...
It was snap. Microsoft made an interesting choice to ship their .NET framework, designed to be used by software developers, inside a sandbox which is hiding the actual operating system behind an abstraction. Under the hood, that thing is using AppArmor kernel module. That’s what produced that access denied status. Agai...
69,146,195
69,146,260
What if std::vector::insert(pos, value) with an invalid pos?
According to cppref: constexpr iterator insert( const_iterator pos, const T& value ); Return value Iterator pointing to the inserted value. Complexity Constant plus linear in the distance between pos and end of the container. Exceptions If an exception is thrown when inserting a single element at the end, and T is Cop...
std::vector is a sequence container. Table 77: Sequence container requirements listes the first argument of every insert overload as being p which is defined just before the table as : "p denotes a valid constant iterator to a" where a is the vector. So the position iterator is required to be a valid iterator to a. Unl...
69,146,343
69,146,573
How do I draw and write to a ppm file?
I want to draw lines/shapes and output to a ppm file, but I don't know how to even draw individual pixels. I know how to output to a file and that there's a nested for loop method for drawing pixels (found this code online), but I was wondering if there's an easier way to handle it. for (auto j = 0u; j < dimy; ++j) ...
I suggest you have a look at the ppm format. https://en.wikipedia.org/wiki/Netpbm#File_formats All you're doing is constructing a character string like this: 1 0 0 0 1 0 0 0 1 1 1 0 1 1 1 0 0 0 So, you could for example use nested arrays and a nested loop to traverse it. This code would generate an std::ostrin...
69,146,617
69,146,683
Why am I getting segmentation fault error?
I am writing a C ++ program that needs to convert numbers from decimal to binary. Here is my code: int* convertToBinary(int i, unsigned int n) { int ans[10000]; if (n / 2 != 0) { convertToBinary(i + 1, n / 2); } ans[i] = n / 2; return ans; } void send_number(int num) { for (int j =...
There are 2 issues at play - scope and (related) dangling pointers. When you define any variable inside a function - it is only valid inside that function. convertToBinary returns a pointer that refers to invalid memory. So when you try to print it - you are using convertToBinary(0, num)[j] Think about what this does....
69,147,098
69,147,562
I modified BFS to find shortest path in weighted undirected graph instead using Dijkstra's algo and it worked
To find shortest path in undirected weighted graph I was comparing BFS and dijkstra's algo to understand why we need priority queue. I wrote some code modifying BFS to find the shortest path to all nodes in a given graph. Problem link :- https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacenc...
The algorithm you wrote is a variant of Bellman-Ford Algorithm. Shortest_Path_Faster_Algorithm is an improvement of the Bellman–Ford algorithm(as well as yours). The only difference between SPFA and your algorithm is that SPFA checks if the vertex is already in queue before pushing it. But its worst-case time complexit...
69,147,273
72,437,362
How to solve the "symbol(s) not found for architecture arm64" in M1 Mac
new user of Mac OS I can't compile the c++ code. This topic is related to : this and this I tried the methods mentioned but it doesn't work. Undefined symbols for architecture arm64: "Menu::affichageMenu()", referenced from: _main in note_soft-276eef.o "Menu::setC(int)", referenced from: _main in not...
The problem can be solved with 2 types of actions: manage compilation with cmake or put all files (headers and sources files) in the same directory
69,147,302
69,147,324
explicit specialization with concepts
I'm trying to use concepts to do explicit specialization of some template method, but it isn't compiled on gcc or msvc, but can compile on clang... Who is right? #include <type_traits> template<typename T> concept arithmetic = std::is_arithmetic_v<T> && !std::is_same_v<T, bool>; template<typename T> void foo(const T...
The correct syntax is template<arithmetic T> void foo(const T &value, int &result){} or void foo(const arithmetic auto &value, int &result){} So no template<> or template<arithmetic T>
69,147,735
69,149,518
can I deduce template argument later?
#include<vector> #include<functional> class SegmentTree final{ public: template<typename T> using data_type=T; public: template<typename T=int> explicit SegmentTree(const size_type& size); }; I want that SegmentTree isn't a template class but has template type, and deduce this type fro...
There is no such thing as a inner template parameters for data members. If a data member depends on a type template parameter, such a parameter must be available in the signature of the class. That does not mean, however, that you need to specify all template parameters when instantiating a class, because, in c++17, th...
69,148,189
69,148,296
difference between double and double& in c++
I have the following function to calculate the mean of a double[] in c++: double& Vector::mean() { double sum = 0.0; for (int i = 0; i < size; i++) { sum += *(arr + i); } double m = sum / size; return m; } this compiles and runs, but this doesn't: double& Vector::mean() { double sum = 0...
Using double& indicates that you are returning by reference. This means that rather than directly returning a value, the function returns a memory location where the value is stored, which is immediately dereferenced and converted to a value in the calling code in most cases. Since sum/size is an expression and not a...
69,148,690
69,153,256
VSCode include path property not working properly
Backstory I'm making a small game engine project for self-learning/ I'm using the Vulkan Graphics API alongside GLFW, which I compile with CMake. Everything works fine during compile-time, but when writing code inside VSCode it gives me false errors saying cannot open source file "GLFW/glfw3.h"C/C++(1696). Even though...
You say you want to use CMake as your buildsystem. I highly recommend keeping all your build settings in CMake then. To convert your vscode config use: set(CMAKE_C_STANDARD 17) set(CMAKE_CXX_STANDARD 17) # declare global include directories used by all targets # by using 'SYSTEM' many compilers will hide internal warn...
69,148,781
69,148,908
Why does printf throw an error when a format identifier (%s) is assigned a function that returns a string in c++?
I have a simple function that simply adds two numbers and returns the output like below #include <stdio.h> #include <iostream> #include <cstdlib> #include <string> using namespace std; double addNum(double num1=0, double num2=0) { return num1 + num2; } int main(int argc, char** argv) { printf("%.1f + %.1f = %...
Not a direct answer to your question, but I want to teach about not using printf. Since using printf is not secure/dangerous. Why not use printf() in C++ // #include <stdio.h> <== I would not use this in c++ #include <iostream> #include <sstream> #include <string> // using namespace std; // I never use using namespac...
69,148,789
69,148,856
C++ value_type::second_type compiler error inside template
I get compiler error when using decltype inside template function. Example is pretty self-explanatory. Help? template<class T> void foo(T&& m) { auto t = (decltype(m)::value_type::second_type::value_type*)3; // compiler error } int main() { unordered_map<int, map<float, double>> m; foo(m); auto t = (de...
If you use m in the function, you need to remove the reference (and add typename): Example: typename std::remove_reference_t<decltype(m)>::value_type::second_type::value_type* t; Or simply use T: typename T::value_type::second_type::value_type* t;
69,148,790
69,170,941
Which of two conversion operators must be selected by C++ compiler?
A class can declare several conversion operators. In particular it can be conversion operators to some type and to const-reference of the same type. Which of the two conversion operators must be selected in case of requested conversion to that type? Consider an example: #include <iostream> struct B {}; static B sb; s...
The program is ill-formed and rejected by GCC is correct here but the diagnosis can arguably say it is not completely correct. For this declaration B b(a);, it is direct-initialization of an object of class B from the initializer a of type A, according to [over.match.copy] p1 Assuming that “cv1 T” is the type of the o...
69,148,814
69,148,900
Cannot understand error: "warning: control reaches end of non-void function [-Wreturn-type]"
I have been learning c++ recently. When I tried to run the following lines... #include <iostream> short a = 0; short b = 1; short c, i; void Fibonacci(){ std::cout << a; std::cout << b; while (a <= 100){ c = a + b; a = b; b = c; std::cout << c; } } int prime_number(sho...
As Elliott in the comments has said the warning you are getting is not going to affect your program at all. It's recommend that you return something since you function has a return type of integer. Below is a easy fix to get rid of the warning. :) Old Code: if (a == 1) { std::cout << "Its a prime number\n"; } New ...
69,148,901
69,148,936
C++: is `X&& goo();` a function declaration or a variable definition?
I'm new to C++ and I'm reading this tutorial. I found the following code snippet. X&& goo(); // (1) X x = goo(); // (2) I think X is a class name, but I don't understand what X&& goo(); does. I suppose there are two possibilities: It declares a function goo which returns a rvalue reference to X. It declares a variabl...
is X&& goo(); a function declaration or a variable definition? It is not a variable definition. If X is a type name, then it is a function declaration. If X is a variable and goo is callable, then it is an expression statement. But if 1 is true then since there is no function body how can it be called? It can be ca...
69,149,046
69,149,601
Errno is not set using c++ system api while invoking powershell script
I am using system api to invoke the powershell script and that script is not setting the errno to any value which is not giving me hint if the command execution is success or failure. Below is my powersehll script which is simply setting the exit code, but this exit code is not set when I am calling this script using c...
The exit keyword in PowerShell sets the return code to 0 by default. As you are just calling exit without an argument, the return code will always be 0. Change your function to this: #------------------------------------------------------------------------------- function ExitWithCode { #-------------------------------...
69,149,369
69,150,891
Is it safe to pass an `std::string` temporary into an `std::string_view` parameter?
Suppose I have the following code: void some_function(std::string_view view) { std::cout << view << '\n'; } int main() { some_function(std::string{"hello, world"}); // ??? } Will view inside some_function be referring to a string which has been destroyed? I'm confused because, considering this code: std::stri...
some_function(std::string{"hello, world"}); is completely safe, as long as the function doesn't preserve the string_view for later use. The temporary std::string is destroyed at the end of this full-expression (roughly speaking, at this ;), so it's destroyed after the function returns. std::string_view view(std::strin...
69,149,459
69,179,747
What causes the error #18 expected a ")" on a MSP430
Compiling the following C++14 code for a MSP430 using TI Code Composer I got the following errors: subdir_rules.mk:14: recipe for target 'main.obj' failed "Interface.h", line 75: error #18: expected a ")" "Derived.h", line 91: error #18: expected a ")" This is for the following code structure in which the Interface.h...
The problem was indeed as @Clifford mentioned. N was already defined somewhere in the MSP430 code. Renaming Derived::advance(const uint32_t N) to Derived::advance(const uint32_t N_bytes) solves the problem.
69,149,998
69,153,235
Vulkan queue waiting on semaphore that has no way to be signaled
Validation error: VUID-vkQueuePresentKHR-pWaitSemaphores-03268(ERROR / SPEC): msgNum: 622825338 - Validation Error: [ VUID-vkQueuePresentKHR-pWaitSemaphores-03268 ] Object 0: handle = 0x2ad2f2d8a38, type = VK_OBJECT_TYPE_QUEUE; Object 1: handle = 0xdd3a8a0000000015, type = VK_OBJECT_TYPE_SEMAPHORE; | MessageID = 0x251f...
You signal the _renderFinishedSemaphores[_currentFrame] semaphore, but then on present you wait on a different semaphore: _imageAvailableSemaphores[_currentFrame].
69,150,131
69,150,448
Reading lines from input
I'm looking to read from std::in with a syntax as below (it is always int, int, int, char[]/str). What would be the fastest way to parse the data into an int array[3] and either a string or char array. #NumberOfLines(i.e.10000000) 1,2,2,'abc' 2,2,2,'abcd' 1,2,3,'ab' ...1M+ to 10M+ more lines, always in the form of (int...
You could use std::from_chars (and reserve() the approximate amount of lines you have in the file, if you store the values in a vector for example). I also suggest adding support for reading directly from the file. Reading from a file opened by the program is (at least for me) faster than reading from std::cin (even wi...
69,150,160
69,150,739
Why the simple multiplication would result in some garbled characters?
I try to design a program that implements the multiplication between two big integers(Using C++). But after I complete it, I found that if I input the two integers by the command arguments, the results would be sometimes very weird and sometimes right. Please help me figure out the reason and tell me how to fix it. Tha...
Just initialize your char arrays to empty ones: char cArr1[500] = {}; char cArr2[500] = {}; then, for the sake of clarity, assign the lengths from your arguments to two integers, casting them since the compiler might warn you about incompatibility between size_t and int. int lenArg1 = 0; int lenArg2 = 0; lenArg1 = (i...
69,150,183
69,150,257
How to remove duplicate items from vector<vector<int>>
I am trying to solve Combination II which is similar to coin change problem with unique combinations and no infinite repetition of the coin. e.g: coins: {1,2,4}, amount = 3 {1,1,1,1} or {1,1,2} not allowed as coin 1 frequency is one time.(A single coin will be used only one time) {1,1,4} ,amount=3 {1,1,2} --> will be a...
Use a std::set. It is literally just about replacing the inner vector with set: class Solution { public: std::vector<std::vector<int>> combinationSum2(std::vector<int>& candidates, int target) { std::sort(candidates.begin(), candidates.end()); std::vector<std::set<std::vector<int>>> dp(target+1); ...
69,150,253
69,151,411
Using the GDI+ API to draw an image
I'm using the GDI+ API just to display an image (bmp) on the screen. Here is the code of the function doing the task: void drawImg_ArmorInfo_PupupWnd(HDC hdc) { GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Image* image = ne...
graphics falls out of the scope after the GdiplusShutdown so it cannot destruct correctly. Try this: Graphics * graphics = new Graphics(hdc); graphics->DrawImage(image, 0, 0); delete graphics;
69,150,509
69,152,922
Is C++ virtual function always resolved in run time?
I have a question regarding the resolving timing of a C++ virtual function. From chapter OOP in C++ Primer, it mentioned that: Calls to Virtual Functions May Be Resolved at Run Time When a virtual function is called through a reference or pointer, the compiler generates code to decide at run time which function to cal...
In general, the compiler will create a vtable and virtual method calls are dispatched through it, i.e., there is one added level of indirection in calls. But optimizing compilers do try to avoid this. This optimization is generally called "devirtualization". When and how this works very much depends on the compiler and...