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,954,799
69,954,809
c++ using bool in a class with set and get functions
I am trying to create a class with private attributes and change values with set and get functions. However i cant seem to change the bool value class VideoGames { private: bool buy; public: bool get_buy(){return buy;} void set_buy(bool b){b = buy;} }; main(){ VideoGames g1; double price...
You flip-flopped the assignment; b = buy; reassigns the parameter (which is then thrown away so nothing changes), you wanted buy = b; to reassign the attribute from the parameter.
69,955,255
69,956,305
How to determine two implicit conversion sequences preferred than each other for overload resolution?
I want to question about overload resolution accompanying an implicit type conversion. This question refers cppreference 1 and 2. It seems that an implicit conversion sequence has at most three steps to convert an type T1(argument type) to T2(parameter type): zero or one standard conversion sequence; zero or one user-...
Cppreference is a useful reference site, but it is not the C++ standard. It has mostly accurate information, but in boiling down the complexities of the standard, some details can be lost around the margins. I will be citing C++17 (since I don't have a C++11 website I can link to), but the wording has not meaningfully ...
69,955,563
69,955,667
How does this binary search works?
I saw this method in a book, to do binary search, but I can't understand how it is working no matter how I try. Can someone explain to me exactly how it is working? the book's explanation did not help : The idea is to make jumps and slow the speed when we get closer to the target element. The variables k and b contain...
b are the length of the jumps of your current position. As you can see, b starts as n/2 and is divided by 2 at each step up until it reaches 1. Now, For each b, remember that b is divided by 2 at each step in the for loop, we run a while loop where we add b to to our current position, which is k. We add b to k checking...
69,955,890
69,965,920
How to make NSOpenPanel accept keyboard and mouse events in objective-c?
I have C++ console application getting written in XCode, and I need to open a file selector dialog. To do this I'm using Cocoa with objective-c. I'm trying to open an NSOpenPanel to use it for this purpose. I'm using the following code currently: const char* openDialog() { NSOpenPanel* openDlg = [NSOpenPanel openPa...
/* To run in Terminal: clang openpanel.m -fobjc-arc -framework Cocoa -o openpanel && ./openpanel */ #import <Cocoa/Cocoa.h> int main() { NSApplication *application = [NSApplication sharedApplication]; [application setActivationPolicy:NSApplicationActivationPolicyAccessory]; NSOpenPanel* openDlg = [NSOpenPanel ope...
69,955,893
69,984,038
Boost polygon union result is differing between windows and linux
I am trying to get a union of all the individual polygons via boost geometry. But oddly the results seem to vary between windows and centOS. The result is coming out right one (the one i expect) in windows BUT in linux its odd. In linux it shows result as two split polygons. In Windows i get MULTIPOLYGON(((0 -0,0 2996,...
The flag BOOST_GEOMETRY_NO_ROBUSTNESS made the boost API behave differently for same set of inputs in linux. Turning OFF this flag made the output to become same in windows and linux.
69,955,915
69,955,968
Template argument deduction in case of designated initializers in C++
In the following code there is an initialization of A<T> objects with template argument deduction using designated initializers in two slightly distinct forms: template<typename T> struct A { T t; }; int main() { A a{.t=1}; //#1: ok in GCC and MSVC A b{.t={1}}; //#2: ok in MSVC only } The first way is accepte...
GCC is correct. Braced-init-list like {1} has no type, so it makes template argument deduction fail. Non-deduced contexts ... The parameter P, whose A is a braced-init-list, but P is not std::initializer_list, a reference to one (possibly cv-qualified), or (since C++17) a reference to an array:
69,955,934
69,973,534
CMake build git submodules and its dependencies
I am a novice in CMake, I would like to use a C++ library A in my CMake project. This library A is included as a git submodule and I include it in my CMakeFile using add_subdirectory("extern/A") which works so far. However, my library A has two other dependencies B and C. They are included in the CMakeFile of library ...
Your mistake adding B as a dependency to RootProject where A needs it. Solution In the following directory structure: RootProject |__ .git |__ CMakeLists.txt |__ src | |__ main.c | |__ ... | |__ vendor |__ A |__ .git |__ CMakeLists.txt |__ src |__ ... RootProject depends on...
69,956,080
69,956,754
No type named 'type' in 'struct std::common_reference<Ref&&, const Val&>'
I'm trying to write a proxy iterator using Boost.STLInterfaces. It fails to compile because the lvalue reference of the value and the rvalue reference of the reference are different, see a simplified version on Compiler Explorer https://godbolt.org/z/aE3bq7en4. How do I make two types have common reference? I tried ove...
In this case, you need to partial specialize std::basic_common_reference to define the common reference of the two, similar to this: template<template<class> class TQual, template<class> class UQual> struct std::basic_common_reference<Ref, Val, TQual, UQual> { using type = Val; }; template<template<class> class TQu...
69,956,284
69,964,339
"opencv_world454.dll was not found"
hello I had imported OpenCV into my C++ project but for some reason my code gives me this error. CODE: #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> int main() { std::string path = "Resources/test.png"; cv::Mat img = cv::imread(path); ims...
The solution was to install a new setup and install OpenCV into another path thank you to everyone who helped.
69,957,483
70,141,928
How can I write a shortcut to compile and run a program in a separate terminal window in Vim?
I have this as a Sublime Text build system right now: It compiles a C++ program, then opens a new window in Terminal.app and runs it there upon pressing ctrl+b. { "shell_cmd": "g++-11 -std=c++20 '${file}' -o '${file_base_name}' && echo 'cd \"${file_path}/\"' > '/tmp/${file_base_name}' && echo './\"${file_base_name}...
You actually have a few options, so use whatever suits your needs the most. You can use vim's built in terminal :terminal (or :term; see :help :terminal), which is probably the easier way: :term g++-11 %:p && ./a.out<CR> Or you can use :compiler with :make (see :help :compile and :help 'makeprg'): :compiler gcc :let ...
69,957,534
69,958,492
Is it possible to use Makefile "define" to define a target plus its recipes?
I have a C/C++ project that contains different directories, each containing a set of objects executables to build from C/C++ source code. To enable automatic dependency tracking (generating .d dependency files whenever my #include header files change), I have defined the following variables in a common Makefile: # auto...
Make is an old grandpa - it is 45 years old. Consider moving to something newer - CMake, Scons, Meson, etc. Such tools will take care of dependencies automatically, will be portable, will come with a lot more features and will save you from endless (and pointless) hours of reinventing the wheel. Is it possible to use ...
69,957,677
69,957,710
c++ Call subclass method in vector of base class type
I have the abstract class Currency and several subclasses like FiatMoney or Crypto. I want to store all of objects of subclasses in one vector and in the same time have access to methods, which are only in those subclasses. My Currency.h file looks like this: class Currency { public: virtual void to_Str...
How can I get access to the function com() which is only in object of subclass FiatMoney? You would have to type-cast a Currency* pointer into a FiatMoney* pointer, but you can only do that when the pointer is actually pointing at a valid FiatMoney object. When you know the Currency* pointer is pointing at a FiatMone...
69,957,881
70,008,122
How I can paint a text background with spdlog?
I did a test with the {fmt} and was super easy to change background color, but I can't get the same with spdlog. I can get the same result with spdlog, but is a weird code fmt::print( bg( fmt::terminal_color::yellow ) | fg( fmt::terminal_color::black ), " {1:<{0}}\n", 120, "message" ); spdlog::set_pattern( "...
If I understand your question correctly, you want to format your spdlog output using fmt, rather than having to specify the escape sequences yourself. For this, you can use the fmt::format function and use its output as a variable for spdlog: #include <spdlog/spdlog.h> #include <spdlog/fmt/bundled/color.h> int main(){...
69,958,282
69,958,423
How do I store a list in a dictionary when it is being created then cleared and then used for the next key with different values?
What I really want is to have the values to each key be an arbitrary list that is accessible for later use. The code given is just a sample of what is being attempted. #include <string> #include <list> #include <map> int main(){ std::map<std::string, std::list<std::string>> myMap; std::list<std::string> myList; ...
If you just want to reuse myList: 1) move the list declaration inside the while loop, so that a new empty list is created in every iteration, and then 2) use the map subscript operator with an rvalue reference so that the list is moved into the map. #include <iostream> // cout #include <string> #include <list> #includ...
69,958,593
69,958,676
Passing a pointer to an int array to a member function, error: invalid types 'int[int]' for array subscript
Ok, I'm fairly new to programming, and c++ so please take it easy on me. I am trying to write a program that takes in the dimensions of a metal plate for a 2-D finite element method analysis (thickness neglected). So, I created a class for my part (the plate), the elements for the mesh, and the nodes for the elements. ...
There are multiple problems with the shown code, not a single problem. All of the problems must be fixed in order to resolve all compilation errors. void PartClass :: meshingPart(int &partMesh, int inRow, int inCol) The first parameter to this class method is declared as a reference to a single, lonely int. It is not ...
69,958,694
69,977,547
Can I set a value using a function in a class?
If I have a friend function can I somehow use set() to assign a value to a private variable inside the function? Or some other method? Example : Here I have 3 private variables. I tried to make the sum of 2 of them and store the result in the 3rd one. I tried to do it with a setter but the result is 0. In main it works...
As alluded to in the comments, the issue is with this function: int sumNumber(Function f) { int a = f.getA(); int b = f.getB(); int sum = a + b; f.setSum(sum); return sum; }; Let us walk through your code: Function AA(1,2); You create a object of type Function, called AA and you allocate each memb...
69,958,896
69,960,027
How to binary serialize in a buffer with Boost
How to binary serialize in a buffer? I didn't find answer on official documentation and on stackoverflow it absent too. The most part of examples show how to binary serialize in some file. Other part show how to binary serialize in the string. (I think this is wrong way because binary could have a lot of null-s, but st...
(I think this is wrong way because binary could have a lot of null-s, but sting - don't) C++ strings contain NUL characters just fine But how to binary serialize in some buffer - there are no information. Could someone show how to do it? Strings are also "some buffer". So using std::stringstream (which you likely s...
69,958,948
69,960,559
Linux make: Need to rebuild a text file when makefile changes
I've inherited a Linux C++ app and makefile. In the existing makefile, it had code such as the following: APPVER=5.01 REL=B $(APP): $(OBJS) $(MAKEFILE) echo $APPVER > .sw_ver.txt echo " " >> .sw_ver.txt echo $REL >> .sw_ver.txt $(LD) $(OBJS) $(LDFLAGS) -o $(APP) At runtime, th...
Two things to clarify: MAKEFILE is not an implicit built-in variable. So if you don't set its value it contains nothing. (You can run make -p in a directory without a Makefile to see what variables are there. See https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html) Based on the reason above, sin...
69,959,087
69,959,272
WinInet Access Violation in HttpOpenRequest()
I am trying to upload a file to a PHP page using WinInet. I'm getting an Access Violation on one of the functions, but can't see why. I've built the code from an example page. Here is the code: HINTERNET aInternet=InternetOpen("My-Custom-Agent/1.0",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0); HINTERNET aConnect=InternetCo...
Per the HttpOpenRequest() documentation: [in] lplpszAcceptTypes A pointer to a null-terminated array of strings that indicates media types accepted by the client. Here is an example. PCTSTR rgpszAcceptTypes[] = {_T("text/*"), NULL}; Failing to properly terminate the array with a NULL pointer will cause a crash. You a...
69,959,091
69,959,132
How do I input 2 variables in one line and count them in output?
Out of all activity I've been tasked with, this was by far one of the most challenging one. I am an IT student, ie a beginner in the C++ language, and so far I've only been taught how to make use of while loops and if conditions. By this, we have to use these two in the following activity: Count how many of a certain ...
#include <iostream> using namespace std; int main() { int v1, v2; cin >> v1 >> v2; }
69,959,421
69,959,911
Strange error while expanding parameter pack containing lambda types
I have a function which looks like foo in the following example: template <typename... Parameters> void foo(std::function<void (Parameters &)>... functions) { // does interesting things with these functions } Now I want to call this function with some lambdas, e.g. like this: foo([](const std::string & string) {})...
The type of address of lambda's operator() is void (Lambda::*)(Param&) const not void (&)(Param &), you need to define the base case of your FunctionTypeTraits as: template <typename Function> struct FunctionTypeTraits: public FunctionTypeTraits<decltype(&std::remove_reference<Function>::type::operator())> {}; templ...
69,959,634
69,959,793
Function template specialization in C++, no Instance of overloaded function
I'm learning about function template specialization in C++ and am tasked with writing a template function called plus that returns the sum of it's two arguments which maybe of different types. One version that accepts by value and another by pointer. As an added challenge, I'm asked to overload this function so that it...
This would be my suggestion: template <typename T1, typename T2, typename T3> T3 plus(const T1& a, const T2& b) { return a + b; } template <typename T1, typename T2, typename T3> T3 plus(const T1* a, const T2* b) { return *a + *b; } template <typename T1, typename T2, typename T3> T3 plus(T1 a, T2 b) { re...
69,959,795
69,959,833
How to obtain smoothed normals when extruding a 2d curve (with parametric normals) into 3d?
I'm extruding a sine-wave curve into 3d but when rendering, I can see that the normals are not smoothed. The sine-wave is generated with parametric normals, as follows: vector<CurvePoint> sineWave(int n, float x0, float y0, float step, float period) { vector<CurvePoint> curve; for (int i = 0; i < n; i++) { ...
Stupid me. It was a small bug in the extruding method, which should be like: void extrude(IndexedVertexBatch<XYZ.N> &batch, const Matrix &matrix, const vector<CurvePoint> &curve, GLenum frontFace, float distance) { auto size = curve.size(); if (size > 1 && distance != 0) { bool cw = ((frontFace == CW) &...
69,959,957
69,962,602
Use cplex with c++: add conditional constraint
I'm new in cplex, I found in python the function: add_indicator_constraint, but in c++ I can't find anything like that. Can someone show me, please?
in the example ilofixnet.cpp in CPLEX_Studio201\cplex\examples\src\cpp you can see a good example of indicator constraint in C++ // Add logical constraints that require x[i]==0 if f[i] is 0. for (IloInt i = 0; i < x.getSize(); ++i) model.add(IloIfThen(env, f[i] == 0, x[i] == 0));
69,960,187
69,960,214
How do I successfully implement my .h file to my main .cpp file to make it run without errors
The code is supposed to take the class from the .h file and use it in the main to create a custom pet synopsis that can be stored later in another text file. I haven't made the modular extraction to a text file yet because I need to get it at least working and able to actually compile and return the different arrays th...
You never implement the constructor and destructor, you just declare it: dog_list(); ~dog_list(); You have to implement it, for example, in main.cpp: dog_list::dog_list() = default; dog_list::~dog_list() = default;
69,960,342
69,961,523
How to properly store lambda functions in a tuple and call them?
I'm trying to create a class that can store functions in a member tuple. But when trying to put lambdas inside of an object's tuple (through function pointers) I'm getting a error. Please explain, what I'm doing wrong and what is the proper way of releasing this idea. I think there should be an elegant and stylisticall...
template<typename Type> using Func = bool(Type const &); This line suggested functions taking in const type arguments. However: [](int &arg) { return arg > 0; }, [](std::string &arg) { return arg == "abc"; } These two lines suggested non-const arguments. Either remove the const from the first line, or add const to th...
69,960,605
69,961,223
How to make this upper lower case c++ program work?
I am trying to make this app which converts upper case characters of a string to lower case and vice versa. But when i run the code it displays a really weird output The code i wrote: #include <iostream> #include <string.h> std::string toggle(std::string str) { #define maxsize 100 if (sizeof(str)>maxsize) ...
First i have added a return inside the toggle function. Second, you can find out the length/size of a std::string using the size() member function. Using these two modifications your program would look like: #include <iostream> #include <string.h> #define maxsize 100 std::string toggle(std::string str) { if ( ...
69,960,826
69,960,901
What is the Faster way to fill vector from float pointer?
Is there a faster way than what I have below to append a number of floats to a vector, where the source floats come from const float buffers? The example below, which is what I currently have, gets called in a loop to append somewhere between 1-16 floats at a time. At any one time, that function can be called 1000's of...
The fastest linear way is dst.insert(dst.end(), ptr, ptr + count); Even a faster way is using the parallel algorithm or OMP.
69,960,995
69,961,072
Tried appending multiple nodes in LinkedList c++ but it's just printing 1 node
I tried appending multiple nodes in LinkedList c++ but it is just printing 1 node as I run it. Kindly review it, and help me fix it. #include <iostream> using namespace std; //here is the node struct Node { int data; struct Node* next; }; // ------------here is linkedlist----------- class LinkedList { private...
Change your while loop from: while (nodePtr->next) { nodePtr = nodePtr->next; nodePtr->next = newNode; ... } to while (nodePtr->next) { nodePtr = nodePtr->next; ... } nodePtr->next = newNode; Also, in C++ use nullptr instead of NULL.
69,961,252
69,961,390
Attempting to save vector<int> in bin file and reading it gave random data
I wrote two functions to save and read data in a bin file: #include <iostream> #include <fstream> #include <vector> using namespace std; // save data in file with name p_file template <typename T> void save(string p_file, T data) { ofstream output(p_file, ios::binary | ios::out); output.write((char*) &data, s...
You are passing the address of the vector object to the save function (which lives on the stack) and not the underlying dynamic array (lives on the heap memory) which holds the ints. Also have a look at how std::vector works: https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdvector/ Here is my full solution w...
69,961,275
69,961,321
cannot access private member in the same class
I tried to declare a public member function with a private struct, but it didn't work. Can someone help me with this? Here's the header file class LinkedList { public: LinkedList(); ~LinkedList(); ... //I tried to add LinkedList also not working //void deleteNode(const LinkedList::Node* n); void delet...
class LinkedList { public: LinkedList(); ~LinkedList(); void deleteNode(const Node* n); private: struct Node { std::string value; Node *next; }; }; Node is declared after void deleteNode(const Node* n);, so the compiler won't know what Node is. You should do this instead: class L...
69,961,473
69,975,236
Template argument deduction for parenthesized initialization of aggregates in C++
In the following code there is an initialization of A<T> objects with template argument deduction using two forms distinct by the type of braces: template<typename T> struct A{ T x; }; int main() { static_assert( A{1}.x == 1 ); //#1: ok in GCC and MSVC static_assert( A(1).x == 1 ); //#2: ok in GCC only } The ...
This is a bug in MSVC. The following papers were all introduced in C++20: P0960R3: Allow initializing aggregates from a parenthesized list of values P1975R0: Fixing the wording of parenthesized aggregate-initialization P2131R0: Fixing CTAD for aggregates Whilst MSVC lists them all as implemented in their Microsoft C/...
69,961,672
69,961,800
Function which outputs several std::collections to CSV / row first iteration
I want to write a function with the following signature (or similar): template <typename... Ts> void collection_to_csv(const std::string filepath, const Ts& ... containers); The function should write a csv file to a file located at filepath, where containers can be any number of iteratable containers from the STD and ...
You can use std::tuple to store the iterator of each containers and then use std::apply to increment them one by one to do this. #include <iostream> #include <string> #include <tuple> #include <vector> #include <list> template <typename... Ts> void collection_to_csv(const Ts&... containers) { const auto ncol = [](co...
69,961,849
69,965,052
OpenGL : Mesh turns black when adding specular lighting
I have implemented specular lighting in my C++ openGL program but when i add the final specular value into my existing diffuse lit equation, it turns black. Just displaying the specular on the mesh also doesnt work and the mesh remains back and removing the specular form the final equation for the Pixel restores the No...
Maybe there's a typo ? The statement specular_factor = max(specular, 0.0); looks like it should be : specular_factor = max(specular_factor, 0.0);
69,961,956
69,962,033
So, why do I have to define virtual function in a base class?
I'm trying to create a simple base abstract class with a virtual function and a child class that defines that virtual function. Running the following produces an error during compilation: #include <iostream> using namespace std; class Animal { public: virtual void speak(); }; class Cat : public Animal{ public: ...
Yes, non-pure virtual function should be defined. [class.virtual]/12: A virtual function declared in a class shall be defined, or declared pure ([class.abstract]) in that class, or both; no diagnostic is required ([basic.def.odr]). You might provide a definition, or mark it as pure virtual. class Animal { public: ...
69,962,150
69,962,321
Can't modify the value of a reference in Range based loop
I'm working on a school project of boolean minimization, and here I want to delete some elements of a set of my user defined class. This is where the error occurs: (dc and PI are both sets of my class Term, passed to this function by reference. std::set<Term>& dc, PI) for (const auto& n : dc) { for (const a...
You can't modify a reference to x because it is const. It is const because iterating a std::set through loop gives only const values. See solution with const_cast example code at the end of my answer. It is known that std::set stores all entries in a sorted tree. Now imagine if you can modify a variable when iterating ...
69,962,684
69,962,765
what is the language code for Turkish in SAPI
I'm working on a desktop application on Windows using Windows API. Application sends notifications and notifications must be spoken in Turkish language. What's the code for Turkish language that required on Language parameter in ISpVoice::Speak function? if(FAILED(voice->Speak((L"<sapi><voice required=\"Language=409\">...
It's 41f. if(FAILED(voice->Speak((L"<sapi><voice required=\"Language=41f\">"+alertBody+L"</voice></sapi>").c_str(), SPF_DEFAULT, NULL))) { // ... } You can find it in the documentation: Windows Language Code Identifier (LCID) Reference
69,962,700
69,962,803
Print 2D Array as a Method in C++
I want to write a method in C++ which prints a 2D array. This method is void and it has these parameters as inputs: 2D array, number of rows, number of columns. I want to use the 2D matrix as a double pointer to call the function. I want to print the elements in a 2D shape. I get the following error: error: cannot conv...
Your array is actually flat, meaning that you have to cast its type to int*, not to int**. int** refers to array of pointers to int arrays, but you have no pointers inside array. In other words you have actually 1-dimensional array of ints (flat). Any C multi-dimensional array like int a[3][5] or int a[3][5][7] are all...
69,962,916
69,962,984
Find the maximum and minimum element in an array
In this question i can't find the error everything seems correct to me, i am sorting the array using Quick Sort but the sorting algorithm is not working , so that i can find the max and min #include <iostream> #include <vector> using namespace std; void swap(int *a, int *b){ int t = *a; *a = *b; *b = t; }...
In quicksort() and partition(): int partition(vector<int> arr ,int low, int high){ int pivot = arr[high]; int i = low-1; for (int j=low; j<=high; j++){ if(arr[j]<pivot){ i++; swap(&arr[i],&arr[j]); } } swap(&arr[i+1],&arr[high]); return (i+1); } void quick...
69,963,212
69,966,062
Is there any practical difference between an inline function having internal and external linkage, with compiler optimization?
If a function is static inline, inline here works only as a suggestion. With either static or static inline the function has internal linkage, and the compiler knows this function cannot be called outside of the translation unit. Thus possibly no symbol is emitted for this function with compiler optimization. In case o...
The important distinction here is that functions with internal linkage in various translation units are different functions, while inline function definitions with external linkage in various translation units all define the same function. This can certainly affect generated code, if only in that if a symbol is emitte...
69,963,329
69,963,362
C++ 20 Concepts/Requires clauses
I would be really grateful if somebody could explain how C++ 20+ compilers (MSVC 2022 in my case) are able to compile the following, why does the Simple concept have no effect? template <typename T> concept Simple = requires(T t) { std::is_trivial_v<T> == true; }; void foo(Simple auto s) { std::cout << "bar";...
template <typename T> concept Simple = requires(T t) { std::is_trivial_v<T> == true; }; This checks if expression std::is_trivial_v<T> == true is well-formed, ignoring its value. To check if the expression is truthy, add a nested requires: template <typename T> concept Simple = requires(T t) { requires std::is...
69,963,353
69,963,608
difference between using a template function type and std::function
I am curious as to why a2 is fine, but b2 won't compile: #include <functional> #include <iostream> class A { public: A(std::function<void(int)>&& func) : f(std::move(func)) {} std::function<void(int)> f; }; template <class F> class B { public: B(F&& func) : f(std::move(func)) {} F f; }; int main() ...
A(std::function<void(int)>&& func) A can be initialized with std::function rvalue. Now, f (in main) is not a std::function, seeing as each lambda has its own distinct type. But we can create a temporary std::function out of it, and bind the rvalue reference func to that. B(F&& func) Don't let appearances fool you. Th...
69,963,443
69,963,558
Why does this c++ template need reference?
I try to print the type using specilization, but this doesn't work. template<typename T> struct print_type { static constexpr char const value[] = "unknown"; }; template<> struct print_type<void> { static constexpr char const value[] = "void"; }; template<> struct print_type<int> { static constexpr char c...
Short answer: You need to activate C++17 or upgrade your compiler Long answer: Even constexpr variables need a defenition. When you ODR-use a constexpr variable, you need to add the definition for it. In C++17, constexpr variables part of a class-type definition are inline by default. Inline variable generate their def...
69,963,445
70,183,422
Safe Memory allocation during a c++ parallel algorithms invocation (with Intel TBB)?
I would like to understand whether a memory allocation inside a function which a thread executes is safe for the c++ parallel algorithms. Consider the following situation: std::for_each(std::execution::par, first, last, func), with func being the function object. During a call to func (CPU and GPU) memory is allocated...
You can use tasks instead of threads as Intel oneTBB works on tasks instead of low-level threads that is, it creates tasks instead of thread and it will map these tasks onto hardware at runtime. The Task scheduler takes care of mapping the tasks onto threads. You should explicitly free the memory space when we use for_...
69,963,665
69,965,546
Writing and Reading boost Property Tree From/To File?
I want to write a boost::property_tree::ptree binary to a file, and read it out again into a ptree. Since i´m not very comfort with the ptree and binary writing/reading them.. I thought you guys can lead me into the right direction. Writing strings, int/float/double isn´t that great problem, but how to store a whole pt...
You will have to select a format: INI, Json, XML or INFO. Each has their own set of limitations: https://www.boost.org/doc/libs/1_77_0/doc/html/property_tree/parsers.html E.g. if you choose JSON: #include <boost/property_tree/json_parser.hpp> void TGS_File::PTreeToFile(std::ofstream &_file, boost::property_tree::ptree...
69,963,867
69,966,587
Expand FindModule.cmake logic with a wrapper file
There are a lot of libraries' packages which do not provide a CMake config file, and in order to find and use them with cmake, one would have to resort to using a FindPackage.cmake script. Some scripts (i.e. SDL) are available within the cmake itself, so finding a package is relatively easy. Though in my case, SDL-sear...
The first thing that comes to mind is to delete the current path from CMAKE_MODULE_PATH before calling find_package(), and then restore it. list(REMOVE_ITEM CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) find_package(SDL) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) if (NOT TARGET SDL::SDL) # add target and ...
69,964,575
69,964,740
What is the type of a vector that stores a vector of one function and one vector of std::string
I am trying to figure a thing out right now and I can't, I need to find a type for this (python) def fn1(hello: list[str]) -> None: pass mv = [(fn1, ("1", "hello", "12", "no")), (fn1, ("w", "ufewef", "1ee", "no"))] # any size what is a C++ type for mv? (doesn't matter if it's mutable or not) I tried std::vector<...
These types get complicated, so to make them shorter I'll first define a couple of type alias: using StringVec = std::vector<std::string>; using StringVecFunc = std::function<void(const StringVec&)>; Now the type of your data container could be any of these: using T1 = std::vector<std::tuple<StringVecFunc, StringVec>>...
69,964,741
69,964,816
How to get same lines in c++
I have a text file with IP addresses in it. For example, I used vector but I confused, i can't. I tried for loop but it was not work because of i am used while in first. 192.168.4.163 192.168.4.163 192.168.4.163 192.168.6.163 192.168.6.163 In output I would like to write 192.168.4.163 => 3 times 192.168.6.163 => ...
You can simplify your program by using std::map as shown below: #include <iostream> #include <map> #include <sstream> #include <fstream> int main() { //this map maps each word in the file to their respective count std::map<std::string, int> stringCount; std::string word, line; int count = 0;//this ...
69,964,985
69,966,713
2D Matrix Multiplication in C++
I want to write a function which allows us to do multiplication of 2 2D matrices. This function has the following parameters as inputs: list1 and list2 are 2D arrays. They are transferred to the function as pointers. Row1, col1, row2, col2 are int values for the size of list1 and list2. When I have square matrices for ...
I wouldn't mix in one function two entirely different matters, a memory allocation and a matrix-matrix multiplication! I would do C = A * B like this: bool matrixMultiplication(int* C, int* A, int * B, int rowA, int colA, int rowB, int colB) { if (colA != rowB) return true; for (int i = 0; i < rowA; i++) ...
69,965,301
70,159,293
C++ modules filesystem and iostream crashes g++
I have the following program: import <iostream>; import <filesystem>; namespace fs = std::filesystem; int main(int argc, char* argv[]){ fs::path input = "./"; std::cout << input; return 0; } I compile it with (g++ version 11.1.0): g++ -c -std=c++20 -fmodules-ts -x c++-system-header filesystem iostream g+...
Compiler support for modules is still in its early days. But if a header fails compiling as a header unit, then you can still include it instead: import <iostream>; #include <filesystem> namespace fs = std::filesystem; int main(int argc, char* argv[]){ fs::path input = "./"; std::cout << input; return 0; ...
69,965,599
69,965,662
How to add a static library permanently to the Ubuntu system?
Hi everybody I recently created a C++ project in which I put my code into header.h and header.cpp files and successfully create a static library called header.a. Now I put my header.h file into /usr/local/include position of my system and header.a into /usr/local/lib in order to "install" my library into the machine. N...
You can't, and no system library will be linked automatically without being told to do so. You can however add the path /usr/local/lib to the default paths for the linker to look for libraries (IIRC it's not in there by default for Ubuntu), which means you only need to add the -l (lower-case L) option to link with the ...
69,965,664
69,965,683
How can I desc order in vectors C++
I have C++ code like below. It works well but my output like this : 192.168.1.163 => 4 times 192.168.1.165 => 7 times 192.168.1.20 => 62 times How can I make desc order like : 192.168.1.20 => 62 times 192.168.1.165 => 7 times 192.168.1.163 => 4 times std::map<std::string, int> stringCount; //str is ip and int...
Since it is not possible to sort a std::map by its values you can use something like a std::vector as shown below. The program below writes the ip addresses in decreasing order of count values as you want. #include <iostream> #include <map> #include <sstream> #include <fstream> #include <vector> #include <algorithm> //...
69,965,676
69,965,764
Why am I getting error while using the Boost Library in C++?
I am using the c++ boost library in one code to get large numbers in output. My code is: #include <iostream> #include<cmath> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; int main() { int a; cout<<"Enter the value for a:"; cin>>a; for(int x =1;x...
The reason is that ans type is not int128_t. After changing ans type to auto compilation works fine: cat boost_error.cpp #include <iostream> #include<cmath> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; int main() { int a; cout<<"Enter the value for a:...
69,965,989
69,966,393
Function template accepting only non integral types (specifially bidirectional iterators)
I need a function template that only accepts non-integral types, if the arguments are iterators i made (i made my own class and using enable_if and a tag i manage to deduce whether or not the params are the iterators I created or not) template <typename InputIterator> foo (InputIterator first, InputIterator las...
Since you are limited to C++98 it is best to try animate SFINAE tools available in later versions c++03. This way code will be more familiar for future maintainer. For example C++98 do not have following tools: std::enable_if, std::iterator_traits std::is_integral. Your case is quite simple, so it is not hard, but lots...
69,966,073
69,966,193
C++ Struct/Class Question - How to create static instances of a struct/class
One of those basic C++ question, my bad. I'm wondering about you format structs in C++ such that, in this case, I could get math::Vector2::zero to return a Vector2 where both values are 0.f. namespace math { struct Vector2 { Vector2() { x = 0.f; y = 0.f; } Vector2(float x_, float y_) { x = x_; y...
The message tells you there are 2 distinct errors: use of undefined type math::Vector2 A member with an in-class initializer must be const. Fixes: for 1.: Move definition (assignment) of zero AFTER the declaration of Vector2 is complete. By the way... You MUST define the static variable in a .cpp file, or in the .h ...
69,966,230
69,966,930
Different result for function resolution on MinGW64 and MSVC
template <typename T> int get_num(const T&) { return 42; } struct Foo { int i = get_num(*this); }; int get_num(const Foo&) { return 23; } int main() { std::cout << Foo().i << std::endl; // MinGW64 - 42, MSVC - 23 return 0; } MSVC chooses non-template get_num "overload". It will successfully link...
For the first sample, MinGW is correct and MSVC is incorrect: the get_num call can only consider the function template. This is a question of overload resolution, so I'll start in clause [over]. get_num(*this) is a plain function call expression, so [over.call.func] applies: In unqualified function calls, the name is ...
69,966,408
69,967,773
I didn't know why my array is displaying wrong numbers. Just want to know why is that so?
Didn't know why my odd array is displaying some large number. I want to print only the odd numbers from the array in a sorted manner. Like if the array is 1 4 6 8 0 9 Print only 1 9 selectionSort() is just the function that sorts the array. int main() { int T, n, p, size,sum=0,si=0; cin >> T; for (int i = 0...
p=0 is not necessary in the for loop. odd[p++] = a[j] equation always mean odd[0]=a[j]. Put p=0 out of the for loop.
69,966,428
69,966,496
How to extract requires clause with two parameter packs into a concept?
I have this (supposedly not so useful) class template with templated constructor which is a candidate for perfect forwarding. I, however, wanted to make sure that the types passed to the constructor are the exact same as the ones specified for the whole class (without cvref qualifiers): template <typename... Ts> struct...
Concepts don't get special privileges with regard to template parameter packs. You can't have two packs in a set of template parameters unless there's something to distinguish them in terms of the arguments passed to them (one could be a series of types while the other is a series of values, or you have access to templ...
69,966,501
69,967,239
Match all GNU C SIMD vector extension types in clang/gcc
The objective is to write a type trait with the following signature: template<typename T> struct is_vector : std::true_type / std::false_type such that you can use is_vector<T>::value in SFINAE signatures. How do I properly detect whether a type is __attribute__((__vector_size(<some_vector_width>)) <some_built-in_type...
You could create a type trait to check if it's one of these vector types. It was a bit tricky finding a way to do it, but using one of the built-in functions that operates on the vectors seems to work. In this gcc example, I use __builtin_convertvector to try to convert the vector type to the same vector type. If it's ...
69,966,903
69,966,971
How is the inline specifier used in C++ to preserve the one definition rule?
I've been trying to figure out how the inline specifier preserves ODR. So far, with everything I've written it seems unnecessary because include guards ensure that definitions are only included once. Suppose I have the following definition in a file called constants.h #ifndef CONSTANTS_H #define CONSTANTS_H namespace ...
Constants that are not declared with the specifier extern have internal linkage. So all compilation units that include these declarations namespace constants { const double pi { 3.14159255358979323846 }; const double e { 2.71828182845904523536 }; } have their own constants pi and e. From the C++ 14 Standard (...
69,967,084
69,967,945
How to set the severity level of Boost log library
I have been successfully using the Boost Log library in my project. In other words, I am emitting log messages via BOOST_LOG_TRIVIAL(info) << "My message"; Now I want to control the severity of logging, and I followed the example from the Boost Log library documentation: #include <boost/log/trivial.hpp> #include <boost...
The severity keyword is defined in boost/log/detail/trivial_keyword.hpp. Apparently it's not being included. The minimal set of includes I could find: #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> namespace logging = boost::log; void init() { logging::core::ge...
69,967,116
69,967,783
Decimal to Binary Converting Years in C++
I wrote a program that converts decimal numbers (date of birth) to binary. Converting the day and month works smoothly, but when it comes to converting the year a problem occurs, for example 2001 is converted to 2521075409 instead of 11111010001. Could you tell me where the problem is? { int i; long long temp, ...
With int i;, i *= 10 quickly reaches the max limit for 32-bit integer 0x7fff'ffff. So i will also need to be 64-bit, it can be unsigned so the ceiling is a bit higher at 0xffff'ffff'ffff'ffff. Example unsigned long long i = 1; unsigned long long bin = 0; int year = 2001; while (year > 0) { int temp = year % 2; ...
69,967,145
69,967,691
Why does my code say that it has an incomplete type even after I tried declaring it?
I am writing a program that displays a number of students test scores in the form of a table and then calculates and displays the average. Upon running the code, I get the following errors(also pictured below): variable has incomplete type 'struct students' struct students st[50]; ^ note: forward declaration of 'studen...
You have to define it first. You can also use this style. struct student{ ... }; int main{ student* st[50]; for(int i=0; i<50;i++) st[i]=new student; return 0; }
69,967,228
69,967,297
Read access violation when trying to create copy constructor for linked list
I am having an issue in regards with my linkedlist implementation, where I am trying to create a copy constructor. // Copy Constructor List342(const List342& source) { *this = source; } List342& operator=(const List342& source) { Node<T>* s_node = nullptr; // Source node Node<T>* d_node = nullptr; // Desti...
By having Node::data be declared as a pointer, your code is responsible for following the Rule of 3/5/0 to manage the data pointers properly. But it is not doing so. Your copy assignment operator is shallow-copying the pointers themselves, not deep-copying the objects they point at. Thus, DeleteList() crashes on the de...
69,968,309
69,968,388
Searching an array of strings, getting weird return
I am doing a school project to search through an array of strings, where the user enters some characters to search through the array, and is displayed the full name and number that includes those characters. This is working, but when I ask if user wants to search again, the program returns the entire contents of the ar...
Adding cin.ignore(); Between line 43 and 44 fixes the bug. See the reason why here. You should try to fix your program without adding this line.
69,968,476
69,972,494
Is it possible to concatenate parameters of variadic macro to form a variable name?
I am trying to achieve something like the following: #define def_name(delim, ...) ??? // how will this variadic macro concatenate its parameters to define a new variable? // Calling `def_name` as follows should define a new variable. def_name("_", "abc", "def", "ghi"); // The following code should be generated after...
With little syntax change (MACRO can stringify, but cannot unstringify), your usage might be: def_name(, a, b) def_name(_, a, b, c) You might do, with some upper bound limit: #define def_name1(sep, p1) \ inline constexpr char const p1##_name[]{#p1}; #define def_name2(sep, p1, p2) \ inline constexpr char const ...
69,968,882
69,968,972
How to pass only mutex to lock_guard constructor parameter
When declare locker like, lock_guard Locker(mLocker); I want the compiler to detect if an mLocker is a mutex. To implement this, I used concept requires and defined as below. template <typename T> concept is_mutex = requires { std::is_same_v<T, std::recursive_mutex>; }; template <class T> requires is_mutex<T> usin...
First, Your concept of is_mutex is incorrectly defined. It will only check the validity of is_same_v in the requires clause without evaluating it. You need to define it as: template <typename T> concept is_mutex = requires { requires std::is_same_v<T, std::recursive_mutex>; }; Or just: template <typename T> concept is...
69,969,101
69,970,745
CEIL in objective function CPLEX C++
As per my knowledge, there's a tutorial that shows that ILOG can use ceil function (here). However, when I tried to implement it to calculate my objective function in CPLEX C++ (concert), it was failed. What I am looking for is as per below: for (i=0; i<I; i++){ for (j=0; j<J; j++){ TO += ceil(DecisionVariable[...
In OPL we have ceil but in concert C++ the equivalent function is IloCeil. But we need to remember that this function is not linear. In How to with OPL ? we can read How to use ceil of a decision variable in a CPLEX constraint ? range r=1..4; float x[r]=[1.5,4.0,2.0001,5.9999]; dvar int y[r]; dvar float f[r] in 0..0....
69,969,166
69,969,292
Using >= or value - 1?
Say I'm checking for if a value is greater than or equal to a certain value and the current values I'm comparing are integers. In C++, would it be more optimal to do something like: if(value > threshold - 1) ... or this if(value >= threshold) ... My thinking is that the call to >= adds an extra stack frame, but then...
The first has undefined behavior if threshold is signed and is the most negative value of its type. That might disqualify it immediately, but if you know that case is impossible, it is therefore at least as fast as the >= version since the compiler is obliged to produce the same answer but in only a subset of cases. ...
69,969,390
69,969,583
What is the space complexity of my code? (Linked List)
I was solving a problem related to linked lists I wrote some code which works perfectly fine but I am not able to analyse the space complexity of my code. This is the problem, You have been given a singly linked list of integers along with two integers, 'M,' and 'N.' Traverse the linked list such that you retain the 'M...
There are two space complexity metrics: total space complexity and auxiliary (extra) space complexity. Total includes input, while auxiliary doesn't. In your case, input size is O(n) and you're modifying it, using O(1) extra space. After modifications, input is still O(n). Here n denotes the size of the list. Which tra...
69,969,421
69,971,299
one strange problem when I generate random numbers by OMP(C++)
The code is as follows: #include<omp.h> #include<stdio.h> #include<stdlib.h> int main() { unsigned int seed = 1; int n =4; int i = 0; #pragma omp parallel for num_threads(4) private(seed) for(i=0;i<n;i++) { int temp1 = rand_r(&seed); printf("\nRandom number: %d by thread %d\n", temp...
The problem is that the variable declared private is not initialized. If you add this line printf("thread %d seed %u \n", omp_get_thread_num(), seed); before int temp1 = rand_r(&seed) you will get an output like this: thread 3 seed 0 Random number: 1012484 by thread 3 seed 2802067423 thread 0 seed 21850 Random ...
69,969,827
69,969,910
overloading assignment operator and header file in c++
i want to add a overloaded assignment operator to my object class in c++ but when I do this Cabinet& Cabinet::operator=( const Cabinet& right ) { if(&right != this){ for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { this->chemicals[i][j] = ...
You need to declare the function in your header file so you can define it later on. using namespace std; #include <stdlib.h> #include <string> #include <iostream> #include "Chemical.h" class Cabinet{ private: int rows; int id_cabinet; int columns; Chemical*** chemicals; string alphabet [9]; public:...
69,969,960
69,970,021
Duplicate Definitions?
I have the following code: #include <iostream> /* template <class A, std::enable_if_t<!std::is_same_v<A, double>, bool> = true> void test() { std::cout << __PRETTY_FUNCTION__ << std::endl; } template <class A, std::enable_if_t<std::is_same_v<A, double>, bool> = true> void test() { std::cout << "SFINAE" << std...
The problem of the first snippet is described here (see how /* WRONG */ vs /* RIGHT */ snippets of code map to your commented and uncommented code respectively). A common mistake is to declare two function templates that differ only in their default template arguments. This does not work because the declarations are t...
69,970,150
69,970,897
std::cin string to int array with variable length input
I have a task where i need to revert a list of variable length numbers. This could be "1 2 3" or "5 6 7 8 9 10". The sorting itself works fine. But I can't figure out how to read the user input (with variable length) and then only execute the reverseSort once. How can I read the user input into an array where each inde...
If you don't know number of inputs you need struct that can be resized. std::vector is good for it. For adding new data you can use member function push_back. You can read the input line as std::string (by std::getline) and you can open new stream with read data (std::istringstream). Further one can read values from ne...
69,970,230
69,970,273
Is there a way to slice the structure vector in c++?
I have an data named faces which definition is like this: struct ivec3 { unsigned int v0; unsigned int v1; unsigned int v2; }; std::vector<ivec3> faces; I got the faces with 100 elements(faces.size()=100). Now I want to get all v0 of faces. If I use the Python, I can do it like this all_v0 = faces[:, 0]...
You can do this with the help of std::transform: std::vector<int> all_v0; all_v0.reserve(faces.size()); std::transform(faces.begin(), faces.end(), std::back_inserter(all_v0), [] (const ivec3& i) { return i.v0; });
69,970,334
69,970,382
C++ SafeSingleton 3 level inheritance
I have a templated SafeSingleton class, Base class which is derived from SafeSingleton and implements some base methods. I want to have class that is derived from Base and can be accessed via instance() method of SafeSingleton. The problem is that when I am trying to access Derived::instance() it returns the pointer to...
template<class D> class Base : public SingleTon<D> { and class Derived : public Base <Derived> and ... done? If you want to put Base's non-Ddependent methods in a cpp file, you'll have to get fancy. Have BaseImp that does not derive from SingleTon, put code there. Have Base<D> derive from it and write forwarding gl...
69,970,809
69,970,865
What is the difference between these two expressions
#include <bits/stdc++.h> using namespace std; void test(){ int a = 100; cout << a << endl; } int main() { void(*b)() = test; (*b)(); //expression one b(); //expression two return 0; } test is a pointer to function, isn't it? (*b)() is a correct form, because it is equivalent ...
test is a pointer to function, isn't it? No, it isn't. test is a function. b is a pointer to function. But Why is it correct to delete a symbol *? Because you can also invoke the function call operator on function pointers, and not just functions. Furthermore, since a function can implicitly convert to a function p...
69,971,076
69,972,187
How to express a constraint in terms of another concept
It's probably easiest to describe specifically what I'm trying to solve to make this easier to understand. I have a SmartPointer concept, so that I can have functions which can accept either std::unique_ptr or std::shared_ptr: template <typename T> concept SmartPointer = requires(const T& t) { requires std::same_as...
You don't need T as a template parameter: template < std::forward_iterator TIterator , std::sentinel_for<TIterator> TIteratorSentinel > requires SmartPointer< std::iter_value_t<TIterator> > // ^^^^^^^^^^^^ void whatever(TIterator begin, TIteratorSentinel end) { // ... }
69,971,092
69,972,136
google mock : error: ‘class ISInfo’ has no member named ‘gmock_registerCallBack’
I have an interface in C++ called SInfo class ISInfo { public: /// Register a callback virtual Handle registerCallBack( const std::string topic) = 0; /// De-register a callback virtual bool deregisterCallback(Handle handle) = 0; /// Deconstructor virtual ~ISInfo() { }; }; I have class...
For a starter: I propose you derive from the base class, not from the impl class: class MockMSInfo : public ISInfo { public: MOCK_METHOD1(registerCallBack, Handle(const std::string topic)); MOCK_METHOD1(deregisterCallback, bool(Handle topicHandle)); }; And now the actual problem: the compiler is your friend he...
69,971,612
69,973,367
How does -march native affect floating point accuracy?
The code I work on has a substantial amount of floating point arithmetic in it. We have test cases that record the output for given inputs and verify that we don't change the results too much. I had it suggested that I enable -march native to improve performance. However, with that enabled we get test failures because ...
The use of FMA can both decrease and increase error, both of those may result in a testcase failing, depending on how the test works. FMA improves error "locally", but the effect may be the opposite when put in a wider context. For example, a * c - b * d (determinant of a 2x2 matrix) famously gives some (usually minor)...
69,972,016
69,974,618
OpenCV's Warp Affine Has Lower Quality Compared to Photoshop
I want to transform and align a detected face (320x240 Size) from a CelebA image (1024x1024 Size) using OpenCV's cv2.warpAffine function but the quality of the transformed image is significantly lower than when I try to align it by hand in Photoshop: (Left Image Is Transformed By Photoshop & Right Image Is Transformed ...
Problem and general solution You are down-sampling a signal. The approach is always the same: lowpass to remove high frequency components resample/decimate What not to do If you don't do the lowpass, you'll get aliasing. You noticed that. Aliasing means the sampling step can completely miss some high frequency compon...
69,972,833
69,972,972
Fastest "trivial" way of shuffling a vector
I am working on a chess engine for some time now. For improving the engine, I wrote some code which loads chess-positions from memory into some tuner code. I have around 1.85B fens on my machine which adds up to 40Gb (24B per position). After loading, I end up with a vector of positions: struct Position{ std::bitset...
There is a tradeoff to be made: Shuffling a a std::vector<size_t> of indices can be expected to be cheaper than shuffling a std::vector<Position> at the cost of an indirection when accessing the Positions via shuffled indices. Actually the example on cppreference for std::iota is doing something along that line (it use...
69,973,152
69,973,475
How to change the increment or step or scale of a Google Benchmark 'Range()' function
I have a very simple Google Benchmark program that benchmarks a function taking two integer arguments, I'm trying to use the benchmark to see how exactly does the time the function takes increase as the second argument's value increases from 1 to 100, so with the first argument staying with the same value of 999999 . T...
One of the following should work: BENCHMARK(largestDivisorOdd) ->ArgsProduct({ benchmark::CreateRange(999999, 999999, /*multi=*/2), // This is probably not what you want benchmark::CreateDenseRange(1, 100, /*step=*/1) // This creates a DenseRange from 1 to 100 }) Or create your own custom arguments...
69,973,270
69,973,595
Can a C++20 [[likely]] or [[unlikely]] attribute be used on the condition of a do-while loop?
I have tried placing C++20's [[likely]] and [[unlikely]] attributes at various locations around the condition of a do-while loop, and it seems placing them at the end of the line after the semicolon is accepted by all three major compilers: int main(int i, char**) { do { ++i; } while (i < 42); [[likely]...
Can a C++20 [[likely]] or [[unlikely]] attribute be used on the condition of a do-while loop? [[likely]] cannot be applied on "conditions". It can be applied on labels and statements. However this looks rather strange. Is this really the correct place for the attribute? You've applied the attribute to the return st...
69,973,456
69,973,621
Overloaded ++ operator only works from left side (C++)
#include <iostream> enum class Color { RED, GREEN }; Color& operator++(Color& source) { switch (source) { case Color::RED: return source = Color::GREEN; case Color::GREEN: return source = Color::RED; } } int main() { Color c1{ 1 }; Color c2 = Color::RED; ++c1; // OK std...
Color& operator++(Color& source) is for pre-incremant, you need Color operator++(Color& source, int) for post increment.
69,974,121
69,974,232
C++11 vector with smart pointer
I read a lot of documentation about vector modern usage. One of the common thing appearing is, "you can replace every push_back by emplace_back". Is it true ? I'm unsure, and the fact is I don't get the idea with a smart pointer. So, is there a difference to emplace a smart pointer than pushing it into the vector ? In ...
There's no difference between the emplace_back and push_back at the start of your question, they both supply a prvalue std::shared_ptr<XXX> that will be passed to the move constructor of the vector element. You can't myVector.emplace_back(x, y, z); if myVector holds std::shared_ptr<XXX> because there's no constructor o...
69,974,183
69,974,251
How exactly structure packing and padding work?
How exactly structs are packed and padded in c++? The standard does not says anything about how it should be done (as far as I know) and compilers can do whatever they want. But there are tutorials showing how to efficiently pack structs with known rules (for example that every variable needs to be on address that is m...
How exactly structs are packed and padded in c++? Short answer: In such way that alignment requirements are satisfied. The standard does not says anything about how it should be done (as far as I know) and compilers can do whatever they want. Within bounds of the alignment requirements, this is indeed correct. This...
69,974,388
69,974,449
How do I include other .cpp files
I've watched several tutorials on C++ header files and did EXACTLY what they were showing, but I can't really understand why I can't use a function from other .cpp file. Main.cpp #include <iostream> #include "Header.h" int main() { std::cout << sum(2, 2); return 0; } Header.cpp #include "Header.h" int sum(i...
Your program is working as can be seen here. To get your program working on your machine follow these steps(assuming you're using g++ and Ubuntu: Step 1: Create a binary/executable using the command: g++ main.cpp Header.cpp -o myexecutable Step 2: Test/Run your executable created in the last step using the command: ./...
69,975,281
69,976,156
Why my program shortcut is not highlighted in Windows start menu when newly installed?
I have a c++ program built with visual studio. An NSIS installer creates a shortcut for the program in the start menu. But the shortcut is not highlighted-as it is the case for all newly installed programs in Windows. Here it says that I have to add the version resource to my program; Which I did, but still no highligh...
I don't think Windows 10 will highlight your new shortcut. If it appears in the "Recently added" section then Windows has correctly detected your new shortcut. Windows XP to 7 highlighted new shortcuts in a different color. Windows 8 would promote a new shortcut as a tile on the start screen. Windows 8 and later does s...
69,975,308
69,975,708
C++ Multipath Inheritance : Why the access using Base class scope is non-ambiguous?
I am studying C++ and while studying virtual inheritance, I came across following doubt: class A { public: int x; A() { x = 677; } A(int a) { cout << "A con , x= " << a << endl; x = a; } }; class B : public A { public: B(int a) : A(a) { } }; class C :public A { public: C(int a) ...
d.A::x; is indeed ambiguous. GCC and Clang report it as error, only MSCV fails to do so: https://godbolt.org/z/1zhjdE6a8. There is a note in [class.mi] with an example of multiple inheritance stating that: In such lattices, explicit qualification can be used to specify which subobject is meant. The body of function C​...
69,975,344
69,985,371
How can I gracefully stop a process created with CreateProcessW and option CREATE_NEW_CONSOLE?
Somewhere in my application, I am creating a process like this: STARTUPINFO startupInfo; ZeroMemory(&startupInfo, sizeof(startupInfo)); startupInfo.cb = sizeof(STARTUPINFO); PROCESS_INFORMATION processInfo; ZeroMemory(&processInfo, sizeof(processInfo)); const auto created = CreateProcessW( pat...
In fact, at the time where I was trying to gracefully kill my console, it was too early to get a HWND to the console window. It was in a test where I naively just created the process and then almost straightaway killed it. If I wait long enough (i.e. if I actually interact for some time with the process I created), the...
69,975,909
69,990,751
No matching function call for boost::get in graph
I'm modeling my graph after example geometry/07_a_graph_route_example from boost. My Graph looks like this: typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, gG_vertex_property<string, double, pointClass>, gG_edge_property<listClass, pointClass>> graph_type; graph_type Graph; with gG_vertex_pro...
I guess gG_vertex_property and gG_edge_property are "Bundled" properties (there's no so such thing as custom properties). If so, you should pass these instead of "boost::get(boost::edge_weight, Graph)", which tries to access "Internal" properties, completely separate thing. See https://www.boost.org/doc/libs/1_77_0/lib...
69,976,104
69,978,148
ESP32 WiFi.status() always returns WL_DICSONNECTED (STA_MODE)
I've spent a many hours trying to solve this. I have added multiple attempts, tried to WiFi.disconnect() before Wifi.begin(). Nothing works: statusremains to be WL_DISCONNECTED (0x06). WiFi.mode(WIFI_STA); for(;;) { attempt++; Wifi.begin(ssid, password); wl_status_t status = WiFi.status(); ...
I finally found a solution: The fix is to use WiFi.waitForConnectResult() instead of WiFi.status(). I initially thought it was a bug but as @juraj mentioned, and by examinination of the WiFi code, it is a matter of waiting for the status to come. And the waitFoConnectionResult() does just that. Hence the result. Workin...
69,976,349
69,978,715
Qt/QML: how to redirect console output to syslog
I have a QtQuick/QML application running on a remote embedded target system. I have syslog configured on the target to direct log messages to a log server. Now, I'd like to have the standard out and err console output also redirected to the local syslog so I can get all of my application feedback in one place. Is ther...
Mind that all Qt and QML log will be streamed through this channel. #include <syslog.h> #include <QtGlobal> /// Consider https://linux.die.net/man/3/openlog /// Qt Log Message handler static void qtLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray loc = msg.toU...
69,976,568
70,017,733
Why am I unable to use CreateWICTextureFromFileEx after shutting down SDL
I am trying to shutdown my DX12 renderer, and restart it within the same process. Said application is heavily based on the microsoft MiniEngine example code, now with some modification to allow re-initialisation of global variables. I am using SDL for window and event management. The last stumbling block for a clean sh...
I'll post an answer here but will remove it if @ChuckWalbourn wants to post his own. This was due to letting SDL call CoInitialize for me. When it cleaned up through SDL_Quit, it called CoUninitialize which then (presumably) invalidated the IWICImagingFactory2 set up by WICTextureLoader . By adding a call to CoInitiali...
69,976,985
69,977,182
I'm getting a segmentation fault error in my program, but it is unclear how
From my understanding of segmentation faults, they occur when you try to access memory outside of the "space" of the program. My IDE says the exception occurs within in the first for loop where I perform the following operation: pi = w + i * i; I don't understand how I am accessing memory that I shouldn't access. The p...
Included code has infinitive recursion. Lets call continued_fraction(1, 1). Then we enter for loop which redefines i and set it to 1 then first iteration when it does: continued_fraction(k, i++); it do: continued_fraction(1, 1) since post-increments provides old i. This call is exactly same as first call, so recursion ...
69,977,543
69,977,615
Inconsistent behavior with `empty` std ranges view depending on type
Consider the following code snippet: #include <vector> #include <ranges> #include <iostream> struct A { }; struct B { B(void *) {}; }; template<class T, class R> std::vector<T> foo(R &&range) { return std::vector<T> { std::ranges::begin(range), std::ranges::end(range) }; } int main(...
This is why you should be wary of list-initialization! In particular, this syntax: std::vector<T>{ ... } should only (!!) be used when you're specifically trying to invoke the std::initializer_list<T> constructor, and specifically providing elements to the vector and not in any other case. Like this one, where you're ...
69,977,662
69,977,694
Why is my class size appending an extra byte?
I have the following class structure: #pragma pack(push, 1) class Base{ Base(){} ~Base{} void accept(); }; class A : Base{ int m1; int m2; int m3; }; class B : Base{ A a; int m1; int m2; int m3; int m4; }; #pragma pack(pop) Size of B in this case is 29 bytes. However, when...
The C++ object model doesn't allow two distinct subobjects of the same type to exist at the same address. https://eel.is/c++draft/intro.object#9 Two objects with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a subobject of zero size and...
69,977,740
70,117,729
Box2d: How to get cursor position to apply a velocity to a dynamic body in that direction?
I want to apply a velocity vector to a dynamic body in the cursor direction: void Game::mousePressEvent(QMouseEvent *e){ double angle = atan2(realBall->GetPosition().y - e->pos().y(), realBall->GetPosition().x - e->pos().x()); realBall->SetLinearVelocity(b2Vec2(-cos(angle) * 50, -sin(angle) * 50)); } But the...
First, you must know that in order for your code to work, the coordinates of your screen and the coordinates of box2d must match. Be aware that if you use screen coordinates in pixels, it means that the size of one pixel matches an 1 meter in box2d. But let’s assume that you have already taken all this into account. Th...
69,977,947
69,978,019
Using negation operator ! with std::atomic<uint_32>
I have a working piece of code: #include <atomic> #include <cstdint> int main() { std::atomic<uint32_t> foo; foo = 5; std::cout << foo.load() << std::endl; if (!foo) // what is checked here???????????? { std::cout << "!foo == TRUE\n"; } else { std::cout << "!foo == FA...
What it is trying to do is convert it to a boolean value so that it can determine which block to run. Because 5 is a 'truthy' value, it is converting it to true, and then negating that to false. On the other hand, 0 is a 'falsy' value, so it becomes false negated to true.