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
70,088,044
70,088,152
reversing coordinates in an array variable C++
I am not exactly sure how to phrase this question, sorry for the unhelpful title. I have a large array (5 columns, 50 rows) that I am using to draw out a level environment in ascii text (each entry in the array is a single character and they are all printed out to make an image) i.e: char worldarr[5][9] = { {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, //the length of these entries are actually {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, //50 but I shortened them for the post {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, } where the output is: XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX Now I am trying to set up a coordinate system, where (0,0) is the bottom left hand corner, the goal is to be able to put in a coordinate and have that location replaced with an '@' my original assumption was that I could use this: int x = 0, y = 0; worldarr[y][x] = '@'; but this outputs: @XXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX not: XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX @XXXXXXXX how could I make a new system to force (0,0) to be at the bottom, or better yet, the exact center of the array (if possible). sorry again for the terrible conciseness, I am not sure what I am working with.
Instead of trying to completely remap your array, you could instead wrap the array in a class. Something like: class World { private: static const size_t COLS = 5; static const size_t ROWS = 9; char worldarr[COLS][ROWS] = { {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, //the length of these entries are actually {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, //50 but I shortened them for the post {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, }; public: char* operator[](int indx) { return worldarr[COLS - (indx + 1)]; } }; Then you could use it like: World w; w[0][0] = '@'; See a live example here: https://ideone.com/f6xgBb
70,088,319
70,088,351
Any possibility that I can remove the next line of the code?
... vector<pair<string,double> > wordsWeight; wordsWeight.clear(); ... I am reading a project's code and I often found that the author create variables like above: it first declares an empty vector and then immediately call clear() on it. If it is empty, why should clear() do anything useful? Can I safely remove it and similar statements, or there is some usefulness of it?
If it is empty, why should clear() do anything useful? It doesn't. Can I safely remove it Yes. and similar statements Depends on details.
70,088,374
70,088,850
C++ - Overloading vs Overriding in Inheritance
As far as I learned, Overriding is when you have 2 functions which have the same name and function return type (void, int, float.. etc) and the same parameter numbers and types. And the overloading is when you have 2 functions which have the same name but either Parameter number/types or function return type should be different. But today when I was in the class, I saw this slide: Shouldn't this be overloading? Not overriding? Because here the return type changed (from void to float) and fa1() function in the base class had no parameter, but in the derived class it has float parameter. If this is overriding, why?
In C++, any method in a derived class only overrides the method in the base class if their declarations match (I say "match" but I don't know the formal term for that). That is, all arguments must have the same type, and const qualification of this must be the same. If anything there mismatches, the method in the derived class hides all methods with the same name, instead of overriding. This is what the "ERROR" in your picture tries to tell you. So // overrides in a comment in that picture is incorrect and misleading. Yes, many C++ teachers actually don't understand these somewhat obscure details. BTW additionally, if you want to override, the method in your base class should be virtual; otherwise, polymorphism won't work. If it was not virtual, we also say that the derived-class method hides the base-class method. Here, however, the part about hiding has almost no meaning; what this term really wants to express is that you're not overriding. In addition, overloading is, as you noticed, presence of several methods with the same name but different signatures. They should all be present in the derived class to be useful - if the derived class has only one method fa1, and the other fa1 are in the base, they will be hidden. However, there is syntax sugar which "copies" all fa1 from base to derived, disabling all that hiding semantics: class A { public: void fa1(); void fa1(int); }; class B: public A { public: using A::fa1; void fa1(int, int); }; ... B b; b.fa1(); // calls A::fa1() b.fa1(4); // calls A::fa1(int) b.fa1(4, 8); // calls B::fa1(int, int) The part about hiding is rarely, if ever, useful. When overriding, you should tell this to your compiler - use the override keyword for that. The compiler will then check that your code works as you intended. class A { public: virtual void fa1(int) {} void fa2(int) {} }; class B: public A { public: void fa1(int) override {} // OK void fa1() override {} // ERROR: doesn't really override - different signature void fa2(int) override {} // ERROR: doesn't really override - not virtual in base };
70,088,450
70,088,486
Default value for parameter of class where value is another class
Title may be a little bit confusing but basically I have a class 'Quaternion' which has 2 parameters, the first being another instance of a class Vector3 and the other being a float. Vector3 takes 3 floats as parameters and assigns them to x, y, and z. I want to set default parameters for the Quaternion class but I am unsure how to set default parameters with a class as a parameter. Vector3 class Vector3 { public: float x, y, z; Vector3(float uX, float uY, float uZ) { this->x = uX; this->y = uY; this->z = uZ; } }; Quaternion class Quaternion { public: Vector3 axis; float scalar; Quaternion(Vector3 uAxis, float uScalar = 0) { axis = uAxis; scalar = uScalar; }; }; I would like to have the default parameter for uAxis to be a Vector3 with x, y, and z set to 1, 0, 0 respectively, but i am unsure how i can do this.
I think this is what you were looking for: class Quaternion { public: Vector3 axis; float scalar; Quaternion(Vector3 uAxis = Vector3(1.0, 0.0, 0.0), float uScalar = 0) { axis = uAxis; scalar = uScalar; }; }; It is possible to call a constructor of a class to set a default parameter. Here is the corresponding cpp reference default arguments.
70,088,834
70,090,582
Replace C++ preprocessor macro with something that can initialize a struct
I'm working with WinAPI's CreateDialogIndirect function, which has some requirements on the DLGTEMPLATE and DLGTEMPLATEEX structures pointed to by the second parameter. My code works well, however, I would like to get rid of the #define macros. I created a simplified example to focus on the macros. This is a working program with macros, it can be compiled, and outputs what is expected: #include <iostream> int wmain() { #define TITLE L"Title" struct { wchar_t title[ sizeof( TITLE ) / sizeof( TITLE[ 0 ] ) ]; int font_size; } s = { TITLE, 12, }; std::wcout << L"s.title = " << s.title << std::endl << L"s.font_size = " << s.font_size << std::endl; return 0; } In Visual Studio 2022, I see three dots at the #define macro, and I can read the following tooltip: Macro can be converted to constexpr Show potential fixes Convert macro to constexpr I would like to see it converted to something to avoid macros, so I click on it, and the code is changed to this: #include <iostream> int wmain() { constexpr auto TITLE = L"Title"; struct { wchar_t title[ sizeof( TITLE ) / sizeof( TITLE[ 0 ] ) ]; int font_size; } s = { TITLE, 12, }; std::wcout << L"s.title = " << s.title << std::endl << L"s.font_size = " << s.font_size << std::endl; return 0; } If I hit F7 to compile, I get the following error message: example.cpp(10,9): error C2440: 'initializing': cannot convert from 'const wchar_t *const ' to 'wchar_t' I would not like to enter L"Title" two times, and I would not like to calculate the length of the string manually. So, what can be a good substitute for the macro, which is capable of both initializing the struct and determining the size of the array in the struct?
A template is a reasonably common replacement for macro usage. Since you don't want to manually calculate the length of the string (I don't blame you), let's make a length (the array length, not the string length) the template parameter. Your anonymous struct becomes a likely candidate for being the templated entity, as you do end up with a different type each time you change the length of your title. The actual conversion to a template is simple enough (given the level of the question) that I won't go over the details here. The nifty part comes when you write a constructor. By using the template parameter in the argument list, the compiler will be able to deduce it. This gives you the ease-of-use you appear to be looking for, albeit at the cost of some additional setup. Caveat: Deducing the template parameter via an argument to the constructor is a C++17 feature. Anyone stuck on C++11 or 14 (hopefully not many of you) can get a similar result by writing a separate function template that constructs and returns a struct. I'll leave that as an exercise. #include <iostream> #include <cstring> // For memcpy template <size_t N> struct DlgTemplate { wchar_t title[N]; int font_size; // Constructor that will deduce `N`. // For those not familiar with this syntax: the incoming title_ is a // reference to an array with exactly N elements. DlgTemplate(const wchar_t (&title_)[N], int font_size_) : font_size(font_size_) { // Copy the title. std::memcpy(title, title_, sizeof(title)); } // Reminder: N is the array length, which includes the null terminator. // The string length is N-1. }; int main() { // As of C++17, the template argument can be deduced here. auto s = DlgTemplate(L"Title", 12); std::wcout << L"s.title = " << s.title << std::endl << L"s.font_size = " << s.font_size << std::endl; } The next consideration is probably how to deal with all the fields that were mercifully left out of the question. One option is to add more parameters to the constructor to handle all of the fields. However, in the interest of readability, I might be inclined to remove font_size_ as a constructor parameter (remembering to mark the constructor explicit) then set each field after construction. The following is what I have in mind for the initialization. auto s = DlgTemplate(L"Title"); s.font_size = 12; //s.other_field = value; // etc. There is one important detail to note from the question. The "potential fix" implemented by Visual Studio caused the length information to be lost. constexpr auto TITLE = L"Title"; defines TITLE to be a pointer (to const wchar_t). Its size is fixed, independent of the length of the title. The calculation sizeof( TITLE ) / sizeof( TITLE[ 0 ] ) does not give the length of the title, and this TITLE will not work with the template. constexpr wchar_t TITLE[] = L"Title"; defines TITLE to be an array, with the length information kept as part of the type. This TITLE can be used with the template.
70,088,953
70,088,983
C++ what does the error of "Initial value of reference to a non-const must be an lvalue" mean in this case?
I am a complete beginner to C++ and was assigned to write a function that returns the factors of a number. Below, I have included the function I also created called print_vector that will print all of the elements of a vector to the Console. In my assignment, in order to check if the factorize function is working, we have to use the test_factorize function provided, which I have also included. However, the issue I've run in to is that the given test_factorize does not work due to the error "Initial value of reference to a non-const must be an lvalue." I'm unsure what this means and why the test_factorize runs into an issue because the output of factorize is a vector and the input of print_vector is also a vector, so I don't see why the contents of test_factorize result in an error, though I suspect it might be something within the `factorize' function I defined that causes this error. #include <iostream> #include <vector> using namespace std; void print_vector(std::vector<int>& v) { for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; } std::vector<int> factorize(int n) { std::vector<int> answer; for (int i = 1;i < n + 1; ++i) { if (n % i == 0) { answer.push_back(i); } } return answer; } void test_factorize() { print_vector(factorize(2)); print_vector(factorize(72)); print_vector(factorize(196)); }
The error is from this line: void print_vector(std::vector<int>& v) { Since you didn't include the const keyword in the argument-type, you are (implicitly) indicating that print_vector has the right to modify the contents of v. However, you are calling print_vector() with a temporary object (the vector returned by factorize()) as an argument, and C++ doesn't allow you to pass a temporary object by non-const reference, presumably on the theory that making changes to a temporary object is pointless (because the temporary is going to be destroyed as soon as the function call returns, so any changes made to it would have no effect) and therefore must a programmer error. In any case, the fix is easy, just change your function declaration to this: void print_vector(const std::vector<int>& v) { ... and that will allow you to pass a reference-to-a-temporary-vector to it.
70,090,424
70,090,488
make prototype of overloading function c++
I want to make a overloading function with a prototype in C++. #include <iostream> using namespace std; int rectangle(int p, int l); int main() { cout << rectangle(3); return 0; } int rectangle(int p) { return p*p; } int rectangle(int p, int l) { return p*l; } I got error at int rectangle(int p, int l); is that possible make prototype with a overloading function? if possible how to do it
You've to declare the function before you use/call it. You did declare the 2 argument version of rectangle function but you seem to forget to declare the 1 argument taking version. As shown below if you add the declaration for the 1 argument version then your program works(compiles). #include <iostream> using namespace std; //declare the function before main int rectangle(int p, int l); int rectangle(int p);//ADDED THIS DECLARATION int main() { cout << rectangle(3); return 0; } //define the functions after main int rectangle(int p) { return p*p; } int rectangle(int p, int l) { return p*l; } The output of the program can be seen here. Alternative solution: If you don't want to declare each function separately then you should just define them before main instead of declaring them as shown below. #include <iostream> using namespace std; //define the functions before main. This way there is no need to write a separate function declaration because all definition are declarations int rectangle(int p) { return p*p; } int rectangle(int p, int l) { return p*l; } int main() { cout << rectangle(3); return 0; }
70,090,484
70,090,553
OpenGL: Batch Renderer: Should Transformations Take place on the CPU or GPU?
I am developing a 2D game engine that will support 3D in the future. In this current phase of development, I am working on the batch renderer. As some of you may know, when batching graphics together, uniform support for color (RGBA), texture coordinates, texture ID (texture index), and model transformation matrix go out the window, but instead are passed through the vertex buffer. Right now, I have implemented passing the model's positions, color, texture coordinates, and the texture ID to the vertex buffer. My vertex buffer format looks like this right now: float* v0 = {x, y, r, g, b, a, u, v, textureID}; float* v1 = {x, y, r, g, b, a, u, v, textureID}; float* v2 = {x, y, r, g, b, a, u, v, textureID}; float* v3 = {x, y, r, g, b, a, u, v, textureID}; I am about to integrate calculating where the object should be in world space using a transformation matrix. This leads me to ask the question: Should the transformation matrix be multiplied by the model vertex positions on the CPU or GPU? Something to keep in mind is that if I pass it to the vertex buffer, I would have to upload the transformation matrix once per vertex (4 times per sprite) which to me seems like a waste of memory. On the other hand, multiplying the model vertex positions by the transformation matrix on the CPU seems like it would be slower compared with the GPU's concurrency capabilities. This is how my vertex buffer format would look like if I calculate the transform on the GPU: float* v0 = {x, y, r, g, b, a, u, v, textureID, m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15}; float* v1 = {x, y, r, g, b, a, u, v, textureID, m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15}; float* v2 = {x, y, r, g, b, a, u, v, textureID, m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15}; float* v3 = {x, y, r, g, b, a, u, v, textureID, m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15}; The question is mostly theoretically driven. So, a theoretical and technical answer would be much appreciated. But for reference, here is the code.
Should Transformations Take place on the CPU or GPU? It really depends on the situation at hand. If you resubmit your vertices every frame, it's best to benchmark what's best for your case. If you want to animate without resubmitting all your vertices, you don't have a choice but to apply it on the GPU. Whatever the reason, if you decide to apply the transformations on the GPU, there are better ways of doing that other than duplicating the matrix for each vertex. I'd instead put the transformation matrices in an SSBO: layout(std430, binding=0) buffer Models { mat4 MV[]; // model-view matrices }; and store a single index in each vertex in the VAO: struct Vert { float x, y, r, g, b, a, u, v; int textureID, model; }; The vertex shader can go and fetch the full matrix based on the index attribute: layout(location = 0) in vec4 in_pos; layout(location = 1) in int in_model; void main() { gl_Position = MV[in_model] * in_pos; } You can even combine it with other per-object attributes, like the textureID. EDIT: you can achieve something similar with instancing and multi-draw. Though it's likely to be slower.
70,090,540
70,090,865
Sharing global variable from C++ library to C main program
I have gstdsexample.so, a C++ library. Inside, it has two global variables that I'd like to share between the library and the main C program. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; Test two scenarios. Scenario 1 sharedata.h #ifndef __SHARE_DATA_H__ #define __SHARE_DATA_H__ #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; #endif /* __SHARE_DATA_H__ */ Include sharedata.h in gstdsexample.cpp and main.c. Compilation OK but I get a segmentation fault when gstdsexample.cpp writes data to *ptr. Scenario 2 Declare two variables in gstdsexamle.cpp pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; Then declare as extern in main.c. extern pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; extern int *ptr; Now I have undefined reference errors to the two variables when compiling main.c. Scenario 3: #ifndef __SHARE_DATA_H__ #define __SHARE_DATA_H__ #include <stdio.h> #include <pthread.h> extern "C" { pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; } #endif /* __SHARE_DATA_H__ */ Then include sharedata.h in gstdsexample.cpp and main.c. Compiling for cpp lib is fine. But compiling for main.c has errors as error: expected identifier or β€˜(’ before string constant extern "C" { ^~~ deepstream_app_main.c: In function β€˜all_bbox_generated’: deepstream_app_main.c:98:24: error: β€˜mutex’ undeclared (first use in this function); did you mean β€˜GMutex’? pthread_mutex_lock( &mutex ); ^~~~~ GMutex deepstream_app_main.c:98:24: note: each undeclared identifier is reported only once for each function it appears in deepstream_app_main.c:101:21: error: β€˜ptr’ undeclared (first use in this function); did you mean β€˜puts’? printf("%d ", *(ptr+x)); How to share variables between C++ and C source files?
in a header file... gstdsexamle.h // disable name mangling in C++ #ifdef __cplusplus extern "C" { #endif // declare your two vars in the header file as extern. extern pthread_mutex_t mutex; extern int *ptr; #ifdef __cplusplus } #endif in gstdsexamle.c #include "gstdsexamle.h" /* only initialise here */ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; in main.c #include "gstdsexamle.h" Thats all you need. mutex & ptr are now available in main.cpp/main.c
70,090,770
70,091,183
Passing float to a function in C++ appears to change precision
This is a very noob question, but I am curious to know the reason behind this: -If I debug the following C++ code: void floatreturn(float i){ //nothing } int main(){ float a = 23.976; floatreturn(a); return 0; } Monitoring the passed value of a, it appears to be 23.9759998 when entering floatreturn. As a result, any processing of the value in the function would require to manually tweak the precision. Is there a reason for this, and any way to avoid it?
The issue happened before floatreturn(a);. It happened at float a = 23.976; floatreturn(a); is irrelevant. There are about 2^32 different values that float can encode exactly. 23.976 is not one of them. The nearest encodable float is about 23.9759998... To avoid, use values that can exactly encode as a float or tolerate being close - about 1 part in 224
70,090,929
70,091,811
Can variables be used in function call in ellipsis functions in C++
For this function that takes variable number of arguments, void func(int count, ...) // ellipsis function { // function definition } Can a function call be made like follows : int a{}; double b{}; string c{}; func(3,a,b,c); // using actual variables instead of fixed values in function call My question is when an ellipsis function is called does it always has to be just fixed values like func(3,5,2.7,"Hi") or can variables be supplied in the function call like so func(3,a,b,c)?
Note that passing classes like std::string, with non-trivial copy constructor or nontrivial move constructor or non-trivial destructor, may not be supported and has "implementation-defined" semantics. You have to check your compiler documentation on how such classes are passed or check if they are supported at all. Can variables be used in function call in ellipsis functions in C++ Yes. Can a function call be made like follows Yes. when an ellipsis function is called does it always has to be just fixed values like func(3,5,2.7,"Hi") No. can variables be supplied in the function call like so func(3,a,b,c)? Yes. Can you suggest any reference so I can do some research on it? https://en.cppreference.com/w/cpp/language/variadic_arguments https://en.cppreference.com/w/cpp/utility/variadic https://eel.is/c++draft/expr#call-12 And in C++ you should strongly prefer: https://en.cppreference.com/w/cpp/language/parameter_pack , because of type safety.
70,091,028
70,091,115
segmentation fault with char* buffer in getline() function
I get segmentation file in the below code. The reason is in the line 10 I guess where I'm using char* buffer. I want to know why is this. Is it because the memory in the buffer is not still allocated? Here is the code: 1 #include <iostream> 2 #include <fstream> 3 4 int main() 5 { 6 const char* filename = "directory of my file";// mnt/c/Users/... 7 std::fstream fin(filename,std::fstream::in); 8 if(!fin.is_open()) 9 std::cout << "Opps!" << std::endl; 10 char* buffer = NULL;//if char buffer[100] then it will be good. 11 while(!fin.eof()) 12 { 13 fin.getline(buffer,100); 14 std::cout << buffer << std::endl; 15 } 16 return 0; 17 }
Is it because the memory in the buffer is not still allocated? Yes. In fact, you don't even have a buffer. The pointer buffer is NULL, meaning it points to a memory location that you have no business accessing. You then went ahead and told getline() it can write up to 100 bytes starting from that address. It worked when you used char buffer[100] because that's an array allocated on the stack, large enough to hold the upper limit of 100 bytes that you promised getline() could be written. If you don't know the length of a line in advance and want to be able to handle arbitrary lengths, consider using std::string instead. Here is the typical way to read a file line-by-line in C++: std::string line; while (std::getline(fin, line)) { std::cout << line << "\n"; } Please also read: Why is iostream::eof inside a loop condition considered wrong?
70,091,096
70,102,583
How to return intersecting linestrings in boost::geometry::intersection(ring1, ring2, vector_of_linestring)?
I have 2 rings A and B, and I want to use boost::geometry::intersection() to return linestrings (the orange arrow ones): But my code only returns the intersecting points P1 and P2. Which part should I modify? #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/register/ring.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <iostream> namespace bg = boost::geometry; typedef bg::model::point<double, 2, bg::cs::cartesian> point_t; typedef bg::model::linestring<point_t> linestring_t; typedef bg::model::ring<point_t> ring_t; typedef bg::model::polygon<point_t> polygon_t; typedef bg::model::multi_point<point_t> mpoint_t; typedef bg::model::multi_linestring<linestring_t> mlinestring_t; typedef bg::model::multi_polygon<polygon_t> mpolygon_t; int main() { point_t ptA0(0, 0); point_t ptA1(10, 0); point_t ptA2(10, 10); point_t ptA3(0, 10); ring_t ringA; bg::append(ringA, ptA0); bg::append(ringA, ptA1); bg::append(ringA, ptA2); bg::append(ringA, ptA3); bg::append(ringA, ptA0); point_t ptB0(5, -5); point_t ptB1(15, -5); point_t ptB2(15, 5); point_t ptB3(5, 5); ring_t ringB; bg::append(ringB, ptB0); bg::append(ringB, ptB1); bg::append(ringB, ptB2); bg::append(ringB, ptB3); bg::append(ringB, ptB0); std::vector<linestring_t> resline; bg::intersection(ringB, ringA, resline); for (int i = 0; i < resline.size(); i++) { std::cout << bg::dsv(resline[i]) << std::endl; } return 0; } Below is the output: (10, 5) is P1 and (5, 0) is P2, which is not what I expected. ((10, 5), (10, 5)) ((5, 0), (5, 0))
I've tried to get a handle on this problem using just the DE-9IM that Boost Geometry implements: https://godbolt.org/z/KWzvzExr7 which outputs https://pastebin.ubuntu.com/p/9ck6gcPK5P/ ---- void do_test(Input, Input) [with Input = boost::geometry::model::ring<boost::geometry::model::point<int, 2, boost::geometry::cs::cartesian> >] a: POLYGON((0 0,0 10,10 10,10 0,0 0)) b: POLYGON((5 -5,5 5,15 5,15 -5,5 -5)) MULTIPOINT((10 5),(5 0)) MULTIPOLYGON(((10 5,10 0,5 0,5 5,10 5))) Segment of ringB LINESTRING(5 -5,5 5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] Segment of ringB LINESTRING(5 5,15 5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] Segment of ringB LINESTRING(15 5,15 -5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] Segment of ringB LINESTRING(15 -5,5 -5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] ---- void do_test(Input, Input) [with Input = boost::geometry::model::linestring<boost::geometry::model::point<int, 2, boost::geometry::cs::cartesian> >] a: LINESTRING(0 0,0 10,10 10,10 0,0 0) b: LINESTRING(5 -5,5 5,15 5,15 -5,5 -5) MULTIPOINT((10 5),(5 0)) Segment of ringB LINESTRING(5 -5,5 5) relates to ringA ['F', 'F', '1'] ['F', 'F', 'F'] ['F', 'F', '2'] Segment of ringB LINESTRING(5 5,15 5) relates to ringA ['F', 'F', '1'] ['F', 'F', 'F'] ['F', 'F', '2'] Segment of ringB LINESTRING(15 5,15 -5) relates to ringA ['F', 'F', '1'] ['F', 'F', 'F'] ['F', 'F', '2'] Segment of ringB LINESTRING(15 -5,5 -5) relates to ringA ['F', 'F', '1'] ['F', 'F', 'F'] ['F', 'F', '2'] ---- void do_test(Input, Input) [with Input = boost::geometry::model::polygon<boost::geometry::model::point<int, 2, boost::geometry::cs::cartesian> >] a: POLYGON((0 0,0 10,10 10,10 0,0 0)) b: POLYGON((5 -5,5 5,15 5,15 -5,5 -5)) MULTIPOINT((10 5),(5 0)) MULTIPOLYGON(((10 5,10 0,5 0,5 5,10 5))) Segment of ringB LINESTRING(5 -5,5 5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] Segment of ringB LINESTRING(5 5,15 5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] Segment of ringB LINESTRING(15 5,15 -5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] Segment of ringB LINESTRING(15 -5,5 -5) relates to ringA ['F', 'F', '2'] ['F', 'F', '1'] ['F', 'F', '2'] but as far as I can see all the results are at least fully disjoint. So you might have to zoom in on the points instead of the segments: Live On Wandbox #include <boost/geometry.hpp> #include <boost/geometry/geometries/ring.hpp> #include <boost/geometry/iterators/segment_iterator.hpp> #include <iostream> namespace bg = boost::geometry; using point_t = bg::model::point<int, 2, bg::cs::cartesian>; using ring_t = bg::model::ring<point_t>; using mpoint_t = bg::model::multi_point<point_t>; void do_test(ring_t ringA, ring_t ringB) { std::string reason; if (!bg::is_valid(ringA, reason)) { std::cout << "warning ringA: " << reason << "\n"; bg::correct(ringA); } if (!bg::is_valid(ringB, reason)) { std::cout << "warning ringB: " << reason << "\n"; bg::correct(ringB); } std::cout << "ringA: " << bg::wkt(ringA) << std::endl; std::cout << "ringB: " << bg::wkt(ringB) << std::endl; mpoint_t result; bg::intersection(ringA, ringB, result); std::cout << bg::wkt(result) << std::endl; for (auto seg : boost::make_iterator_range(bg::segments_begin(ringB), bg::segments_end(ringB))) { for (auto& p : result) if (bg::intersects(p, seg)) std::cout << bg::wkt(p) << " intersects " << bg::wkt(seg) << "\n"; } } int main() { do_test({{0, 0}, {0, 10}, {10, 10}, {10, 0}/*, {0, 0}*/}, {{5, -5}, {5, 5}, {15, 5}, {15, -5}/*, {5, -5}*/}); } Prints warning ringA: Geometry is defined as closed but is open warning ringB: Geometry is defined as closed but is open ringA: POLYGON((0 0,0 10,10 10,10 0,0 0)) ringB: POLYGON((5 -5,5 5,15 5,15 -5,5 -5)) MULTIPOINT((10 5),(5 0)) POINT(5 0) intersects LINESTRING(5 -5,5 5) POINT(10 5) intersects LINESTRING(5 5,15 5)
70,092,075
70,092,253
How do you pass user input from main to other classes?
#include <iostream> #include "multiplication.h" #include "subtraction.h" using namespace std; int main() { multiplication out; subtraction out2; int x, y, z; int product; int difference; cout << "Enter two numbers to multiply by: "; cin >> x; cin >> y; product = out.mult(); cout << "the product is: " << product; cout << "Now enter a number to subtract the product by: "; cin >> z; difference = out2.sub(); cout << "the difference is: " << difference; } #pragma once class multiplication { public: int mult(); }; #include <iostream> using namespace std; #include "multiplication.h" int multiplication::mult(int x, int y) { return x * y; } #pragma once class subtraction { public: int sub(); }; #include <iostream> using namespace std; #include "subtraction.h" int subtraction::sub(int product, int z) { return product - z; } I need to pass the user input variables from main to mult and the user input z and product from main to sub. I tried passing them as args in the functions I've created, but they are not accessed. Edit: I added multiplication.h and subtraction.h In them I just have the call to the function declarations for the class.
You should pass them to the function call as arguments difference = out2.sub(x, y); In the .h files you should define them with arguments class subtraction { public: int sub(int x, int y); }; Function overloading
70,092,277
70,093,623
How to replace NDEBUG by C++ means
So I use preprocessor macro NDEBUG to enable some checks for my debug build. But I would like to replace it with C++ constant to use it in noexept clause and in static if. I know I can probably achieve it like so: // in constants.hpp #ifdef NDEBUG constexpr bool ndebug = true; #else constexpr bool ndebug = false; #endif But with NDEBUG you can, for example, supply -D NDEBUG flag to compiler, but for certain files you can manually specify #undef NDEBUG. So parts of code will be compiled with NDEBUG and parts will be compiled without it. So even within one translation unit there will be parts with defined NDEBUG and parts without it. Is it possible with C++ means to devise something that will 100% conform to this behavior, so in every header file there would be compile-time bool constant with value based on NDEBUG? You can of course create constants with different name in each file, if it is the only way can you at least somehow automate this?
If you use variable or function, you will probably have ODR violation if you mix file with NDEBUG defined or not with those variable/function. You can though declare a MACRO with a value matching NDEBUG presence. #ifdef NDEBUG # define NDEBUG_VALUE true #else # define NDEBUG_VALUE false #endif to use it in noexept clause and in static if But still care, as ODR-violation can happen quickly. All definitions should be identical.
70,093,274
70,093,437
^ after data type in Visual C++
What does ^ mean near the c++ data type? This seems to only work in visual studio C++ and is clearly not a standard C++ syntax, so what does it do here? I am familiar with pointer * and reference &, but to see ^ after the data type, I have no clue.
In C++/CLI and C++/CX, ^ is the Handle to Object Operator: The handle declarator (^, pronounced "hat"), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible. ... Because native C++ pointers (*) and references (&) are not managed references, the garbage collector cannot automatically update the addresses they point to. To solve this problem, use the handle declarator to specify a variable that the garbage collector is aware of and can update automatically.
70,093,511
70,095,761
how to write a C++ debug function in Windows?
I want to write a windows debug function like linux one: #define debug(fmt, ...) printf("[%s:%d]"fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
In order for string concatenation like that to work, you need spaces between the strings. So this part: "[%s:%d]"fmt"\n" changes to "[%s:%d]" fmt "\n" Otherwise, fmt is assumed to be a string literal operator (operator""fmt), which you don't want here. Don't forget to include <cstdio> for printf, and then it should work as expected.
70,093,863
70,110,667
Linux BTF: bpftool: Failed to get EHDR from /sys/kernel/btf/vmlinux
I am trying to start with BPF CO:RE Development. Using Ubuntu 20.04 LTS in a VM, I needed to recompile the kernel and install pahole (from apt install dwarves) so that BTF is enabled (I set CONFIG_DEBUG_FS=y and CONFIG_DEBUG_INFO_BTF=y). So my setup is: Ubuntu 20.04 Kernel 5.4.0-90-generic bpftool --version: /usr/lib/linux-tools/5.4.0-90-generic/bpftool v5.4.148 /sys/kernel/btf/vmlinux exists and can be read out with cat. But bpftool shows the following error: $ sudo bpftool btf dump file /sys/kernel/btf/vmlinux format c libbpf: failed to get EHDR from /sys/kernel/btf/vmlinux Error: failed to load BTF from /sys/kernel/btf/vmlinux: Unknown error -4001 From https://github.com/libbpf/libbpf/blob/master/src/libbpf.h it looks like it is LIBBPF_ERRNO__FORMAT, /* BPF object format invalid */ but I can not find out what's wrong. Does anybody know where the mistake might be? Thanks in advance! EDIT: Added bpftool version
You need to update bpftool to support a fallback to reading BTF as raw data if the input file is not an object file. The minimum bpftool version required is v5.5 as that's the Linux release where the patch landed. In general, I would recommend to always use the latest bpftool version as there are no backports.
70,093,991
70,094,081
GCC #pragma or command options
If the compiler has some command-line flags and the code has some pragmas that are incompatible with those flags, which one will be used? To be clearer: I am compiling with g++ -g -O2 -std=gnu++17 -static {files} – GCC version g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0. If I write in my code #pragma GCC optimize("Ofast"), will the final code be compiled with -O2 or with -Ofast?
That depends on if it's above or below the pragma. void this_will_be_compiled_with_O2() { stuff(); } #pragma GCC optimize("Ofast") void this_will_be_compiled_with_Ofast() { stuff(); }
70,094,288
70,096,468
Why Queue Give me 0 in last display function
#include <iostream> #define size 100 using namespace std; class Q { private: int item[size]; int front, rear; public: Q() { front = -1; rear = -1; } bool is_empty(); bool is_full(); void enque(int num); void deque(); void display(); }; bool Q::is_full() { return rear == size - 1; } void Q::enque(int num) { if (is_full()) cout << "Sorry Enque Is Full !!" << endl; if (front == -1) front = 0; rear++; item[rear] = num; } bool Q::is_empty() { return front == -1; } void Q::deque() { if (is_empty()) { cout << "Q is Empty You Can't Deque From it" << endl; exit(0); } if (front == rear) { front = -1; rear = -1; } else front++; } void Q::display() { for (int i = front; i <= rear; i++) { cout << item[i] << "\t"; } cout << endl; } int main() { Q q; q.enque(1); // front=0; //rear=0 q.enque(2); // front=0 //rear=1 q.display(); // display fron 0 to 1 q.deque(); q.deque(); q.display(); return 0; } When i try to compare my code with another code my code give in the second display 0 but other code give me -1 and he ask me to print -1 if Queue is empty so why it give me 0 when queue is empty and i make condition to reset values it front==rear in dequeue function if anyone give me hand to solve this problem i will be thankful The Second code with output -1 #include #define size 100 using namespace std; class Queue { private: int front, rear; int items[size]; public: Queue(); bool isempty(); bool isfull(); void enqueue(int x); int dequeue(); void dispaly(); }; Queue::Queue() { rear = -1; front = -1; } bool Queue::isempty() { if (front > rear || front == -1) return true; return false; } bool Queue::isfull() { if (rear == size - 1) return true; return false; } void Queue::enqueue(int x) { if (isfull()) { cout << "Queue is overflow\n"; return; } if (front == -1) { front = 0; } rear++; items[rear] = x; } int Queue::dequeue() { if (isempty()) { cout << "Queue is underflow\n"; exit(0); } int x = items[front]; if (rear == front) { front = -1; rear = -1; } else front++; return x; } void Queue::dispaly() { cout << "Elements in queue : "; for (int i = front; i <= rear; i++) { cout << items[i] << "\t"; } cout << endl; } int main() { Queue Q; Q.enqueue(1); Q.enqueue(2); Q.dispaly(); Q.dequeue(); Q.dequeue(); Q.dispaly(); return 0; }
We should check whether the Q contains elements or not and then start printing. void Queue::display() { if (is_empty()) { cout << "Q is Empty You Can't Deque From it" << endl; return; } cout << "Elements in queue : "; for (int i = front; i <= rear; i++) { cout << items[i] << "\t"; } cout << endl; }
70,095,010
70,100,359
Detect if C++ class has a template method
I know how to detect presence of a variable or a regular method in a C++ class. But how to do it, when the method is a template? Consider the code: struct SomeClass { template<typename Sender, typename T> auto& send(T& object) const { Sender::send(object); return object; }; }; How to write something like is_sendable so that is_sendable<SomeClass>::value (or any other syntax) returns true because SomeClass has method send like above ?
Ok, I acutally managed to solve it, if anyone is interested: I needed to create a dummy class class DummySender { public: template<typename T> static void send(const T&) {} }; And then I can check for the presence of the send method, by defining type traits: template<typename T, typename = void> struct IsSendable: std::false_type {}; template<typename T> struct IsSendable<T, decltype(std::declval<T>().send<DummySender>(std::cout), void())> : std::true_type {}; To finally have IsSendable<SomeClass>::value.
70,095,337
71,733,584
How can I get specific std::map value with indexing while using gdb for debuggin c++ code?
I use Ubuntu 20.04-LTS with WSL(Windows Subsystem Linux), GDB version is 9.2, and I builded my c++ code with c++11. I tried to access std::map's value with index in GDB, however GDB showed error message "Invalid cast". My code is same for below #include <iostream> #include <map> #include <string> using std::cout; using std::map; using std::string; using std::to_string; int main() { map<string, int> si; for(int i = 0; i < 10; ++i) { si[to_string(i)] = i; } for(int i = 0; i < 10; ++i) { cout << si[to_string(i)] << "\n"; } } And, in GDB GNU gdb (Ubuntu 9.2-0ubuntu1~20.04) 9.2 Copyright (C) 2020 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ctest... (gdb) l main 6 using std::map; 7 using std::string; 8 using std::to_string; 9 10 int main() 11 { 12 map<string, int> si; 13 14 for(int i = 0; i < 10; ++i) 15 { (gdb) l 15 10 int main() 11 { 12 map<string, int> si; 13 14 for(int i = 0; i < 10; ++i) 15 { 16 si[to_string(i)] = i; 17 } 18 19 for(int i = 0; i < 10; ++i) (gdb) b 18 Breakpoint 1 at 0x2579: file ctest.cpp, line 19. (gdb) r Starting program: /home/lksj/ctest Breakpoint 1, main () at ctest.cpp:19 19 for(int i = 0; i < 10; ++i) (gdb) p si["1"] Invalid cast. (gdb) How can I access the std::map object value directly with index in GDB?
You first write the below code in the ".gdbinit" file. define newstr set ($arg0)=(std::string*)malloc(sizeof(std::string)) call ($arg0)->basic_string() # 'assign' returns *this; casting return to void avoids printing of the struct. call (void)( ($arg0)->assign($arg1) ) end define delstr call ($arg0)->~basic_string(0) # ^ call free($arg0) set ($arg0)=(void*)0 end And then write the below function in your c++ code. void indexing_map( map<string,[type]> & m, string i ) { cout << m[i] << "\n"; } Now, all things are ready. You just execute gdb for debugging your code with the newstr $foo [any string of map of the key] For example, example.cpp #include <iostream> #include <unordered_map> #include <string> using std::cout; using std::unordered_map; using std::string; void indexing_map(unordered_map<string, int> &m, string i) { cout << m[i] << "\n"; } int main() { unordered_map<string, int> st_in; st_in["1"] = 1; st_in["2"] = 2; st_in["3"] = 3; indexing_map(st_in, "1"); return 0; } and gdb (gdb) b 25 Breakpoint 1 at 0x28d6: file ctest.cpp, line 25. (gdb) r Starting program: /home/user/ctest [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Breakpoint 1, main () at ctest.cpp:25 25 st_in["3"] = 3; (gdb) newstr $foo "1" (gdb) call indexing_map(st_in , *$foo) 1
70,095,549
70,095,784
How do I stop segmentation error with array in C++?
I am creating a simple command line, tic-tac-toe game in C++. Whenever I reun the code I get no compiler errors but then VSCode tells me once I have given input that there is a Segmentation Fault. I will paste my code below: #include <iostream> #include <cmath> using namespace std; void print_board(string board[3][3]) { cout << " | | " << endl; cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " " << endl; cout << "_____|_____|_____" << endl; cout << " | | " << endl; cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " " << endl; cout << "_____|_____|_____" << endl; cout << " | | " << endl; cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " " << endl; cout << " | | " << endl; } string turn(string board[3][3], bool xturn) { int position; cout << "Where would you like to go (1 - 9): "; cin >> position; if (xturn) { string player_turn = "X"; } else { string player_turn = "O"; } board[(int)floor(position / 3)][(position % 3) - 1] = "X"; return board[3][3]; } int main(void) { string board[3][3] = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}}; bool xturn = true; while (true) { print_board(board); board[3][3] = turn(board, xturn); xturn = !xturn; } return 0; } Any help is much is much appreciated. Thanks! If it helps I am using the GCC compiler.
void print_board(string board[3][3]) why are you using a string[3][3] ? you basically just need a 3x3 character array board[(int)floor(position / 3)][(position % 3) - 1] = "X"; make sure you keep yourself in range 0..2, -1 is outside and will cause undefined behavior return board[3][3]; No that is wrong in more ways than one, and in any case there is no need to return a copy board[3][3] = turn(board, xturn); this will not go well, you return a board of 3x3 strings but assign it to at best, an undefined place. since you already pass the address of the board to your turn function, that is that is all needed. change it in place. turn(board, xturn); arrays are addresses in memory, it is the starting address where in memory some data is stored if you pass an array/matrix to a function you are letting the function know where in memory it is stored, so any changes to the array/matrix will be done in place, therefore you do not need to return a copy.
70,095,987
70,102,829
boost program_options: Read required parameter from config file
I want to use boost_program_options as follows: get name of an optional config file as a program option read mandatory options either from command line or the config file The problem is: The variable containing the config file name is not populated until po::notify() is called, and that function also throws exceptions for any unfulfilled mandatory options. So if the mandatory options are not specified on the command line (rendering the config file moot), the config file is not read. The inelegant solution is to not mark the options as mandatory in add_options(), and enforce them 'by hand' afterwards. Is there a solution to this within the boost_program_options library? MWE bpo-mwe.conf: db-hostname = foo db-username = arthurdent db-password = forty-two Code: #include <stdexcept> #include <iostream> #include <fstream> #include <filesystem> #include <string> #include <boost/program_options.hpp> // enable/disable required() below #ifndef WITH_REQUIRED #define WITH_REQUIRED #endif namespace po = boost::program_options; namespace fs = std::filesystem; int main(int argc, char *argv[]) { std::string config_file; po::options_description generic("Generic options"); generic.add_options() ("config,c", po::value<std::string>(&config_file)->default_value("bpo-mwe.conf"), "configuration file") ; // Declare a group of options that will be // allowed both on command line and in // config file po::options_description main_options("Main options"); main_options.add_options() #ifdef WITH_REQUIRED ("db-hostname", po::value<std::string>()->required(), "database service name") ("db-username", po::value<std::string>()->required(), "database user name") ("db-password", po::value<std::string>()->required(), "database user password") #else ("db-hostname", po::value<std::string>(), "database service name") ("db-username", po::value<std::string>(), "database user name") ("db-password", po::value<std::string>(), "database user password") #endif ; // set options allowed on command line po::options_description cmdline_options; cmdline_options.add(generic).add(main_options); // set options allowed in config file po::options_description config_file_options; config_file_options.add(main_options); // set options shown by --help po::options_description visible("Allowed options"); visible.add(generic).add(main_options); po::variables_map variable_map; // store command line options // Why not po::store? //po::store(po::parse_command_line(argc, argv, desc), vm); store(po::command_line_parser(argc, argv).options(cmdline_options).run(), variable_map); notify(variable_map); // <- here is the problem point // Problem: config_file is not set until notify() is called, and notify() throws exception for unfulfilled required variables std::ifstream ifs(config_file.c_str()); if (!ifs) { std::cout << "can not open configuration file: " << config_file << "\n"; } else { store(parse_config_file(ifs, config_file_options), variable_map); notify(variable_map); } std::cout << config_file << " was the config file\n"; return 0; }
I'd simply not use the notifying value-semantic to put the value in config_file. Instead, use it directly from the map: auto config_file = variable_map.at("config").as<std::string>(); Now you can do the notify at the end, as intended: Live On Coliru #include <boost/program_options.hpp> #include <fstream> #include <iomanip> #include <iostream> namespace po = boost::program_options; int main(int argc, char *argv[]) { po::options_description generic("Generic options"); generic.add_options() ("config,c", po::value<std::string>()->default_value("bpo-mwe.conf"), "configuration file") ; // Declare a group of options that will be allowed both on command line and // in config file struct { std::string host, user, pass; } dbconf; po::options_description main_options("Main options"); main_options.add_options() ("db-hostname", po::value<std::string>(&dbconf.host)->required(), "database service name") ("db-username", po::value<std::string>(&dbconf.user)->required(), "database user name") ("db-password", po::value<std::string>(&dbconf.pass)->required(), "database user password") ; // set options allowed on command line po::options_description cmdline_options; cmdline_options.add(generic).add(main_options); // set options allowed in config file po::options_description config_file_options; config_file_options.add(main_options); // set options shown by --help po::options_description visible("Allowed options"); visible.add(generic).add(main_options); po::variables_map variable_map; //po::store(po::parse_command_line(argc, argv, desc), vm); store(po::command_line_parser(argc, argv).options(cmdline_options).run(), variable_map); auto config_file = variable_map.at("config").as<std::string>(); std::ifstream ifs(config_file.c_str()); if (!ifs) { std::cout << "can not open configuration file: " << config_file << "\n"; } else { store(parse_config_file(ifs, config_file_options), variable_map); notify(variable_map); } notify(variable_map); std::cout << config_file << " was the config file\n"; std::cout << "dbconf: " << std::quoted(dbconf.host) << ", " << std::quoted(dbconf.user) << ", " << std::quoted(dbconf.pass) << "\n"; // TODO REMOVE FOR PRODUCTION :) } Prints eg. $Β ./sotest bpo-mwe.conf was the config file dbconf: "foo", "arthurdent", "forty-two" $Β ./sotest -c other.conf other.conf was the config file dbconf: "sbb", "neguheqrag", "sbegl-gjb" $Β ./sotest -c other.conf --db-user PICKME other.conf was the config file dbconf: "sbb", "PICKME", "sbegl-gjb" Where as you might have guessed other.conf is derived from bpo-mwe.conf by ROT13.
70,097,152
70,097,267
Is there an easier way of finding cpp executable in visual studio?
I've started programming in c++ and I recently switched from a text editor to visual studio's ide, and I found out how to compile a single hello world. But it takes a bit to actually find the executable which is in a mess of folders full of a bunch of different files. Is there just an easier way to find the file? Or change where the file is compiled at?
In visual Studio (not code), go to the Project menu, then to <Project_name> properties. In the popup window go to Configuration properties/General, you will find the output directory. Plan B: when building your solution, the full path of the exe is displayed in the console output.
70,097,673
70,097,800
How to continue to next item in iterator using recursive_directory_iterator
I am currently iterating through a filesystem. I want to capture any errors that occur and then just continue iterating. The current behavior if an error occurs it will set the current iterator to the end and then the for loop exits. I would like for this to skip that path and continue. try { for (const auto& dirEntry : recursive_directory_iterator(myPath)) { std::cout << dirEntry << std::endl; } } catch (...) { std::cout << "ERROR" << std::endl; //continue iteration } EDIT: This is my little sample that I am working with. The error occurs on the recursive_directory_iterator. Specifically it errors out when accessing a folder it does not have access to. I know I can add std::filesystem::directory_options::skip_permission_denied and it will skip those folders, but what about just errors in general? I am not sure if that would ever occur so maybe I am overthinking it? Would permissions be the only reason this would error?
You can't recover from errors in recursive_directory_iterator. If the recursive_directory_iterator reports an error or is advanced past the last directory entry of the top-level directory, it becomes equal to the default-constructed iterator, also known as the end iterator. From cppreference
70,098,010
70,100,138
Can I move construct (or assign) to a map a different type values using conversion?
I have a simple container for data (simplified more for the purpose of this question) that I use as a value in a map. I want to know if there is some way I can move construct a map with this container as a value type from a map using the underlying data type. Here is such a class: class D { public: D() :m_value(0.0){} D(double value) : m_value(std::move(value)) {} D(const D& from) : m_value(from.m_value) {} D(D&& from) : m_value(std::move(from.m_value)) {} D& operator= (const D& from) { m_value = from.m_value; return *this; } D& operator= (D&& from) { m_value = std::move(from.m_value); return *this; } ~D() = default; double m_value; }; And here is an example of how I would like to convert it. int main() { std::map<std::string, double> m = { { "1", 1.0 } }; std::map<std::string, D> m_map = std::move(m); return 0; } This gives the following error: error C2440: 'initializing' : cannot convert from 'std::map<std::string,double,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' to 'std::map<std::string,D,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' I would like to note that the main reason I would like to move construct such a map, is to avoid creating copies of the key values of the map. Which in this case is a string.
Something along these lines, perhaps (requires C++17): std::map<Key, long> new_m; while (!m.empty()) { auto node = m.extract(m.begin()); new_m.emplace(std::move(node.key()), std::move(node.mapped())); } Demo. I made a user-defined class the key of the map rather than std::string, so that I could instrument it and confirm it's indeed being moved and not copied.
70,098,210
70,098,738
Can I throw exceptions through functions compiled w/o exceptions
Let we have two libraries: libA.a and libB.a. They are organised s.t. libA.a calls libB.a functions and provides a callback to itself. In other words, the following call stack is possible: #0 liba_callback() #1 libb_function() #2 liba_function() libA.a is compiled with -fexceptions and libB.a is compiled with -fno-exceptions. The question is: what happens if liba_callback() throws? Can I handle this in liba_function()? Can I throw exceptions through functions compiled w/o exceptions? Is this behaviour defined?
As @Pete Becker noted, exceptions are part of the language, so the compiler is responsible for documenting such C++ dialect. The GCC documentation says: Before detailing the library support for -fno-exceptions, first a passing note on the things lost when this flag is used: it will break exceptions trying to pass through code compiled with -fno-exceptions whether or not that code has any try or catch constructs. If you might have some code that throws, you shouldn't use -fno-exceptions. If you have some code that uses try or catch, you shouldn't use -fno-exceptions. In particular, hitting a stack frame with no unwind information is problematic: In particular, unwinding into a frame with no exception handling data will cause a runtime abort. If the unwinder runs out of unwind info before it finds a handler, std::terminate() is called. To sum up: The question is: what happens if liba_callback() throws? abort() is called. Can I handle this in liba_function()? No. Can I throw exceptions through functions compiled w/o exceptions? No. Is this behaviour defined? No. It is only documented as a compiler extension.
70,098,331
70,098,459
Conventions for using std::feclearexcept
Is there any convention for using std::feclearexcept? In the examples you usually see, this is called before an operation is executed that might trigger a floating point exception. This seems a safe thing to do. But should you also call std::feclearexcept after you have detected and handled an error, so that the error state does not persist throughout the rest of the program's execution? If you would always call std::feclearexcept before checking for floating point exceptions, and if you would always check all operations that could trigger such exceptions, then this would be redundant. But these are a lot of ifs and an unlikely situation in real software, at least from my experience.
Simlar in reasoning to (re-)setting errno only before you do a specific operation and intend to check errno afterwards. There might be conditions under which errno, or the floating point exception flags, are set that you are not aware of. You don't know where exactly they happened or what they mean semantically. You are not equipped to handle a situation of "uh, there was an overflow somewhere in the past but I don't know what it means". Thus, you reset errno / call std::feclearexcept right before you execute a specific operation where you want to know the exact result / error condition, and do know how to handle it. Resetting the error flags after that operation serves no purpose.
70,098,533
70,098,864
C++ How to read input N and then read a series of numbers N long?
I'm working on an assignment where I need to create a program that reads a non-empty sequence of integer numbers, and tells how many of them are equal to the last one. It should read the amount of integers the sequence has and then read the sequence itself and return the amount of times the last number repeats itself excluding the last one. Input would be like this: 9 1 7 3 2 4 7 5 8 7 and the output should be: 2 Now, I have no problem with the functionality of the program but I'm struggling on having it read the inputs. This is what I got: #include <iostream> #include <vector> #include <sstream> int NumbersEqualToLast(int limit, std::vector<int> elements) { int check = elements[limit], counter = 0; for (int i = limit; i >= 0; i--) { if (elements[i] == check) { counter++; } } return(counter); } int main() { int amount, number; std::cin >> amount; std::string input; getline(std::cin, input); std::stringstream iss(input); std::vector<int> numbers; while ( iss >> number ) { numbers.push_back( number ); } std::cout << NumbersEqualToLast(amount, numbers) << std::endl; } The problem is after reading the amount of integers (in this case 9) I get a Segmentation fault (core dumped) error. EDIT AFTER SOLUTION This is what worked for me using your suggestions. Thank you. I understand if it's not pretty or there are better more efficient ways but I'm just starting out. :) #include <iostream> #include <vector> int NumbersEqualToLast(int limit, std::vector<int> elements) { int check = elements[limit - 1], counter = 0; for (int i = limit - 2; i >= 0; i--) { if (elements[i] == check) { counter++; } } return(counter); } int main() { int quantity; std::cin >> quantity; int number; std::vector<int> numbers; for (int i = 0; i < quantity; i++) { std::cin>>number; numbers.push_back(number); } std::cout << NumbersEqualToLast(quantity, numbers) << std::endl; }
Just don't judge harshly, please. I suggest another way to solve this problem. #include <iostream> #include <vector> using namespace std; int special, count; void dfs(int current, int previous, vector<int>& visited, vector<int>& input) { if(visited[current]==1) { return; } visited[current]=1; if(current==(input.size()-1)) { special=input[current]; } for(int next=(current+1); next<input.size(); ++next) { if(next==previous) { continue; } dfs(next, current, visited, input); } if(special==input[current]) { ++count; } if(current==0) { --count; cout<<count; } return; } void solve() { int quantity; cin>>quantity; int number; vector<int> numbers; for(int i=0; i<quantity; ++i) { cin>>number; numbers.push_back(number); } vector<int> visited(quantity); dfs(0, -1, visited, numbers); return; } int main() { solve(); return 0; } Input: 9 1 7 3 2 4 7 5 8 7 Here is the result: 2
70,098,843
70,098,953
Adding a member to std::vector<std::vector<int>> class in C++
I have to modify a code so that I can add a member to 2D vectors. The code started with a typedef vector<vector<int>> Matrix which I replaced with a Matrix class. I tried to inherit from vector<vector<int>> using : class Matrix: public vector<vector<int>> { public: int myMember; }; This way I practically don't have to modify the source code much. However, if I try to run : Matrix mymatrix (4); It raises an error : modele.cpp:19:20: error: no matching function for call to 'Matrix::Matrix(int)' Matrix mymatrix (4); ^ In file included from modele.cpp:8:0: modele.h:6:7: note: candidate: Matrix::Matrix() class Matrix: public vector<vector<int>> { ^ modele.h:6:7: note: candidate expects 0 arguments, 1 provided
Constructors are not inherited by default, but can use them in your derived class for that you have to do something like this: #include <vector> #include <iostream> class Matrix : public std::vector<std::vector<int>>{ public: using vector::vector; int myMember; }; int main(){ Matrix data(1); std::vector row = {1,2,3,4,5}; data.push_back(row); for(auto i: data){ for(auto r : i){ std::cout << r << std::endl; } } } This way compiler will know all the constructors from the base class. And will call the appropriate constructor for your derived class.
70,099,368
70,109,565
std::chrono gdb pretty printer
I am mildly surprised that gdb doesn't come with pretty printers out of the box for the std::chrono duration types since they are part of the standard library. With gdb 10.2 (through most recent Clion IDE although that should not be Clion specific - it's plain gdb under the hood) I see the unhelpful : system_clock::m_time_counter = {std::chrono::nanoseconds} instead of e.g. system_clock::m_time_counter = 133ns That forces me to expand the field everytime and dig into the type to reveal the __r member that holds the std::chrono::duration<long, std::ratio>::rep value I am interested in. I am on ubuntu 20.04, using gdb 10.2 I am open to using any gdb pretty printers (python version welcome) - and want to make sure I am not missing any implementation out there so I don't reinvent the wheel.
I ended up adding a .gdbinit file in my home directory with a few lines of python which achieves the single-line value display I was after. python # way to tell .gdbinit we enter a python section import gdb class ChronoPrinter: def __init__(self, val): self.val = val def to_string(self): integral_value = self.val['__r'] return f"{integral_value}" p = gdb.printing.RegexpCollectionPrettyPrinter("sp") p.add_printer("chrono", "^std::chrono::duration<.*>$", ChronoPrinter) o = gdb.current_objfile() gdb.printing.register_pretty_printer(o, p) end # end of python section I then get the pretty view: system_clock::m_time_counter = {std::chrono::nanoseconds} 33 Note: The libstdc++ gdb printers from the repo mentioned there https://sourceware.org/gdb/wiki/STLSupport seem to be affecting only the dislayed type name (e.g. turn std::chrono::duration<long, std::ratio> into the more friendly std::chrono::nanoseconds). A useful command to list enabled printers in a gdb session is: info pretty-printers The output under libstdc++-v6 doesn't have anything related to chrono. > objfile /lib/x86_64-linux-gnu/libstdc++.so.6 pretty-printers: > libstdc++-v6 > __gnu_cxx::_Slist_iterator > __gnu_cxx::__8::_Slist_iterator > __gnu_cxx::__8::__normal_iterator > __gnu_cxx::__8::slist > __gnu_cxx::__normal_iterator ... /*many more but nothing chrono related */
70,099,903
70,100,358
c++ how to sum all rows from one specific column from a csv delimited
I have a question in C++ For example, i have a csv file delimited by ; with this data name;age;country maria;19;portugal joao;20;espanha carlos;18;portugal antonio;30;alemanha How can i get the sum of column 2 (age) -> =87 How can i get the country that shows more times (portugal) With this code i get a complete line, but I don't know how get the information above. I thought convert the data in a matrix (i,j) and access the values, but I don't know how. CODE: #include <iostream> #include <fstream> #include <string> #include <limits> using namespace std; std::fstream &GotoLine(std::fstream& file, unsigned int num){ file.seekg(std::ios::beg); for(int i=0; i < num - 1; ++i){ file.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); } return file; } int main(){ using namespace std; fstream file("teste.csv"); GotoLine(file, 2); string line2; file >> line2; cout << line2; cin.get(); return 0; }
You should use struct to hold information together in this case, as shown below. You can use the below given program as a reference(starting point) for your future purposes/programs. #include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> #include <map> #include <functional> #include<iterator> struct Person { std::string name, country; double age = 0; //parameterised constructor Person(std::string pname, std::string pcountry,double page): name(pname), country(pcountry), age(page) { } }; int main() { std::ifstream inputFile("input.txt"); std::string line,wordAge, tempName, tempCountry; double tempAge; //create a vector of Person objects std::vector<Person> myVec; if(inputFile) { //read the first line and discard it std::getline(inputFile, line); //read line by line while(std::getline(inputFile, tempName,';'),//read name std::getline(inputFile, wordAge,';'),//read age std::getline(inputFile, tempCountry,'\n'))//read country { std::istringstream ss(wordAge); if(ss >> tempAge)//read age { myVec.emplace_back(tempName, tempCountry,tempAge); } } } else { std::cout<<"Input file cannot be opened"<<std::endl; } //lets print out all the elemnts of the vector to confirm that we read the file correctly double sum = 0; std::map<std::string, int> myMap;//this will be used to keep track of the count corresponding to each country for(const Person &elem: myVec) { std::cout <<"Name: "<<elem.name<<" Age: "<<elem.age<<" Country: "<<elem.country<<std::endl; sum+=elem.age; myMap[elem.country]++; } std::cout<<"The sum of all ages is: "<<sum <<std::endl; std::cout<<"The country that occurs most number of times is: "<<(std::prev(myMap.end())->first)<<" which occurred :"<<(std::prev(myMap.end())->second)<<" times"<<std::endl; return 0; } The output of the above program can be seen here. The input file can also be found at the above mentioned link.
70,100,820
70,102,036
For print a pattern by using loop
*this is my output 1234 234 34 4 code //variable declaration #include<iostream> using namespace std; int main(){ int i,j,space,star,n; cin>>n; i=1; //for printing spaces while(i<=n){ space=i-1; while(space){ cout<<" "; space--; } // for counting variables j=1; star=n-i+1; // for printing numbers while(star){ int num=i+j-1; cout<<num; star--; j++; } cout<<"\n"; i++; } return 0; } Que- I want that as an output :- 1 2 3 4 2 3 4 3 4 4
Well, when printing spaces, you do this: cout<<" "; You can do this: cout<<" "; That is, print two spaces instead of one. That's half your answer. Later you do this: cout<<num; You can do this: cout << num << " "; That is -- print the digit plus a space. Done. However, if you do that, then you get an extra trailing space at the end of the line, So you can do this. std::string delim = ""; while (star) { int num=i+j-1; cout << delim << num; delim = " "; star--; j++; } This is your code with very very simple changes. I added a variable delim and changed the cout statement slight. The first time through the loop, delim is an empty string, so adding it to the cout statement does nothing. After that, delim is a single space, so now you print a space before all but the very first digit. On a side note -- please make more use of whitespace. Cramming everything together becomes very hard to read for those of us getting older, and it's a common way to obscure bugs. That's a style thing, but it WILL save you HOURS of time in the future.
70,100,958
70,101,000
Skip 2 Index In the body of For Loop VS While Loop ( Python VS C++)
In the first code below (Using for loop) When I want to skip 2 index by increasing the index within the body of for loop, it ignores i = i+2 and updates the index only with for i in range (len(c)) phrase, while in the c++ we could do this in th e body of for loop by for (int i = 0 ; i <sizeof(c) ;i++){i += 2;}. Is there anyway to implement this using a for loop (by correcting first code) or I have to use a while loop (second code)? First Code (For loop) def jumpingOnClouds(c): count_jumps = 0 for i in range (len(c)): if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0): i = i+2 count_jumps+=1#It doesnt let me to update i in the while loop elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0): count_jumps+=1 else: pass return(count_jumps) c = [0, 0, 0, 1, 0, 0] jumpingOnClouds(c) Second Code (While Loop) def jumpingOnClouds(c): count_jumps = 0 i = 0 while( i < len(c)): if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0): i = i+2 count_jumps+=1 elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0): count_jumps+=1 i = i+1 else: i = i+1 return(count_jumps) c = [0, 0, 0, 1, 0, 0] jumpingOnClouds(c)
You can use continue to skip. You'll just need a condition that will be True. def jumpingOnClouds(c): skipCondition = False count_jumps = 0 for i in range (len(c)): if skipCondition: skipCondition = False continue if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0): count_jumps+=1#It doesnt let me to update i in the while loop skipCondition = True continue elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0): count_jumps+=1 else: pass return(count_jumps) c = [0, 0, 0, 1, 0, 0] jumpingOnClouds(c) Putting continue will continue iterating, but before that, it will make the skipCondition = True. The next iteration, skipCondition will be True, so you will skip again, but setting skipCondition back to False
70,101,355
70,102,095
How to get all dictionary words from a list of letters?
I have an input string, like "fairy", and I need to get the English words that can be formed from it. Here's an example: 5: Fairy 4: Fray, Airy, Fair, Fiar 3: Fay, fry, arf, ary, far, etc. I have an std::unordered_set<std::string> of dictionary words so I can easily iterate over it. I've created permutations before as shown below: std::unordered_set<std::string> permutations; // Finds every permutation (non-duplicate arrangement of letters) std::sort(letters.begin(), letters.end()); do { // Check if the word is a valid dictionary word first permutations.insert(letters); } while (std::next_permutation(letters.begin(), letters.end())); That's perfect for length 5. I can check each letters to see if it matches and I end up with "fairy", which is the only 5 letter word that can be found from those letters. How could I find words of a smaller length? I'm guessing it has to do with permutations as well, but I wasn't sure how to implement it.
You can keep an auxiliary data structure and add a special symbol to mark an end-of-line: #include <algorithm> #include <string> #include <set> #include <list> #include <iostream> int main() { std::list<int> l = {-1, 0 ,1, 2, 3, 4}; std::string s = "fairy"; std::set<std::string> words; do { std::string temp = ""; for (auto e : l) if (e != -1) temp += s[e]; else break; words.insert(temp); } while(std::next_permutation(l.begin(), l.end())); } Here the special symbol is -1
70,101,356
70,101,410
How to use a char buffer array as the case in switch-case C++?
I have a snip of the following code which should read the first 4 objects in a .wav file in order to eventually parse the header of the file. I know I'm doing something wrong here because the buffer always passes "RIFF" without printing out Riff is found How should I use the Switch-case in order to find the correct array characters? #include <iostream> #include <string> using namespace std; int main() { cout << "Nom: "; string filename; cout << "First Input filename:" << endl; cin >> filename; #pragma warning (disable : 4996) FILE* InFile = fopen(filename.c_str(), "rb"); // Open wave file in read mode char Buffer[4]; while (InFile) { fread(Buffer, sizeof Buffer[0], 4, InFile); switch (Buffer[4]) { case 'R' +'I'+'F'+'F': cout << "Riff is found " << endl; case 'c' +'r'+ 'i'+ 'f' : cout << "CRiff is found " << endl; } } }
In contrast to languages such as C#, you cannot use strings in a switch expression. You will have to use if...else statements in conjunction with std::memcmp instead: if ( std::memcmp( Buffer, "RIFF", 4 ) == 0 ) std::cout << "Riff is found.\n"; else if ( std::memcmp( Buffer, "crif", 4 ) == 0 ) std::cout << "CRiff is found.\n"; Note that std::memcmp should only be used if you are sure that all character sequences are of the same length. Otherwise, it is safer to use std::strncmp. In your posted code, what is actually happening is the following: The expression 'R'+'I'+'F'+'F' will evaluate to the sum of the individual character codes of these letters. This is not what you want.
70,101,890
70,102,033
Meaning of "ill-formed declaration" in L(n)
A code snippet from cppreference.com is like this: struct M { }; struct L { L(M&); }; M n; void f() { M(m); // declaration, equivalent to M m; L(n); // ill-formed declaration L(l)(m); // still a declaration } L(n); is commented with "ill-formed declaration". But nearly all compilers issue message like this: no default constructor exists for class "L". That is to say, it's not considered to be ill-formed, right? Because if i throw a line L() = default; into L's body, it compiles successfully. Is the comment wrong or misleading or compilers are not strictly standard-conforming? Follow Up Seems that i made something wrong with ill-formed: ill-formed - the program has syntax errors or diagnosable semantic errors. A conforming C++ compiler is required to issue a diagnostic, > even if it defines a language extension that assigns meaning to such > code (such as with variable-length arrays). The text of the standard > uses shall, shall not, and ill-formed to indicate these requirements. In light of that, that line is semantically wrong. Thanks, for you guys' answers and comments.
I think that the example demonstrates that declarator may be enclosed in parentheses. So this declaration M(m); is equivalent to M m; that is there is declared an object m of the type M. However this record L(n); can be considered as an expression statement with calling the constructor L( M & ) with the argument n of the type M or as a declaration. The C++ Standard resolves such an ambiguity as a declaration instead of the expression statement. So in this record n is the name of the created object. But the class L does not have the default constructor. So the declaration is ill-formed because the structure L does not have the default constructor that is required for this declaration. From the C++ 14 Standard (6.8 Ambiguity resolution) 1 There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration. To make an expression statement instead of the declaration you can write for example ( L )( n ); This record L(l)(m); is a correct declaration. There is declared the object l of the type L using the constructor L( M & ).
70,102,205
70,103,381
Why wrapping call to function returning by value in hana::always circumvent requirements of ranges::views::join? Or maybe it doesn't?
This function, fed with any int, returns a std::vector<int> by value: auto make = [](int){ return std::vector<int>{1,2,3}; }; Therefore, such a thing can't work std::vector<int> v{1,2,3}; auto z = v | std::ranges::views::transform(make) | std::ranges::views::join; // fails to compile because, I understand (but correct me if I'm wrong), when the iterator wrapped in join advances, it triggers the generations of the vectors by means of make, but those temporary are already destroyed by the time the iterator in join is dereferenced. However, the following doesn't fail: std::vector<int> v{1,2,3}; auto z = v | std::ranges::views::transform(boost::hana::always(make(int{}))) | std::ranges::views::join; Why is that? What mechanism is being introduced by the use of always? I think the following is proof that both functions, make and always(make(int{})), return a temporary. Am I making a mistake? static_assert(!std::is_reference_v<decltype(make(int{}))>); static_assert(!std::is_reference_v<decltype(boost::hana::always(make(int{}))(int{}))>); Full demo.
There are two separate issues. join_view's restriction on joining ranges of prvalue ranges is a defect in C++20 that has been corrected by P2328R1. transform(make) | join should Just Work on a standard library implementing the defect resolution (such as libstdc++ trunk). hana::always returns different things depending on whether it is invoked as an lvalue or rvalue. It returns an lvalue reference when invoked as an lvalue and a prvalue when invoked as an rvalue. transform always invokes as lvalue, while your static_assert is checking the result of invoking as rvalue.
70,102,937
70,103,124
How should an input string be read into a shunting yard algorithm calculator?
I have implemented the basic structure of the shunting yard algorithm, but I'm not sure how to read in values that are either multidigit or functions. Here's what I have currently for reading in values: string input; getline(cin, input); input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end()); //passes into function here for (int i = 0; i < input.length(); ++i) { string s = input.substr(i, 1); //code continues } As you can see, this method can only parse one character at a time, so it is extremely flawed. I also have tried searching up reading in values or parsing them but haven't found a result that is relevant here. Full Code: https://pastebin.com/76jv8k9Y
In order to run shunting-yard, you're going to want to tokenize your string first. That is, turn 12+4into {'12','+','4'}. Then you can just use the tokens to run shunting yard. A naive infix lexing algorithm might like this: lex(string) { buffer = "" output = {} for character in string { if character is not whitespace { if character is operator { append buffer to output append character to output buffer = "" } else { append character to buffer } } append buffer to output return output } Real lexers are a lot more complicated and are a prime field of study in compiler design.
70,103,116
70,103,161
Get access to a variable in a class without copying it
I would like to get access to fields from a class without copying it. I have a class that stores two variables (simplified version here). In the get_cutting_types method I check where the user inputs true or false and pass the object back by reference. But here I have to use =, meaning the data is copied. Is there a direct way to pass a field without re-assignment? class joint { std::vector<char> m_letters; std::vector<char> f_letters; void get_cutting_types(bool flag, std::vector<char>& letters) { if (flag) { letters= m_letters; } else { letters= f_letters; } } }
There's a lot to unpack here, but: I don't think you're going to be able to avoid using an "=" sign somwhere along the way. And I don't see any reason that's a problem. If all you want is to return a boolean value: then maybe just add a new public method to your class, e.g. public: bool isMale() { return <<some test>>; } // Easy peasy! Q: Does this address your concern(s)? Q: Or do you need "something else"? If so, please clarify. Sorry maybe there was confusion in the code of variable naming. It is only a return values of char not a single boolean flag. OK, maybe you want something like this: public: const std::vector<char>& get_cutting_types(bool is_male) { return (is_male) ? m_letters : f_letters; }
70,103,300
70,103,325
Accessing non-const data members from constexpr member function
Both GCC and MSVC seem to allow defining constexpr accessor functions for non-const data members: #include <random> #include <iostream> class Foo { int val; public: Foo(int v) : val(v) {} constexpr int get_val() { return val; } // OK }; int main() { std::random_device rd; Foo foo((int)rd()); std::cout << foo.get_val(); // works } Is this nonstandard behavior from MSVC and GCC or does the standard actually allow this?
Of course this is allowed! constexpr don't mean const. You can even mutate values in a constexpr function: class Foo { int val; public: constexpr Foo(int v) : val(v) {} // OK constexpr int get_val() { return val; } // OK constexpr void set_val(int v) { val = v; } // OK }; With this you can write constexpr functions that look like normal function, it's just that they may be executed at compile time in the compiler runtime. constexpr int test() { Foo f{}; f.set_val(2); return f.get_val(); } static_assert(test() == 2); // Checks at compile time
70,103,393
70,103,474
Is there a portable way in standard C++ to retrieve hostname?
I'm working on a C++ program that needs to use the hostname of the computer it is running on. My current method of retrieving this is by mangling a C API like this: char *host = new char[1024]; gethostname(host,1024); auto hostname = std::string(host); delete host; Is there a portable modern C++ method for doing this, without including a large external library (e.g., boost)?
No, there is no standard C++ support for this. You'll either have to make your own function, or get a library that has this functionality.
70,104,117
70,123,774
How to set expectation on a mocked method which is called inside another mocked method C++
I am a beginner with google testing framework and have looked up for the solution to this question on SO, but could not find any solutions with respect to C++. Anyway here is what i am trying to do. I have a state machine(service) which is called inside a client code. //IStateMachine.h class IStateMachine { public: bool Run(const std::string& action) = 0; bool IsTxnValid(const std::string& action)= 0; } //StateMachine.h class StateMachine : public IStateMachine { bool Run(const std::string& action) override; bool IsTxnValid(const std::string& action) override; } //StateMachine.cpp bool StateMachine::IsTxnValid(const std::string& action) { //Checks whether the given action is valid for the given state. } bool StateMachine::Run(const std::string& action) { if(IsTxnValid(action)) // #E { //Do processing return true; } return false; } //Client.h contains a class Client which has function called RunService. Client { public: void RunService(); std::unique_ptr<IStateMachine> service_; // Initialised to a non null value in either ctr or // factory. } //Client.cpp bool Client::RunService(std::string&action) { if(!service_->Run(action)) //Run in turn calls IsTxnValid(). { return false; } return true; } Now i am writing a test case to test the functioning of RunService. I am expecting that if Client::IsTxnValid(param) returns false, then so should RunService. I have successfully set up the testing recipe and could get the basic tests running. Here is the relevant test i have written. On running this test the i get the error, that IsTransitionValid is never called. TEST_F(ClientTest, RunService) { EXPECT_CALL(*p_service, Run("some_action")); // #A // EXPECT_CALL(*p_service, Run(testing::_)).WillOnce(::testing::Return(true)); //#B EXPECT_CALL(*p_service,IsTransitionValid(testing::_)).WillOnce(::testing::Return(false)); //#C : This never gets called. EXPECT_EQ(false, x_client->RunService()); } How do i correctly call IsTransitionValid ?
You don't need to set this expectation. I'd go even further: you should not even depend on the implementation of Run in IStateMachine: you should only care about what input it is provided with (parameters, checked with matchers) and what output it can return (so basically only the contract between these two classes) and that's the beauty of it! It is an implementation detail of StateMachine class (the real implementation) what is done when Run is called. The only thing you need to check in your test is to act upon the result of Run. Using triple A rule (arrange, act, assert): you arrange the test case conditions (using EXPECT_CALLs), then you act (calling RunService) and then you assert (checking the result of RunService). The technical details: When you create a mock by inheriting from class Foo: class Foo { public: virtual ~Foo() = default; virtual void bar() = 0; } By defining: class FooMock : public Foo { MOCK_METHOD0( bar, void()); } gmock will add bar (the method to override) and gmock_bar (internal detail of gmock) methods to FooMock class. bar has empty implementation in this case. FooImpl and FooMock share the interface, but have different implementations - hence no call to IsTxnValid is made in Run: the mock class just doesn't know (nor care) how Run is implemented in StateMachine. Remember: in your testcase you interact with StateMachineMock and you only care about the interaction with its public interface, the contract between these two classes and how they cooperate together. That being said, you of course need to utest the StateMachine class. It may depend on yet another interfaces in its implementations: that will be tested with different set of mocks. But Client should not know about this.
70,104,318
70,104,345
c++ 2 overloads have similar conversions depending on whether the operator is a member function or a global one
Consider a simple vector class realization: #include <algorithm> class Vector { public: Vector(int _elementsCount) : elementsCount(_elementsCount) , elements(new float[_elementsCount]) {} ~Vector() { delete[] elements; } Vector(const Vector& rhs) { elementsCount = rhs.size(); elements = new float[elementsCount]; for (int i = 0; i < elementsCount; ++i) (*this)[i] = rhs[i]; } float& operator [](int i) { return elements[i]; } float operator [](int i) const { return const_cast<Vector&>(*this)[i]; } int size() const { return elementsCount; } /*// Dot product float operator *(const Vector& v) { float res = 0; for (int i = 0; i < size(); ++i) res += (*this)[i] * v[i]; return res; }*/ private: int elementsCount; float* elements; }; // Multiplication by a scalar Vector operator *(const Vector& v, float k) { Vector res(v.size()); for (int i = 0; i < v.size(); ++i) res[i] = v[i] * k; return res; } // Dot product float operator *(const Vector& v1, const Vector& v2) { float res = 0; for (int i = 0; i < std::min(v1.size(), v2.size()); ++i) res += v1[i] * v2[i]; return res; } void main() { Vector v(2); v * 3; // ambiguous } This code compiles. But if we uncomment * operator realization in the class and comment its global realization (dot product function), then there will be an error "'Vector::operator *': 2 overloads have similar conversions", because there is an ambiguity: whether to call the multiplication by a scalar or to interpret 3 as an argument to a parametrized constructor and to call the dot product. This makes sense. But I don't get what's the difference of declaring the * operator as a member function or as a global function. I thought they should be the same in the example like above, but it's not the case. Added. The thing I most interested in is not how to avoid the ambiguity, but why there is an ambiguity in one case (when * is declared as a member) and there is no one in the other (when * is declared as a global function).
You need to make your constructor explicit: explicit Vector(int _elementsCount) { ... } The reason for the ambiguity is that the compiler can't decide whether it should implicitly convert a int value to a Vector and invoke Vector::operator*, or implicitly convert a int value to a float and use operator*(const Vector&, float). By using explicit, such conversions are forbidden, and you must use Vector(3) if you want "3" to be a Vector. As a side-note, you should make the operator const, since it does not modify the object. Making it const will also allow it to be used with a const Vector: float operator *(const Vector& v) const { ... } Beware that will still conflict with your other overload: float operator *(const Vector& v1, const Vector& v2) There is no reason to have both. Choose either the member function or the global function and remove the other.
70,104,717
70,104,722
Why is move-constructor not called?
I have the following piece of code: #include <iostream> struct T { int a; T() = default; T(T& other) { std::cout << "copy &\n"; } T(T&& other) { std::cout << "move &&\n"; } }; void foo(T&& x) { T y(x); // why is copy ctor called?????? } int main() { T x; foo(std::move(x)); return 0; } I don't understand why copy constructor is preferred over move constructor even though foo() accepts rvalue-reference.
x is an lvalue itself, even its type is rvalue-reference. Value category and type are two independent properties. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression; You need to use std::move to convert it to rvalue, just same as using std::move on x in main(). void foo(T&& x) { T y(std::move(x)); }
70,104,749
70,104,785
Can't kill all child processes using SIGTERM
My program has the following parent child layout: int main() { std::vector<pid_t> kids; pid_t forkid = fork(); if (forkid == 0) { //child process pid_t fork2 = fork() if (fork2 == 0) { // child process }else { //parent kids.push_back(fork2); } }else { // code here kids.push_back(forkid); } // Not killing the fork2 process - only the first process(forkid) is terminated for (pid_t k : kids) { int status; kill(k, SIGTERM); waitpid(k, &status, 0); } } I am not able to kill the child process (fork2) - the first process gets terminated. The kids vector seems to only contain the process id of the first process. Never gets the pid of the child process. What am I doing wrong here. Any help will be appreciated. Thanks.
std::vector<pid_t> kids; pid_t forkid = fork(); fork() creates a complete duplicate image of the parent process as its child process. Emphasis on: duplicate. This means that, for example, the child process has its very own kids vector, that has nothing to do, whatsoever, with the parent process's original kids vector. Since this is the very first thing that happens in main, this is really no different than you running this executable twice, individually as two distinct and separate processes, instead of forking off a process. You can't expect the kids vector in one of the two processes to have any effect on the kids vector in the other one. The first child process creates a 2nd child process, and also adds the 2nd child process's pid into its own kids vector. But that's just the first child process's kids vector. The only process id that the original parent process's kids vector ends up having is the first child's process it, so that's all you get to SIGTERM. Your options are: Restructure your logic so that both child process get created by the parent process, so it, alone, puts their process ids into its kids vector. Instead of using fork use multiple execution threads, and the same process. However, neither std::vector, nor any other C++ library container is thread safe. A massive pile of code will need to be written to properly synchronize the threads, in order for things to work themselves out correctly (not to mention that the analogue for the SIGTERM, with respect to multiple execution threads, needs to be invented in some way). The simplest alternative is the first one.
70,104,875
70,130,364
How did a Renderer pass to the rest of the classes?
I have a Game class that through its constructor initializes the window and the SDL renderer. I understand from what I read so far (not much) that there should only be one renderer for each window. Then I have a Player class where through the constructor I want to load a texture with an image, for which I need the renderer, therefore, I put the renderer as the constructor parameter and in this way I am forced to pass from the constructor from Game the renderer to the Player constructor (since it instantiated the Player class in The Game class). The fact is that the renderer is passed before being created, and I don't know if there is another way to invoke the constructor of the Player from Game, since it forces me to put it that way. I leave the code for you to see: Game class: #pragma once #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "player.hpp" //#include "helpers.hpp" using namespace std; #define WINDOW_WIDHT 640 #define WINDOW_HEIGTH 480 class Game { public: Game(); ~Game(); void loop(); void update() {} void input(); void render(); void draw() {} private: SDL_Window *window; SDL_Renderer *renderer = nullptr; SDL_Event event; SDL_Texture *gTexture; bool running; Player player; }; Game::Game() : player(renderer) { SDL_Init(0); SDL_CreateWindowAndRenderer(WINDOW_WIDHT, WINDOW_HEIGTH, 0, &window, &renderer); SDL_SetWindowTitle(window, "Intento..."); //inicializa la carga de pngs int imgFlags = IMG_INIT_PNG; if (!IMG_Init(imgFlags) & imgFlags) { cout << "No se puede inicializar SDL_Img" << endl; } running = true; loop(); } Game::~Game() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } void Game::loop() { while (running) { input(); render(); update(); } } void Game::render() { SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); SDL_Rect rect; rect.x = rect.y = 0; rect.w = WINDOW_WIDHT; rect.h = WINDOW_HEIGTH; SDL_RenderFillRect(renderer, &rect); SDL_RenderPresent(renderer); } void Game::input() { while (SDL_PollEvent(&event) > 0) { switch (event.type) { case SDL_QUIT: running = false; break; } } } Clase Player: #pragma once #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> //#include "helpers.hpp" using namespace std; class Player { public: Player(SDL_Renderer *renderer); ~Player() = default; const SDL_Rect getDest() { return dest; } const SDL_Rect getSrc() { return src; } void setDest(int x, int y, int w, int h); void setSrc(int x, int y, int w, int h); SDL_Texture *loadTexture(std::string path, SDL_Renderer *renderer); private: SDL_Rect dest; SDL_Rect src; }; Player::Player(SDL_Renderer *renderer){ loadTexture("mario.png", renderer); /* setSrc(48, 48, 48, 48); setDest(100, 100, 48, 48); SDL_Rect playerRectSrc = getSrc(); SDL_Rect playerRectDest = getDest(); */ } void Player::setDest(int x, int y, int w, int h){ dest.x = x; dest.y = y; dest.w = w; dest.h = h; } void Player::setSrc(int x, int y, int w, int h){ src.x = x; src.y = y; src.w = w; src.h = h; } SDL_Texture* Player::loadTexture(std::string path, SDL_Renderer *renderer) { SDL_Texture *newTexture = NULL; SDL_Surface *loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == NULL) { cout << "No se pudo cargar la imagen" << endl; } else { newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface); if (newTexture == NULL) { cout << "No se pudo generar la textura para player" << endl; } SDL_FreeSurface(loadedSurface); } return newTexture; } The question is how to call the Player constructor after the renderer has been created? The only thing I can think of is not to create the texture through the constructor, but through a function, but it wouldn't be the right thing to do, right? that's what the constructor is for
The only thing I can think of is not to create the texture through the constructor, but through a function, but it wouldn't be the right thing to do, right? that's what the constructor is for Right. However, SDL is a C library so it doesn't use C++ RAII, which is responsible for construction/destruction. First, we call constructors in the member initializer list (: foo{}, bar{foo}), which provides us with fully constructed member objects. Then, we do whatever we want in the constructor body ({ use(foo); }). However, in your case the constructor body ({ SDL_CreateWindowAndRenderer(...); } ) is needed before member initialization (: player{renderer}). The question is how to call the Player constructor after the renderer has been created? Construct all that SDL_ stuff before constructing the Player: class RenderWindow { SDL_Window* window; SDL_Renderer* renderer; public: RenderWindow() { SDL_Init(0); SDL_CreateWindowAndRenderer(WINDOW_WIDHT, WINDOW_HEIGTH, 0, &window, &renderer); SDL_SetWindowTitle(window, "Intento..."); } // an easy double-free protection, you can use anything else RenderWindow(RenderWindow&&) = delete; ~RenderWindow() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } // lvalue-only to forbid dangling like RenderWindow{}.raw_renderer() auto raw_renderer() & { return renderer; } }; Now, your Player and Game can be implemented in a natural RAII construct-then-use way: class Player { public: Player(SDL_Renderer*); // TODO implement }; class Game { // note the declaration order: construction goes from top to bottom RenderWindow render_window; Player player; public: // SDL_* happens in render_window{}, // so player{render_window.raw_renderer()} gets an initialized SDL_Renderer Game(): /*render_window{},*/ player{render_window.raw_renderer()} {} };
70,104,984
70,105,036
C++ Keeping track of start iterator while adding items
I am trying to do a double loop across a std::vector to explore all combinations of items in the vector. If the result is good, I add it to the vector for another pass. This is being used for an association rule problem but I made a smaller demonstration for this question. It seems as though when I push_back it will sometimes change the vector such that the original iterator no longer works. For example: std::vector<int> nums{1,2,3,4,5}; auto nextStart = nums.begin(); while (nextStart != nums.end()){ auto currentStart = nextStart; auto currentEnd = nums.end(); nextStart = currentEnd; for (auto a = currentStart; a!= currentEnd-1; a++){ for (auto b = currentStart+1; b != currentEnd; b++){ auto sum = (*a) + (*b); if (sum < 10) nums.push_back(sum); } } } On some iterations, currentStart points to a location that is outside the array and provides garbage data. What is causing this and what is the best way to avoid this situation? I know that modifying something you iterate over is an invitation for trouble...
nums.push_back(sum); push_back invalidates all existing iterators to the vector if push_back ends up reallocating the vector. That's just how the vector works. Initially some additional space gets reserved for the vector's growth. Vector's internal buffer that holds its contents has some extra room to spare, but when it is full the next call to push_back allocates a bigger buffer to the vector's contents, moves the contents of the existing buffer, then deletes the existing buffer. The shown code creates and uses iterators for the vector, but any call to push_back will invalidate the whole lot, and the next invalidated vector dereference results in undefined behavior. You have two basic options: Replace the vector with some other container that does not invalidate its existing iterators, when additional values get added to the iterator Reimplement the entire logic using vector indexes instead of iterators.
70,105,002
70,105,136
Using a concept in another concept's 'requires' clause
I have a fairly simple example that I'm struggling with. I'd like to use an already-defined concept in another concept's requires clause - something like this, except actually working: template<typename T> concept Any = true; template<typename T> concept UsesAnyA = requires(T t, Any auto a) { t(a); }; I've also tried defining UsesAny like this, to no further avail: template<typename T, Any A> concept UsesAnyB = requires(T t, A a) { t(a); }; From a conceptual (...sorry) angle it feels like this should be possible. Can anyone suggest something?
Probably need to do something like this: template <typename T> concept Any = true; template <typename T, typename A> concept UsesAny = Any<A> and requires (T t, A a) { t(a); }; A concept needs each of the complete types involved in order to test its constraint, but at the point you evaluate it, you should already have the complete types available to test with. I realize checking Any<A> in this example is redundant, but I'm assuming your actual concept is not trivial, and this demonstrates how to use it to constrain your dependent concept. Here are the three different ways you can constrain a template with UsesAny: template <typename A> auto f(A a, UsesAny<A> auto t) { t(a); } template <typename A, UsesAny<A> T> auto f(A a, T t) { t(a); } template <typename A, typename T> requires UsesAny<T, A> auto f(A a, T t) { t(a); } each of these forms are equivalent.
70,105,697
70,105,771
Why does automatic type deduction not work for constexpr member referencing?
In the example code, compiled in C++17: template <typename T = int> struct A { static constexpr double b = 0.5; }; int main() { A a; // compiles double c = A<>::b; // compiles double d = A::b; // fails to compile // ... return 0; } Live example A::b fails to compile because: main.cpp:13:16: error: 'template<class T> struct A' used without template arguments 13 | double d = A::b; // fails to compile I thought in C++17 automatic template type deduction would take care of this since I have the default template argument. What am I missing?
Each instantiated class instance has own A<T>::b member. #include <iostream> template <typename T = int> struct A { static constexpr double b = 0.5; }; int main() { std::cout << &A<int>::b << "\n"; std::cout << &A<char>::b << "\n"; return 0; } Compiled with clang++13 with the option -std=c++17. Output: 0x402008 0x402018 Think about if A::b could be compiled, which address would be selected by the compiler. The live example https://godbolt.org/z/GqhjMvoz6 As for failed to compile double d = A::b; with the default template parameter, this is the rule, templates must be instantiated used with using angle brackets <, >.
70,105,768
70,105,787
what is the difference between while and do-while loop in c?
I am new to programming language. Anyone please help me with this. It helps to improve my skills. what is the difference between while and do-while loop in c Thank You,
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. do-while loop: do while loop is similar to while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of Exit Control Loop. for more info click here.
70,105,905
71,513,590
How do I remove a special constructor from overload resolution?
I'm creating an implementation of C++17's std::optional<class T> in C++14. The specification states that the move constructor should be excluded from overload resolution if T is not move-constructible, and made trivial if T is trivially move-constructible. I'm stuck on getting the former. Here's a code sample of what I have so far: template<class T, bool = is_trivially_move_constructible_v<T>> class optional_move_construct : public optional_copy_construct<T> { public: optional_move_construct(optional_move_construct&& rhs) : optional_base<T>() { if (rhs.m_full) { _impl_construct(std::move(rhs.m_value)); } } }; optional_copy_construct<T> is part of the inheritance chain I'm using, so I won't worry about it. There are two ways I can "remove" the move constructor, neither of which works for this scenario. Option 1: Delete the move constructor. This won't work because deleted functions are included in overload resolution. Option 2: Use SFINAE to exclude the move constructor from overload resolution. This won't work either, because SFINAE requires a template function to work, and that would be lower-priority than the default move constructor. How would I go about doing this?
A move constructor has one T&& argument, and possibly additional arguments provided those have default values. That means you can add std::enable_if_t<Condition, int> = 0 as an additional argument to your move constructor. The compiler won't create a one-argument optional::optional(T&&) move constructor when you have that two-argument move constructor.
70,105,969
70,105,992
C++ Loop through first K elements of unordered_map
I have an unordered_map that stores counts of integers. I want to loop through the map, but instead of fetching all the entries, I only wish to get the first K.It is guaranteed that map has more than K entries. I'm running into issues when I do the following: unordered_map<int, int> u_map; // Logic to populate the map for(auto it=u_map.begin(); it!=u_map.begin()+2; it++) cout<<it->first<<" "<<it->second<<endl; The expression u_map.begin()+2 is causing the issue. So is it possible to get only the first K entries of a map using for_each loop in C++?
I only wish to get the first K Note from std::unordered_map documentation an unordered_map object makes no guarantees on which specific element is considered its first element. This essentially means that there is no guarantee that you will iterate over the elements in the inserted order. For iterating over the elements of the map you can use: int count = 0; for (auto& it: u_map) { /* some code here like you can keep a count variable that will check if it reaches the number K and then break the loop. But remember that it is **not** guaranteed that the elements you will get will be in inserted order.*/ if(count < K) { cout<<it.first<<" "<<it.second<<endl; } else { break; } ++count; } Working example #include <iostream> #include <unordered_map> using namespace std; int main() { std::unordered_map<std::string, std::string> u_map = { {"RED","#FF0000"}, {"GREEN","#00FF00"}, {"BLUE","#0000FF"},{"PURPLE","#0F00FF"},{"WHITE","#0000RF"},{"ORANGE","#F000FF"} }; int K = 3; int count = 0; for (auto& it: u_map) { if(count < K) { cout<<it.first<<" "<<it.second<<endl; } else { break; } ++count; } return 0; }
70,106,194
70,135,562
Combine multiple animations for PathView delegate
Qt 6.2.0, Ubuntu 20.04. Here the code of my PathView: PathView { id: view property int item_gap: 60 anchors.fill: parent pathItemCount: 3 preferredHighlightBegin: 0.5 preferredHighlightEnd: 0.5 highlightRangeMode: PathView.StrictlyEnforceRange highlightMoveDuration: 1000 snapMode: PathView.SnapToItem rotation: -90 model: modelContent delegate: DelegateContent { } path: Path { startX: view.width + item_gap; startY: view.height / 2 PathAttribute { name: "iconScale"; value: 0.7 } PathAttribute { name: "iconOpacity"; value: 0.1 } PathAttribute { name: "iconOrder"; value: 0 } PathLine {x: view.width / 2; y: view.height / 2; } PathAttribute { name: "iconScale"; value: 1 } PathAttribute { name: "iconOpacity"; value: 1 } PathAttribute { name: "iconOrder"; value: 9 } PathLine {x: -item_gap; y: view.height / 2; } } } and here its delegate: Item { id: root property int highlightMoveDuration: 1000 property int image_width: 864 * 0.8 required property int index required property string label required property string thumbnail width: image_width; height: width * 1.7778 scale: PathView.iconScale opacity: PathView.iconOpacity z: PathView.iconOrder Image { id: img width: parent.width height: parent.height cache: true asynchronous: true source: "file://" + thumbnail sourceSize: Qt.size(parent.width, parent.height) visible: false } // other non-relevant stuff } } When I receive a signal from C++ I want to animate the current item in the following way: fade it and all the other items to transparent in the meantime (i.e. at the same time the previous animation runs) the current item (only) has to move up along Y axis call a C++ function reposition the item at the original position (it's still transparent) fade it and all the other items back to solid I tried something like this: SequentialAnimation { id: selectedContent running: false ParallelAnimation { PropertyAnimation { target: view; properties: "opacity"; duration: 500; to: 0.0} PropertyAnimation { target: view.delegate; properties: "y"; duration: 500; to: 0.0} } ScriptAction { script: ccp_code.selectedContent(view.currentIndex) } ParallelAnimation { PropertyAnimation { target: view; properties: "opacity"; duration: 500; to: 1.0} PropertyAnimation { target: view.delegate; properties: "y"; duration: 0; to: view.height / 2} } } but the y properties of the delegate is not found: QML PropertyAnimation: Cannot animate non-existent property "y" Just to check the behavior I set target: view, but still there is no movements on the y axis. Would you please help me to understand how to achieve such an animation?
The problem is that view.delegate is a Component, which is like a class definition, not a class instance. Your PathView may create many instances of that delegate. So you can't use view.delegate as a target for an animation because it needs to know which instance you're referring to. Since it's the current item you're interested in, you can use the currentItem property to get the correct instance. PropertyAnimation { target: view.currentItem; properties: "y"; duration: 500; to: 0.0}
70,106,777
70,107,046
C++ compilation vs translation unit
I am preparing a short presentation on templates for work and am using isocpp.org as a starting point for the content. However, I have come across an interesting paragraph: A note to the experts: I have obviously made several simplifications above. This was intentional so please don’t complain too loudly. If you know the difference between a .cpp file and a compilation unit, the difference between a class template and a template class, and the fact that templates really aren’t just glorified macros, then don’t complain: this particular question/answer wasn’t aimed at you to begin with. I simplified things so newbies would β€œget it,” even if doing so offends some experts. There are a few things that confuse me, one of which is .cpp file vs compilation unit. I have read that a single .cpp file is called a "translation unit". But what exactly is a compilation unit? I found this answer that says translation and compilation units are the same thing, and basically just fancy names for a single .cpp file, but isocpp seems to think otherwise, and google only gives explanations for translation units even if I search "compilation unit". Wikipedia seems to mention the "Single Compilation Unit" model, but gives no insight on what actually is a compilation unit. So what is a compilation unit and how is it different from a translation unit (and is a translation unit 100% the same thing as a .cpp file)?
First, translation and compilation units are the same thing. The word/phrase Translation unit is used more often than compilation unit. Which basically means your source file including all of its header files. Second we(and by we i mean good C++ books) use the term function template or class template rather than using the terms "template function" and "template class". From documentation The text of the program is kept in units called source files in this International Standard. A source file together with all the headers (17.6.1.2) and source files included (16.2) via the preprocessing directive #include, less any source lines skipped by any of the conditional inclusion (16.1) preprocessing directives, is called a translation unit Also note in the same document they have used the term compilation unit. And if you read carefully the use of the word compilation unit in that document, you will see that they mean the same thing as translation unit. Now to clear everything up(from above), a compilation and a translation unit are the same thing. a cpp file alone(without its headers) does not constitute a translation unit(or compilation unit since they mean the same thing). On the other hand a cpp file with all of its headers included does constitute a translation/compilation unit.
70,107,117
70,143,198
I need assistance with pinpointing a std run time error
So the question above pretty much explains my problem, I have a program that prints the code size of my fragment shader and vertex shader, it is part of my Game engine project I have been working on for the past few days as a learning experience to get more knowledge of low-level c++ programming, but the problem is when I list where both shaders are placed in the project, my program proceeds to crash with a memory leak, the answer I need is exactly why this is happening PipeLine.h: #include <iostream> #include <vector> namespace G_piplne { class EdtrPipeLine { public: //grabs the file path to the frag file of the glsl shader file EdtrPipeLine(const std::string& vertFilePath, const std::string& fragFilePath); private: //gets the file path of both the frag file and vert file static std::vector<char> readFile(const std::string& filepath); //grabs the file path to the vert file of the glsl shader file void createGraphicsPipeLine(const std::string& vertFilePath, const std::string& fragFilePath); }; } PipeLine.cpp used for initiating the functions in the PipeLine header file #include "shaders_h/PipeLine.h" #include <fstream> #include <stdexcept> namespace G_piplne { EdtrPipeLine::EdtrPipeLine(const std::string& vertFilePath, const std::string& fragFilePath) { createGraphicsPipeLine(vertFilePath, fragFilePath); } std::vector<char> EdtrPipeLine::readFile(const std::string& filepath) { std::ifstream file(filepath, std::ios::ate | std::ios::binary); if (!file.is_open()) { throw std::runtime_error("failed to open file: " + filepath); } size_t filesize = static_cast<size_t>(file.tellg()); std::vector<char> buffer(filesize); file.seekg(0); file.read(buffer.data(), filesize); file.close(); return buffer; } void EdtrPipeLine::createGraphicsPipeLine(const std::string& vertFilePath, const std::string& fragFilePath) { //Reads Frag and Vert Code Size auto vertCode = readFile(vertFilePath); auto fragCode = readFile(fragFilePath); //Prints Frag and Vert Code Size std::cout << "Vertex Shader Code Size: " << vertCode.size() << "\n"; std::cout << "Frag Shader Code Size: " << fragCode.size() << "\n"; } } and finally, the EditorConfigWindow header file which uses the function to display my vert and frag code size #pragma once #include "EditorWindow.h" #include "../shaders_h/PipeLine.h" namespace G_editor { class EditorWindowConfig { public: //Init Varibles for the size of the Editor Window static constexpr int WIDTH = 800; static constexpr int HEIGHT = 600; void run(); private: //init Window with name GPRPG EditorWindow editorWindow{ WIDTH, HEIGHT, "GPRPG" }; //Display vert and frag code size G_piplne::EdtrPipeLine edtrPipeLine{"../../Shaders/simpleShader.vert.spv ", "../../Shaders/simpleShader.frag.spv"}; }; } All shader files are in the right place and listed correctly, I double-checked the names and they are correct as well, the error is as listed below Unhandled exception at 0x00007FF8F0154F69 in GPRPG.exe: Microsoft C++ exception: std::runtime_error at memory location 0x00000064240FEEA8. this error is hit at the breakpoint right when the createGraphicsPipeLine function is called from the EditorWindowConfig Header file, I've tried moving the shader files around in the project but it leads to the same problem, thank you in advance for any assistance given that may point me in the right direction to solve this problem
In researching, I found that adding the absolute path to my shader file actually outputs the size as expected, the program didn't like the short path I was inputting for some reason
70,107,183
70,107,238
Virtual list (Problems with parameter/pointer)
I am trying to convert my CListCtrl into a virtual list, but i dont know which parameter i have to use // --- Virtual List --- void CSpielebibliothekGUIDlg::OnGetdispinfoList(NMHDR* pNMHDR, LRESULT* pResult) // --- nullptr muss weg --- { LPNMITEMACTIVATE pNMIA = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; LV_ITEM* pItem = &(pDispInfo)->item; int itemid = pItem->iItem; if (pItem->mask & LVIF_TEXT) { CString text; // --- Welche Spalte --- if (pItem->iSubItem == 0) { // --- Name --- text = Spiele[itemid].m_Name; } if (pItem->iSubItem == 1) { //Text is slogan text = Spiele[itemid].m_Plattform; } if (pItem->iSubItem == 2) { text = Spiele[itemid].m_Genre; } if (pItem->iSubItem == 3) { CString Release; Release.Format(_T("%d"), Spiele[itemid].m_Erscheinungsjahr); text = Release; } if (pItem->iSubItem == 4) { CString Preis; Preis.Format(_T("%g"), Spiele[itemid].m_Preis); text = Preis; } if (pItem->iSubItem == 5) { CString EAN; EAN.Format(_T("%d"), Spiele[itemid].m_EAN); text = EAN; } if (pItem->iSubItem == 6) { text = Spiele[itemid].Verwandschaft; } lstrcpyn(pItem->pszText, text, pItem->cchTextMax); } *pResult = 0; } this is my function call OnGetdispinfoList(nullptr, nullptr); of course the nullptr are not right, iam glad for any help.
You don't need to call message handlers, they will be called by system after you: Set proper window styles (LVS_OWNERDATA) Set item count Add your OnGetdispinfoList to the message map
70,107,218
70,107,290
QWebEngineView will not load a local file, but will load perfectly a remote webpage
An MWE demoing the problem is this: #include <QMainWindow> #include <QApplication> #include <QWidget> #include <QWebEngineView> #include <QGridLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); QMainWindow w; auto w1 = new QWidget(); w1->setLayout(new GridLayout()); auto view = new QWebEngineView(); view->load(QUrl("file://C:\\Users\\FruitfulApproach\\Desktop\\AbstractSpacecraft\\MathEnglishApp\\KaTeX_template.html")); view->show(); w1->layout()->addWidget(view); w.setCentralWidget(w1); w.show(); return a.exec(); } KaTeX_template.html: <!DOCTYPE html> <html> <head> <title>MathJax TeX Test Page</title> <script type="text/x-mathjax-config"> MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}}); </script> <script type="text/javascript" async src="https://example.com/mathjax/MathJax.js?config=TeX-AMS_CHTML"> </script> </head> <body> When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$ </body> </html> You have to type in the correct file path in the first code listing. Anyway, it's not the template, because I put some plain text inside of the template and the same thing happens. What I expected was for QWebEngineView to be able to load a local file. I've tried playing around with the filepath string using forward instead of back-slashes, each change from what it is produce a "File not found" in the web view display. What happens currently is that the QWebEngineView is just displaying blank white. When you right-click on the view you can try reload or view source and nothing happens. I've tried loading an online webpage and that works.
If you want to create a QUrl using a file path then use QUrl::fromLocalFile(): view->load(QUrl::fromLocalFile("C:\\Users\\FruitfulApproach\\Desktop\\AbstractSpacecraft\\MathEnglishApp\\KaTeX_template.html"));
70,107,366
70,107,425
atcoder educational dp problem a runtime error problem
I am getting a runtime error in some test cases when I try to submit my code. Problem Link: https://atcoder.jp/contests/dp/tasks/dp_a My code: #include<bits/stdc++.h> using namespace std; #define int long long int minCost(int n, vector<int> h, vector<int> dp) { if (dp[n] != -1) { return dp[n]; } if (n == 1) { return dp[n] = 0; } if (n == 2) { return dp[n] = abs(h[1] - h[2]); } int oneStep = minCost(n - 1, h, dp) + abs(h[n] - h[n - 1]); int twoStep = minCost(n - 2, h, dp) + abs(h[n] - h[n - 2]); if (oneStep < twoStep) { return dp[n] = oneStep; } return dp[n] = twoStep; } int32_t main() { int n; cin >> n; vector<int> h(n + 1); for (int i = 1; i <= n; i++) { cin >> h[i]; } vector<int> dp(n + 1, -1); cout << minCost(n, h, dp); return 0; } i cannot figure out why it is giving runtime error. it works perfectly fine for sample tests.
I'm not sure this is the only problem, in minCost() but you're passing dp by value, not reference. That means the compiler will make a copy of dp, not the actual dp. Change your code to: int minCost(int n, vector<int> h, vector<int>& dp)
70,107,582
70,107,759
cmake add_custom_command pre_build
I am writing cmake example for the first time. Here is a part of CMakeFiles.txt: add_custom_command( OUTPUT ${CODEGEN_SRC} PRE_BUILD COMMAND ${CODEGEN_CMD} ${SERVICE_XML} --generate-cpp- code=/home/hello/include/gen/testGenCode COMMENT "Generate gdbus code" ) add_custom_target(${CODEGEN_TARGET} DEPENDS ${CODEGEN_SRC} ) Generate code using gdbus-codegen-glibmm in command syntax using add_custom_command. However, contrary to my expectations, when I actually do cmake and make, it looks like this: cmake .. CMake Error at Server/CMakeLists.txt:1 (ADD_EXECUTABLE): Cannot find source file: #### generate File #### CMake Error at Client/CMakeLists.txt:36 (ADD_EXECUTABLE): Cannot find source file: #### generate File #### Then, if you proceed with make, the contents of COMMANT in add_custom_command are output, and codes are actually generated. After checking the generated code, proceed with cmake .. and make again to build normally. Server/CMakeLists.txt, Client/CMakeLists.txt I set the dependency of ${CODEGEN_TARGET} using ADD_DEPENDENCIES in , but it works differently than I expected. How can I get the gdbus-codegen-glibmm command to run first?
add_custom_command will run the command during build phase (when running make). Since it generate the files required by the next target, it will fail if the file have never been generated. You can configure the file when running cmake too, using execute_process() in addition of add_custom_command(). You can also use configure_file() to create a placeholder for the target before you erase it later with gdbus-codegen-glibmm when running make.
70,108,420
70,108,699
how to poll a com port in c++
This is all the code for polling the com port, according to the modbus-RTU protocol, the device does not respond. I can't figure out how to get the device to respond to me. The device address and the function code are enough to answer. These are the first two characters (0x15, 0x03 ...) I do not know what I am doing wrong! There is a code: #include <windows.h> #include <stdio.h> #include <iostream> #include <TCHAR.h> using namespace std; #pragma warning(disable:4996) //ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ COM ΠΏΠΎΡ€Ρ‚Π° HANDLE hSerial; //Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΠΏΠΎΡ€Ρ‚Π° LPCTSTR sPortName = L"COM3"; int ReadCOM() { int a = 0; DWORD iSize; char sReceivedChar = { 0 }; char recBuf[100] = { 0 }; recBuf[0] = '\0'; while (!a) { //ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠ΅ ΠΎΡ‚Π²Π΅Ρ‚Π° ReadFile(hSerial, &sReceivedChar, 1, &iSize, 0); // ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ 1 Π±Π°ΠΉΡ‚ if (iSize > 0) // Ссли Ρ‡Ρ‚ΠΎ-Ρ‚ΠΎ принято, Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ { cout << "Answer: " << sReceivedChar; strcat(recBuf, &sReceivedChar); } else { cin >> a; } } CloseHandle(hSerial); return 0; } int _tmain(int argc, _TCHAR* argv[]) { //настройка ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ² соСдинСния (Π’ Π΄Π°Π½Π½ΠΎΠΌ случаС COM ΠΏΠΎΡ€Ρ‚Π°) DCB *dcbSerialParams = (DCB*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DCB));; dcbSerialParams->DCBlength = sizeof(dcbSerialParams); if (BuildCommDCB(L"baud=9600 parity=E data=8 stop=2", dcbSerialParams)) { std::cout << "success 1" << std::endl; } else { std::cout << "failure 1" << std::endl; } dcbSerialParams->fNull = TRUE; //установка Ρ‚Π°ΠΉΠΌΠ°ΡƒΡ‚Π° ΠΏΡ€ΠΈΠ΅ΠΌΠ° ΠΈ ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‡ΠΈ ΠΏΠΎΡ€Ρ‚Π° COMMTIMEOUTS CommTimeOuts; CommTimeOuts.ReadIntervalTimeout = 1000; CommTimeOuts.ReadTotalTimeoutConstant = CommTimeOuts.ReadTotalTimeoutMultiplier = 100; CommTimeOuts.WriteTotalTimeoutConstant = CommTimeOuts.WriteTotalTimeoutMultiplier = 100; //ΠΎΡ‚ΠΊΡ€Ρ‹Ρ‚ΠΈΠ΅ ΠΏΠΎΡ€Ρ‚Π° для чтСния/записи hSerial = CreateFile(sPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); //ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° роботоспособности (Π½Π΅ Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚) if (hSerial == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { cout << "wrn::Serial port does NOT exist.\n"; } else { cout << "wrn::Some other error occurred.\n"; } } //(Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚) пишСм ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰Π΅Π΅ сообщСниС else { cout << "suc::Serial port DOES exist.\n"; } //запись свойств ΠΏΠΎΡ€Ρ‚Π° if (!SetCommState(hSerial, dcbSerialParams)) { cout << "faulure 2" << endl; } if (!SetCommTimeouts(hSerial, &CommTimeOuts)) { cout << "failure 3" << endl; } //ОсвобоТдСниС DCB HeapFree(GetProcessHeap(), 0, dcbSerialParams); //char data[] = { 0x15, 0x03, 0x6B, 0x03, 0x37, 0x7E }; char data[] = { 0x15, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A}; DWORD dwSize = sizeof(data); // Ρ€Π°Π·ΠΌΠ΅Ρ€ этой строки DWORD dwBytesWritten; // Ρ‚ΡƒΡ‚ Π±ΡƒΠ΄Π΅Ρ‚ количСство собствСнно ΠΏΠ΅Ρ€Π΅Π΄Π°Π½Π½Ρ‹Ρ… Π±Π°ΠΉΡ‚ BOOL iRet = WriteFile(hSerial, data, dwSize, &dwBytesWritten, NULL); //Π½ΠΎΡ€ΠΌΠ°Π»ΡŒΠ½Π°Ρ Ρ€Π°Π±ΠΎΡ‚Π° if (iRet) { cout << "nor :: " << dwSize << " Bytes in string. " << dwBytesWritten << " Bytes sended. " << endl; } //ошибка ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‡ΠΈ else { cout << "wrn :: " << "db = " << dwBytesWritten << "\nds = " << dwSize << endl; } ReadCOM(); return 0; }
Did you check your request string with a terminal program f.e. hterm? As far as I know only two tx characters will not make an answer from the device, there is also a crc at end of a frame https://www.der-hammer.info/pages/terminal.html
70,108,453
70,109,438
How to structure "future inside future"
I am building a system where a top layer communicates with a driver layer, who in turn communicate with a I2C layer. I have put my I2C driver behind a message queue, in order to make it thread safe and serialize access to the I2C bus. In order to return the reply to the driver, the I2C layer returns a std::future with a byte buffer inside that is filled out when the I2C bus read actually happens. All this works and I like it. My problem is that I also want the driver to return a future to the top layer, however this future will then depend on the previous future (when the I2C driver future-returns a byte buffer, the driver will have to interpret and condition those bytes to get the higher-level answer), and I am having problems making this dependency "nice". For example, I have a driver for a PCT2075 temperature sensor chip, and I would like to have a: future<double> getTemperature() method in that driver, but so far I can't think of a better way than to make an intermediate "future-holder" class and then return that: class PCT2075 { public: class TemperatureFuture { private: std::future<std::pair<std::vector<uint8_t>, bool>> temperatureData; public: TemperatureFuture(std::future<std::pair<std::vector<uint8_t>, bool>> f); template< class Clock, class Duration > std::future_status wait_until(const std::chrono::time_point<Clock, Duration>& timeout_time) const; void wait() const; // wait and wait_until just waits on the internal future double get(); }; TemperatureFuture getTemperature(); }; This structure works and I can go forward with it, but for some reason I am not super happy with it (though I can't quite explain why... :/ ). So my questions are: Is there some pattern that can make this better? Would it make sense to let TemperatureFuture inherit directly from std::future (I have heard that "do not inherit from std classes" is a good rule)? Or is this just how you do it, and I should stop worrying about nothing? Ps. I also have another method whose answer relies on two I2C reads, and thus two different futures. It is possible to rework this to only have a one-on-one dependency, but the current way can handle the one-on-multiple variant so it would be nice if a potential new proposal also could.
You are looking for an operation called then, which as commenters note is sadly missing even in C++20. However, it's not hard to write a then yourself. template<typename Fun, typename... Ins> std::invoke_result_t<Fun, Ins...> invoke_future(Fun fun, std::future<Ins>... futs) { return fun(futs.get()...); } template<typename Fun, typename... Ins> std::future<std::invoke_result_t<Fun, Ins...>> then(Fun&& fun, std::future<Ins>... futs) { return std::async(std::launch::deferred, invoke_future<Fun, Ins...>, std::forward<Fun>(fun), std::move(futs)...); } I expect something like this wasn't standardised because it makes loads of assumptions about how the function should be run once the result is ready.
70,108,588
70,108,747
What is "a>b" as a parameter which requires a function pointer or lambda expression?
Below is the very simple use of boost::log::set_filter, #include <boost/log/trivial.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> namespace logging = boost::log; void test() { logging::add_file_log("sample.log")->set_filter( logging::trivial::severity >= logging::trivial::info ); } According to definition of set_filter, template< typename FunT > void set_filter(FunT const& filter) { BOOST_LOG_EXPR_IF_MT(boost::log::aux::exclusive_lock_guard< mutex_type > lock(m_Mutex);) m_Filter = filter; } filter is supposed to be a function pointer or lambda expression. What is logging::trivial::severity >= logging::trivial::info and how it is casted to a function?
The result of a user-defined >= can be any type, it does not have to be bool. In this case, the library author defined a >= that returns a function object. As a sketch, it's something like this struct severity_t {} severity; enum severity_level { info, ... }; struct greater_equal_filter { severity_level level; bool operator()(severity_level other) { return other >= level; } }; greater_equal_filter operator>=(severity_t, severity_level level) { return { level }; }
70,108,635
70,108,733
C++: Variable that is passed by const referance changes value
for an assignment I was provided with a framework of different classes that use parameters passed by const reference. When I initialize one instance of this same class and then a second one later, the values of the members that were passed by const reference within the first one change. I am not allowed to change a_cameras. Is there anything I can do within the class definition so that I avoid the values just changing on their own? Initialization of PerspectiveCamera: #include <core/image.h> #include <core/point.h> #include <core/vector.h> #include <core/scalar.h> #include <core/julia.h> #include <rt/ray.h> #include <rt/cameras/perspective.h> #include <rt/cameras/orthographic.h> #include <iostream> #include <rt/renderer.h> using namespace rt; void a_cameras() { Image img(800, 800); Image low(128, 128); PerspectiveCamera pcam(Point(0, 0, 0), Vector(1, 0, 0.1f), Vector(0, 0, 1), pi/3, pi/3); Renderer r1(&pcam,0); r1.test_render2(img); r1.test_render2(low); img.writePNG("a1-2.png"); low.writePNG("a1-2-low.png"); PerspectiveCamera pcam2(Point(0, 0, 0), Vector(0.5f, 0.5f, 0.3f), Vector(0, 0, 1), pi * 0.9f, pi * 0.9f); Renderer r12(&pcam2,0); r12.test_render2(img); img.writePNG("a1-3.png"); OrthographicCamera ocam(Point(0, 0, 0), Vector(0.1f, 0.1f, 1), Vector(0.2f, 1.0f, 0.2f), 10.f, 10.f); Renderer r2(&ocam,0); r2.test_render2(img); img.writePNG("a1-4.png"); } Definition of PerspectiveCamera perspective.cpp: #include <rt/cameras/perspective.h> #include <cmath> #include <core/matrix.h> namespace rt { PerspectiveCamera::PerspectiveCamera(const Point& center, const Vector& forward, const Vector& up, float verticalOpeningAngle, float horizontalOpeningAngle) : center(center), forward(forward) { vertFactor = tanf(verticalOpeningAngle / 2.0f); horFactor = tanf(horizontalOpeningAngle / 2.0f); x_axis = cross(forward, up).normalize(); up_axis = cross(x_axis, forward).normalize(); //vertFactor = tanf(verticalOpeningAngle / 2.0f); //horFactor = tanf(horizontalOpeningAngle / 2.0f); } Ray PerspectiveCamera::getPrimaryRay(float x, float y) const { printf("center: (%f, %f, %f); forward: (%f, %f, %f); x_axis: (%f, %f, %f); up_axis: (%f, %f, %f)\n", center.x, center.y, center.z,forward.x, forward.y, forward.z, x_axis.x, x_axis.y, x_axis.z, up_axis.x, up_axis.y, up_axis.z); Vector direction = x * x_axis * horFactor + y * up_axis * vertFactor + forward; return {center, direction}; } } perspective.h: #ifndef CG1RAYTRACER_CAMERAS_PERSPECTIVE_HEADER #define CG1RAYTRACER_CAMERAS_PERSPECTIVE_HEADER #include <rt/cameras/camera.h> #include <core/vector.h> #include <core/point.h> namespace rt { class PerspectiveCamera : public Camera { public: PerspectiveCamera( const Point& center, const Vector& forward, const Vector& up, float verticalOpeningAngle, float horizontalOpeningAngle ); virtual Ray getPrimaryRay(float x, float y) const; const Point &center; const Vector &forward; Vector x_axis; Vector up_axis; float vertFactor; float horFactor; }; } #endif Thank you, Jane
Your code is rather complicated. Though much less is needed to see that the assumption: "A const reference does not change its value." is based on a misunderstanding. #include <iostream> struct foo { const int& x; }; int main() { int a = 42; foo f{a}; a = 0; std::cout << f.x; } The output of this is 0 even though f.x was initialized with a when a had the value 42. f holds a constant reference to a. This merely implies that you cannot modify a via f.x. It does not imply that x cannot be modified through other means. A constant reference is not a reference to a constant!
70,108,639
70,109,089
output map object where the value can be any data type
Trying to output a map object where the value can be any data type. Tried the following: #include <iostream> #include <unordered_map> #include <any> std::unordered_map<std::string, std::any> example = { {"first", 'A'}, {"second", 2}, {"third", 'C'} }; std::ostream &operator<<(std::ostream &os, const std::any &m) { for (auto &t : example) { os << "{" << t.first << ": " << t.second << "}\n"; } return os; } int main() {std::cout << example; return 0; } But,getting infinite loop of values.
There isn't a good way of printing the contents of an arbitrary std::unordered_map<std::string, std::any>. It might have contents that aren't printable, and you've discarded the information about what type the contents actually are. You need to keep that information somewhere. #include <string> #include <iostream> #include <unordered_map> #include <any> #include <utility> template <typename T> std::ostream & print_any(std::ostream & os, const std::any & any) { return os << std::any_cast<const std::decay_t<T> &>(any); } class any_printable { using print_t = std::ostream & (*)(std::ostream &, const std::any &); std::any value; print_t print; public: template <typename T> any_printable(T&& t) : value(std::forward<T>(t)), print(print_any<T>) {} friend std::ostream & operator<<(std::ostream & os, const any_printable & ap) { return ap.print(os, ap.value); } }; std::ostream &operator<<(std::ostream &os, const std::unordered_map<std::string, any_printable> &map) { for (auto & [key, value] : map) { os << "{" << key << ": " << value << "}\n"; } return os; } int main() { std::unordered_map<std::string, any_printable> example = { {"first", 'A'}, {"second", 2}, {"third", 'C'} }; std::cout << example; } See it on coliru
70,108,692
70,109,103
Calling function that was declared virtual in interface (and implemented in derived class) inside base abstract class
I have the following inheritance model: interface abstract class concrete derived class _________________________________________________________ IPriorityQueue -> APriorityQueue -> UnsortedPriorityQueue My member function was declared purely virtual in the interface. In the abstract class, I want to use size() to already implement empty(), since if size = 0, then the priority queue is empty. size() is properly implemented in the derived class. #include <list> template <typename K, typename V> class IPriorityQueue { public: virtual int size(void) const = 0; virtual bool empty(void) const = 0; }; template <typename K, typename V> class APriorityQueue : virtual public IPriorityQueue<K, V> { public: bool empty(void) const { return (!size()); } }; template <typename K, typename V> class UnsortedPriorityQueue : virtual public APriorityQueue<K, V> { private: std::list<V> _list; public: int size(void) const { return (this->_list.size()); } }; int main() { UnsortedPriorityQueue<int, char> test; } However, I get the following error: ../../libft/APriorityQueue.hpp:49:37: error: there are no arguments to 'size' that depend on a template parameter, so a declaration of 'size' must be available [-fpermissive] bool empty(void) const { return (!size()); } ^~~~ ../../libft/APriorityQueue.hpp:49:37: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated) I read in some other answers on StackOverflow that one has to specify the namespace, so I modified it the following way: bool empty(void) const { return (!IPriorityQueue<K, V>::size()); } But now I get a linker error complaining that IPriorityQueue<K, V>::size() is not implemented: main.o:main.cpp:(.text$_ZNK14APriorityQueueIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE5emptyEv[_ZNK14APriorityQueueIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE5emptyEv]+0x28): undefined reference to `IPriorityQueue<int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::size() const' collect2.exe: error: ld returned 1 exit status Is there any way I can figure this out? Is such a design even possible? Thank you in advance
Just replace bool empty(void) const { return (!size()); } with bool empty(void) const { return (!this->size()); }//note i have added this-> and that will solve your problem. Here's the rule the compiler does not look in dependent base classes when looking up nondependent names . Here's a good article for reading more about this.
70,108,763
70,112,613
Estimate the camera pose in the reference system using one marker with ARUCO
I am currently working on a camera pose estimation project using only one marker with ARUCO. I used Aruco's Marker Detector to detect markers and get the marker's Rvec and Tvec. I understand these two vectors represent the transform from the marker to the camera, which is the marker's pose w.r.t camera. I form a 4 by 4 matrix called T_marker_camera using these two vectors. Then, I set up a world frame (left handed) and get the marker's world pose, which is a 4 by 4 transform matrix. I want to calculate the pose of the camera w.r.t the world frame, and I use the following formula to calculate it: T_camera_world = T_marker_world * T_marker_camera_inv Before I perform the above formula, I convert the OpenCV coordinates to the left handed one (flip the sign of x axis). However, I didn't get the correct x, y, z of the camera w.r.t the world frame. What did I miss to get the correct answer? Thanks
The one equation you gave looks right, so the issue is probably somewhere that you didn't show/describe. A fix in your notation will help clarify. Write the pose/source frame on the right (input), the reference/destination frame on the left (output). Then your matrices "match up" like dominos. rvec and tvec yield a matrix that should be called T_cam_marker. If you want the pose of your camera in the world frame, that is T_world_cam = T_world_marker * T_marker_cam T_world_cam = T_world_marker * inv(T_cam_marker) (equivalent to what you wrote, but domino) Be sure that you do matrix multiplication, not element-wise multiplication. To move between left-handed and right-handed coordinate systems, insert a matrix that maps coordinates accordingly. Frames: OpenCV camera/screen: right-handed, {X right, Y down, Z far} ARUCO (in OpenCV anyway): right-handed, {X right, Y far, Z up}, first corner is top left (-X+Y quadrant) whatever leftie frame you have, let's say {X right, Y up, Z far} and it's a screen or something The hand-change matrix for typical frames on screens is an identity but with the entry for Y being a -1. I don't know why you would flip the X but that's "equivalent", ignoring any rotations.
70,108,775
70,108,776
gdb exits immediately `Process finished with exit code 1` or lldb `'A packet returned error 8'` on docker
This took me full days to find, so I am posting this for future reference. I am developing C++ on a docker image. I am using clion. My code is compiled in debug mode, and runs fine in run mode, but when trying to debug, the process exits immediately with the very informative Process finished with exit code 1 When switching the debugger from to Trying to debug still exits, but yields a popup in clion 'A packet returned error 8' The same code debugs fine on a local computer. The docker run command is RUN_CMD="docker run --group-add ${DOCKER_GROUP_ID} \ --env HOME=${HOME} \ --env="DISPLAY" \ --entrypoint /bin/bash \ --interactive \ --net "host" \ --rm \ --tty \ --user=${USER_ID}:${GROUP_ID} \ --volume ${HOME}:${HOME} \ --volume /mnt:/mnt \ $(cat ${HOME}/personal-uv-docker-flags) \ -v "${HOME}/.Xauthority:${HOME}/.Xauthority:rw" \ --volume /var/run/docker.sock:/var/run/docker.sock \ --workdir ${HOME} \ ${IMAGE} $(${DIR}/impl/known-tools.py cmd-line ${TOOL})" How to debug C++ on docker?
Eventually, I found this comment which led me to this blog post, in which I learned C++ debugging is disallowed on docker by default. The arguments --cap-add=SYS_PTRACE and --security-opt seccomp=unconfined are required for C++ memory profiling and debugging in Docker. I added --cap-add=SYS_PTRACE --security-opt seccomp=unconfined to the docker run command, and the debugger was able to connect.
70,109,239
70,109,562
RSA Algorithm is not working for certain numbers
I have a homework that includes handling user login and register. For that the teacher told us to use the RSA Algorithm to encrypt the passwords of the users. My problem is with the RSA. I am trying to write it to encrypt only 1 integer and after that I will write a new method that encrypts a string. So at this moment, my code works for some integers and for others it fails pretty bad. This is the header file #ifndef _RSA_ #define _RSA_ #include <cmath> #include <string> // A class that defines the RSA algorithm class RSA { private: int p, q, n, z, d = 0, e; public: RSA(); int gcd(int a, int b); int encrypt(int m); int decrypt(int c); }; #endif And this is the file where I implement those functions. #include "./RSA.h" RSA::RSA() { this->p = 3; this->q = 11; this->z = (this->p - 1) * (this->q - 1); this->n = this->p * this->q; for (this->e = 2; this->e < this->z; this->e++) { if (this->gcd(this->e, this->z) == 1) { break; } } for (int i = 0; i <= 9; ++i) { int x = (i * this->z) + 1; if (x % this->e == 0) { this->d = x / this->e; break; } } } int RSA::gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int RSA::encrypt(int m) { return (int)pow(m, e) % this->n; } int RSA::decrypt(int c) { return (int)pow(c, d) % this->n; } Now I am going to provide you with some numbers that work and some numbers that do not work. Saying that the numbers work I mean that after I decrypt the result of encrypt method I get the initial number. It works for 1,2,6,7,8,9,10(it returns 10 for encrypted part and 10 for decrypted), 11(same as 10), 12(same as 11), 13, 14, 15, 16. I tested numbers in the range [1, 17] and it failed for 3,4,5,17. It returns completely random numbers for this 4 numbers. Also, I tried it on other number ranges and the result was the same.
Even with small numbers like that it's easy to exceed the limits of int with exponentiation. If you make your own pow, it should apply the modulo after every step: // computes x**y % n int custom_pow(int x, int y, int n) { int res = 1; for(;y;y--) { res = (res*x) % n; } return res; }
70,109,363
70,109,462
Why do I need Boost.SmartPtr for the C++ compiler that supports C++11 and later?
The boost C++ library is a famous sandbox for the language and Standard Library features that absorbed with each new version of the Standard C++. However boost components that eventually became a part of the Standard are still present in boost. One of the classic examples of said above are smart pointers. So why do I need Boost.SmartPtr for the C++ compiler that supports C++11 and later?
Why do I need Boost.SmartPtr for the C++ compiler that supports C++11 and later? Because: You may need your program to compile with another compiler that doesn't support C++11 or later. You may not want to bother implementing make_unique yourself. Sure it's easy, but why do it when you can use an existing implementation? You may want to use one of the smart pointers provided by Boost.SmartPtr besides shared pointer. You may already have been using it, and don't want to pay for the effort of stopping using it.
70,109,372
70,109,482
Global namespace variables without translation unit issues?
I'm trying to abstract away some GLFW input code by using a global variable state to keep track of key presses. I thought using namespaces would be nice, so I thought doing something like: namespace InputState { namespace KeyPressed { static bool left = false; static bool right = false; static bool down = false; static bool up = false; }; }; and then accessing these variables like if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { InputState::KeyPressed::left = true; } else { InputState::KeyPressed::left = false; } and if (InputState::KeyPressed::left) { body->velocity.x -= 0.25f; } would be really easy and visually/architecturally appealing, but as I've found out, creating static variables in namespaces brings some weird behavior that make this not work as intended. I've tried using extern, but that gave me linker errors stating that there was a redefinition of the variables. I've triple checked that I have my header guards in place. Is there some way I can get this working where I truly have a global variable within a namespace or is this just not possible/not intended behavior for namespaces?
Is there some way I can get this working where I truly have a global variable within a namespace or is this just not possible/not intended behavior for namespaces? If you want to use these variables in other source file then you can do so using extern as follows: myheader.h #ifndef MYHEADER_H #define MYHEADER_H namespace InputState { namespace KeyPressed { extern bool left, right, down, up; }; }; #endif mysource.cpp #include "myheader.h" namespace InputState { namespace KeyPressed { bool left = false; bool right = false; bool down = false; bool up = false; } } main.cpp #include "myheader.h" #include <iostream> int main() { std::cout<<InputState::KeyPressed::left<<std::endl; InputState::KeyPressed::left = true; std::cout<<InputState::KeyPressed::left<<std::endl; } Just like i have used the variable InputState::KeyPressed::left in main.cpp you can now use it in your own file and it will work. The above program works as can be seen here.
70,109,628
70,109,841
How should I define my destructor for the Node class in C++?
I am supposed to implement a class of Nodes for the tree that consists of static nodes (for educational purposes). The classes headers look like this: class CNodeStatic { private: int i_val; CNodeStatic *pc_parent_node; vector<CNodeStatic> v_children; public: CNodeStatic() {i_val =0; pc_parent_node = NULL;}; ~CNodeStatic(); void vSetValue(int iNewVal) {i_val = iNewVal;}; int iGetChildrenNumber() {return (v_children.size());}; void vAddNewChild(); void vAddChild(CNodeStatic pcChildNode); CNodeStatic *pcGetChild (int iChildOffset); }; class CTreeStatic { private: CNodeStatic c_root; public: CTreeStatic(); ~CTreeStatic(); CNodeStatic *pcGetRoot() {return (&c_root);}; bool bMoveSubtree(CNodeStatic *pcParentNode, CNodeStatic *pcNewChildNode); void vPrintTree(); }; However I am not sure how the destructor for such class should look like. I know that we need to define destructors when there is a dynamically allocated memory or pointer in class. In this case it's pc_parent_node that points to the parent of the node. However if I try to define my destructor only as delete pc_parent_node the program won't work.
I know that we need to define destructors when there is a dynamically allocated memory or pointer in class Right. If a class manages a resource, it must manage the resource and cleaning up is part of that. In this case it's pc_parent_node that points to the parent of the node. Pointers != managing a resource. In particular, raw pointers should not be used to manage lifetime. The shown code does not dynamically allocate something. The class does not seem to own a resource, hence there is nothing it must delete in its destructor. If it does manage a resource, it should do so by using a smart pointer or container. Read about the rule of zero (https://en.cppreference.com/w/cpp/language/rule_of_three). A class that manages a resource should do only that and nothing else. In all other cases you should strive to follow the rule of zero by delegating lifetime managment to smart pointers or containers. The best destructor is a destructor that the compiler can generate. Only if that is not sufficient you need to manually manage something.
70,109,726
70,109,941
Segmentation fault caused by repeating pop_back() and push_back()
When I run the following code in Clion(an IDE) with c++11. I ran into a segmentation fault. But if I delete the if statement, add else before pop_back, remove push_back, or remove pop_back(do them separately). There would be no error. So why there would be a segmentation fault and why doing any of the above would eliminate the error? #include "vector" using namespace std; int main() { vector<int> test; for(int i = 0; i < 10000; i++){ if(i % 2 == 0) test.push_back(i); test.pop_back(); } } Edit: Some people say it's because pop_back from empty vector, but if I remove push_back() there won't be any problem(even if I push_back some elements before the loop).
You are popping from the vector when it is empty. Using pop_back() from an empty vector results in undefined behaviour which means: your program could crash your program could print some nonesens your program could continue normally your program could continue normally, but have some other strange seemingly unrelated behaviour later or some other behaviour Consider this code: #include <vector> #include <iostream> using namespace std; int main() { vector<int> test; for (int i = 0; i < 10; i++) { if (i % 2 == 0) test.push_back(i); if (test.empty()) cout << "stack is empty" << endl; else test.pop_back(); } }
70,109,997
70,110,333
How to format an 2d array of different type sized strings (e.g. x, xxx ,xx ,xxx) to look more square like when printed
This is my code Does any one know how I can format it so it looks more like a square rather due to the different character sizes in each element. 1 int main() { string a[4][4]= {{"\xC9","\xCD","\xCD","\xBB"}, {"\xBA","p1","p2","\xBA"}, {"\xBA","100","p3","\xBA"}, {"\xC8","\xCD","\xCD","\xBC"}}; printSquare(a); this is my code but the output seems to look funny
There's not really a shortcut here: you'll have to all bring them to the same length. Which length to choose: hard. You might first have to make all rows, then find the longest one, the format all rows to have the same length, then make the top and bottom bar. You can do that with iostreams / stringstream in standard C++. But it's really a pain. iostreams are simply not a good output formatting library. I'd instead recommend using fmtlib, which supports format strings. So you can first format all your rows, and save the length of the longest #include "fmt/format.h" #include "fmt/ranges.h" #include <algorithm> #include <fmt/core.h> #include <string> #include <vector> int main() { std::vector<std::vector<std::string>> data{ {"p1", "p2"}, {"100", "p3"}, {"very long string"}}; unsigned int longest_row = 0; for (const auto &row : data) { unsigned int rowlength = fmt::formatted_size("{}", fmt::join(row.begin(), row.end(), "")); longest_row = std::max(longest_row, rowlength); } // Explanation: Print corner - empty string - corner, but pad "empty string" // longest row times with "middle piece" > is for right-aligned padding // (doesn't matter for empty string) fmt::print("β•”{:═>{}}β•—\n", "", longest_row); for (const auto &row : data) { // ^ is for centered padding // fill with " " (we could omit this, but I think it's clearer) const std::string this_row = fmt::format("{}", fmt::join(row.begin(), row.end(), "")); fmt::print("β•‘{: ^{}}β•‘\n", this_row, longest_row); } fmt::print("β•š{:═>{}}╝\n", "", longest_row); } Remarks: Replaced your string arrays with std::vectors. Just more convenient. No need to use escape sequences to include unicode characters in strings, unless your compiler sucks. later on, learned about formatted_size, which simplifies things
70,110,055
70,110,141
C++: Variables change values after initialization of different class
I have the following problem. PerspectiveCamera pcam2(Point(0, 0, 0), Vector(0.5f, 0.5f, 0.3f), Vector(0, 0, 1), pi * 0.9f, pi * 0.9f); Renderer r12(&pcam2,0); In the above code, pcam2 is initialized and then after that, &pcam2 is passed on to r12. pcam2 has members const Point& center, const Vector& forward, const Vector& up, and two float numbers that are passed upon initialization in said order. r12 has members Camera* cam_ and an int number. The strange thing that happens is that during the initialization of r12, the values of the field center of pcam2 get changed to some bogus like Point(1.984192e+27, 4.59149455e-41, 0) when in the code you can see that pcam2 was initialized with Point(0, 0, 0). Literally all that happens during initialization of r12 is that its members are assigned their values via member initialization list. I really don't understand what is happening here and I don't know enough about C++ to find out on my own. Thanks in advance.
Point(0, 0, 0) is a temporary object which lives only until the nearest ;. If you store a reference to it inside pcam2, this reference becomes dangling right after the line with pcam2 initialization is complete. Any access to the dangling reference afterwards is undefined behavior. You typically don't need to store any references in structs, having ownership semantics (i.e. storing by-value and copying/moving data into struct) is less errorprone and easier to reason about.
70,110,371
70,111,033
Why is object member value changing between 2 getter calls
I am getting unexpected value in second getter call which looks wrong to me, any specific reason for this happening? #include<iostream> using namespace std; class Test { public: int &t; Test (int x):t(x) { } int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout << t1.getT() << " "; cout << t1.getT() << endl; return 0; }
The problem here is that your code results in undefined behavior. The constructor of Test does not take a reference to an int but a copy, and due to int x only being a temporary copy which is not guaranteed to live until your second function call you will end up with undefined behavior. You would have to change your constructor to the following to make the code work properly: Test(int& x) : t(x) {} Now the reference you're working with in Test will be the same x as defined in main
70,111,021
70,111,067
Strange behaviour of if in C++
At my work I tried to use this construction: if (repl && (repl = replaced.count(*l))) { // repl isn't used here ... } and in my mind it should work the same way as bool newRepl = replaced.count(*l); if (repl && newRepl) { // repl isn't used here ... } repl = newRepl; because expressions in && evaluate from left to right, but unexpectedly it's not. Is it a not specified construction in C++ or I don't correctly understand how it should work? Example of code with a problem: std::set<int> set{3, 4, 6}; bool repl = false; for (size_t i = 3; i < 7; ++i) { if (repl && (repl = set.count(i))) { std::cout << "strangeif" << std::endl; } } output: std::set<int> set{3, 4, 6}; bool repl = false; for (size_t i = 3; i < 7; ++i) { bool newRepl = set.count(i); if (repl && newRepl) { std::cout << "strangeif" << std::endl; } repl = newRepl; } output: strangeif
&& is short-circuiting. Your original code is equivalent to this: if (repl) { repl = replaced.count(*l)) if (repl) { // repl isn't used here ... } }
70,111,290
70,111,691
Correct way to numerically calculate a sum
I am trying to numerically calculate a sum: I fully understand that it is an easy sum, however, my mind keeps tingling me for a few days consequently, if I am doing it correctly. Here is an outline of a C++ code that I have written to calculate it: struct vecs{ float x; float y; float z; float a; }; struct vector_file{ int id; vector<vecs> VAL; }; vector<vector_file> VEC; I[10][10]={} double absolute_val(double xi, double yi, double zi, double xj, double yj, double zj){ return(sqrt(pow(xi-xj,2)+pow(yi-yj,2)+pow(zi-zj,2))); } for (int i=0;i<VEC.size();i++){ for (int j=0;j<i;j++){ double integ=0; for (int k=0;k<VEC[i].VAL.size();k++){ for (int l=0;l<VEC[j].VAL.size();l++){ integ+=VEC[i].VAL[k].a*VEC[j].VAL[l].a/absolute_val(VEC[i].VAL[k].x,VEC[i].VAL[k].y,VEC[i].VAL[k].z,VEC[j].VAL[l].x,VEC[j].VAL[l].y, VEC[j].VAL[l].z); } } I[i][j]=integ; } } I only need the off-diagonal elements and do not need the upper triangular part of the matrix as it is analogous to lower triangular part. I have checked it multiple times, however, still going back and wondering, if I have done it correctly. Thank you so much in advance for taking time to look at it.
Yes, your code is correct. If you want to make it "more obviously" correct, I would move it closer to the mathematical definitions by defining some helper functions. Concretely: const vecs& R(int upper, int lower) { return VEC[upper].VAL[lower]; } const float a(int upper, int lower) { return VEC[upper].VAL[lower].a; } int num_vecs(int upper) { return VEC[upper].VAL.size(); } Next, I would write magnitude_diff to accept two vecs. It is not strictly the magnitude because you're only looking at three of the four components, but I don't feel comfortable defining operator - for 3/4 components either. double magnitude_diff(const vecs& i, const vecs& j){ return sqrt(pow(i.x-j.x,2) + pow(i.y-j.y,2) + pow(i.z-j.z,2)); } and then your inner loop stays very close to the formula: double integ=0; for (int k=0; k < num_vecs(i); k++){ for (int l=0; l < num_vecs(j); l++){ integ += a(i, k) * a(j, l) / magnitude_diff(R(i, k), R(j, l)); } } I[i][j] = integ;
70,111,914
70,114,545
How to use Boost::log not to rewrite the log file?
Below is the simple example of using boost::log to write log, #include <boost/log/trivial.hpp> namespace logging = boost::log; logging::add_file_log("sample.log")->set_filter( logging::trivial::severity >= logging::trivial::info ); BOOST_LOG_TRIVIAL(info) << "log content"; Every time run logging::add_file_log("sample.log") would rewrite the log file -- erase the original stuff and write new log. So it can't be used for a multi-process-one-log-file system. How do I set not to rewrite the file? Edit: I wrap this boost::log in a dll and attempt to let other exe files to call it.
You can pass an openmode to the setup function: Live On Coliru #include <boost/log/trivial.hpp> #include <boost/log/utility/setup.hpp> #include <random> namespace logging = boost::log; namespace logkw = logging::keywords; int main() { logging::add_file_log("sample.log", logkw::open_mode = std::ios::app) ->set_filter( // logging::trivial::severity >= logging::trivial::info // ); std::mt19937 mt(std::random_device{}()); BOOST_LOG_TRIVIAL(info) << "log content " << std::uniform_int_distribution(5,50)(mt); } Prints e.g. log content 33 log content 14 log content 39 log content 39 log content 46
70,112,122
70,112,213
What is a better data structure to replace a map o sets?
recently I wrote a post in which I asked for help in a problem I had in a C++ code. However, some people focused on a definition I put in one of my codes, which is: std::map <std::string, std::pair<std::string, std::string>> map_example; saying that this is considered a bad definition and that I should replace it. I want to ask you if you can suggest me a better way to represent this data structure in a C++ code (possibly I want to avoid tuples), thanks. EDIT Here the link to the question I talked above.
A common concern against std::pair is poor naming of its members. Your code will be sprinkled with first and second when you probably could use better names. Compare struct customer_name_and_company { std::string customer_name; std::string company; }; std::map<std::string, customer_name_and_company> m; for (const auto& e : m) { std::cout << e.customer_name << " " << e.company << "\n"; } with the same code using a std::pair: std::map<std::string, std::pair<std::string,std::string> m; for (const auto& e : m) { std::cout << e.first << " " << e.second << "\n"; } Neither the type nor the loop using the type uses proper names. Names are important! Consider you are looking only at the loop, then customer_name and company immediately tell you what those members are, while first and second requires you to track down previous definitions to make any sense out of the code. std::pair is good for generic code when you simply have no way to give names better than first and second because you don't know what they are. Also the standard library makes extensive use of std::pair (for example std::map::insert and others). I suppose that is to avoid inflation of simple types that would pollute the std namespace. In your own code, on the other hand, any variable and type you can give a meaningful name, means more readable code.
70,112,202
70,112,287
multithread segment fault destructors
i have a segment fault when it calls the function unit_thread_data,Actually it is caused by ~Data(). thread1 is all right, but thread2 cause the segment fault, the whole code is as fallows:(forgive the poor code style), error info is double free or corruption. Other info: gcc5.4.0, centos7. any help? thank you very much! #include <iostream> #include <pthread.h> #include <unistd.h> using namespace std; class Data { public: int* A_; Data() { cout<<"111\n"; A_=NULL; } ~Data() { cout<<"222\n"; if(A_) { delete A_; } } }; struct thread_data_t { Data* d; }; void* _add(void* _pthread_data) { thread_data_t* pthread_data = (thread_data_t*) _pthread_data; pthread_data->d->A_ = new int[2]; pthread_data->d->A_[0] = 1; pthread_data->d->A_[1] = 2; std::cout<<pthread_data->d->A_[0]+pthread_data->d->A_[1]<<endl; return (void*)0; } void unit_thread_data(thread_data_t* pthread_data) { for(int i=0;i<2;i++) { delete[] pthread_data[i].d->A_; delete pthread_data[i].d; } delete[] pthread_data; } int main() { int num_threads = 2; pthread_t threads[num_threads]; thread_data_t* pthread_data = new thread_data_t[num_threads]; for(int i=0;i<num_threads; i++) { pthread_data[i].d = new Data(); } for (int i=0; i<num_threads; i++) { pthread_create(&threads[i], NULL, _add, (void*)(pthread_data+i)); } for (int i=0; i<num_threads; i++) { pthread_join(threads[i], NULL); } sleep(1); unit_thread_data(pthread_data); return 0; }
delete[] pthread_data[i].d->A_; This deletes the A_ member of your Data class, an int *. Immediately afterwards, this happens: delete pthread_data[i].d; And this deletes the Data itself. Data's destructor then does the following: if(A_) { delete A_; } This then proceeds to attempt delete the same pointer. This should be delete[]d instead of deleted in the first place, but this is moot because this pointer is already deleted, and this tries to delete it a 2nd time. This results in undefined behavior.
70,112,492
70,112,672
Same class as a member inside a class in C++?
Sorry I ill formed the question earlier. The piece of code is something like: class Bar { public: // some stuff private: struct Foo { std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo; // some other basic variables here }; Foo foo; }; I got the basic idea about subFoo. But I am wondering that a single instance of Bar will contain only a single instance of Foo that is foo member variable? So a single instance/object of Bar will not be able to map multiple Foo inside the subFoo? It feels like I am missing something here, can anyone break it down for me?
There are more misunderstandings about nested class definitions than there are actual benefits. In your code it really does not matter much and we can change it to: struct Foo { std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo; // some other basic variables here }; class Bar { Foo foo; }; Foo is now defined in a different scope and it is no longer private to Bar. Otherwise it makes no difference for the present code. I am wondering that a single instance of Bar will contain only a single instance of Foo that is foo member variable? Yes. So a single instance/object of Bar will not be able to map multiple Foo inside the subFoo? subFoo is a map holding unique pointers to Foos. Bar::foo is not managed by a unique pointer, hence placing them in subFoo is not possible without running into a double free error. std::unique_ptr can be used with a custom deleter, but thats not the case here. Hence you cannot store a unique pointer to Bar::foo in any Foo::subFoo. You can however, store unique pointers to other Foos in Foo::subFoo.
70,113,095
70,214,141
How to cross-compile Qt6 on Linux for Windows?
I'm trying to cross-compile Qt 6.2.1. Target - Windows, my machine OS - Linux (Mint 20.2) (both 64bit). Unfortunately I can't compile it on Windows, so I have to do this cross-compilation. My configure cmd: ./../qt-everywhere-src-6.2.1/configure -prefix $PWD/. -platform linux-gcc-64 -xplatform win32-g++ -device-option CROSS_COMPILE=/usr/bin/x86_64-w64-mingw32- -opensource -opengl desktop -qt-host-path /home/papoj/Projects/host_qtbuild At the end of CMake work I'm getting this: CMake Warning: Manually-specified variables were not used by the project: QT_QMAKE_DEVICE_OPTIONS And then, after cmake --build . --parallel: FAILED: qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o /usr/bin/c++ -DHAVE_CONFIG_H -DQT_BOOTSTRAPPED -DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_TO_ASCII -DQT_NO_DEBUG -DQT_NO_FOREACH -DQT_USE_QSTRINGBUILDER -DQT_VERSION_MAJOR=6 -DQT_VERSION_MINOR=2 -DQT_VERSION_PATCH=1 -DQT_VERSION_STR=\"6.2.1\" -D_LARGEFILE64_SOURCE -D_LARGEFILE_SOURCE -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/Core_autogen/include -I/home/papoj/Projects/qtbuild/qtbase/include -I/home/papoj/Projects/qtbuild/qtbase/include/QtCore -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib -I/home/papoj/Projects/qtbuild/qtbase/src/corelib -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/global -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/kernel -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/tinycbor/src -I/home/papoj/Projects/qtbuild/qtbase/include/QtCore/6.2.1 -I/home/papoj/Projects/qtbuild/qtbase/include/QtCore/6.2.1/QtCore -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/double-conversion/double-conversion -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/double-conversion -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/forkfd -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/.rcc -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/mkspecs/win32-g++ -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/home/papoj/Projects/qtbuild/qtbase/src/xml/Xml_autogen/include -I/home/papoj/Projects/qtbuild/qtbase/include/QtXml -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/xml -I/home/papoj/Projects/qtbuild/qtbase/src/xml -I/home/papoj/Projects/qtbuild/qtbase/include/QtXml/6.2.1 -I/home/papoj/Projects/qtbuild/qtbase/include/QtXml/6.2.1/QtXml -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/tools/bootstrap/.. -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/tools/bootstrap/../../3rdparty/tinycbor/src -DNDEBUG -O2 -fPIC -fvisibility=hidden -fvisibility-inlines-hidden -Wall -Wextra -ffunction-sections -fdata-sections -mshstk -Wsuggest-override -std=gnu++17 -MD -MT qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o -MF qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o.d -o qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o -c /home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/global/qglobal.cpp In file included from /home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/global/qglobal.cpp:41: /home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/mkspecs/win32-g++/qplatformdefs.h:55:10: fatal error: tchar.h: No such file or directory 55 | #include <tchar.h> | ^~~~~~~~~ I have checked (this is also visible in log above) and CMake, for some reason, ignore my "CROSS_COMPILE" option and uses Linux c++ tool to compile instead of 'x86_64-w64-mingw32-g++', but I dont know how to fix that. Does anybody cross-compiled Qt6 for Windows on Linux manually? I cannot find any working solution on the Internet.
For those coming here from google with same problem. In Qt6 you need to specify Cmake toolchain for cross-compilation (I get something similar to toolchain shared here), as 'alone' device-option CROSS_COMPILE (as in cmd from my question) is depreciated/outdated (or smth like that). In my case I needed to use CMake toolchain and device-option CROSS-COMPILE as well, because in other way qmake was not able to find proper cross-platform compiler (in my case x86_64-w64-mingw32-g++-posix). To use compiler with "posix" at the end I needed to modify qtbase/mkspecs/win32-g++/qmake.conf. This is how it looks like after changes: # # qmake configuration for win32-g++ # # Written for MinGW-w64 / gcc 5.3 or higher # # Cross compile example for i686-w64-mingw32-g++: # configure -xplatform win32-g++ -device-option CROSS_COMPILE=i686-w64-mingw32- # include(../common/g++-win32.conf) include(../common/windows-desktop.conf) # modifications to g++-win32.conf QMAKE_CC = $${CROSS_COMPILE}gcc-posix QMAKE_CFLAGS += -fno-keep-inline-dllexport QMAKE_CFLAGS_WARN_ON += -Wextra QMAKE_CXX = $${CROSS_COMPILE}g++-posix QMAKE_CXXFLAGS += -fno-keep-inline-dllexport QMAKE_CXXFLAGS_WARN_ON = $$QMAKE_CFLAGS_WARN_ON QMAKE_CXXFLAGS_EXCEPTIONS_ON += -mthreads QMAKE_LINK = $${CROSS_COMPILE}g++-posix QMAKE_LINK_C = $${CROSS_COMPILE}gcc-posix QMAKE_CFLAGS_LTCG = -flto QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG QMAKE_LFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG QMAKE_LFLAGS_EXCEPTIONS_ON += -mthreads load(qt_config) Final ./configure cmd: ./../qt-everywhere-src-6.2.1/configure -prefix $HOME/Projects/testing_qt_builds/qtbuild_with_old_params -platform linux-g++ -xplatform win32-g++ -device-option CROSS_COMPILE=/usr/bin/x86_64-w64-mingw32- -opensource -opengl desktop -qt-host-path $HOME/Qt/6.2.1/gcc_64 -nomake tests -nomake examples -skip qtwebengine -- -DQT_BUILD_TOOLS_WHEN_CROSSCOMPILING=ON -DCMAKE_TOOLCHAIN_FILE=$HOME/Projects/toolchain.cmake After cmake --build and cmake --install I got host-qmake script in my build path $HOME/Projects/testing_qt_builds/qtbuild_with_old_params/bin/ Which I had to use to build my Qt project by passing .pro file to it. And then I just copied .exe file to Windows, provided all needed dlls and POOF, app works. :D My thread on qt forum with same problem where one of moderators helped me a lot to get final solution.
70,113,292
70,113,655
Why doesn't std::string have a constructor that directly takes std::string_view?
To allow std::string construction from std::string_viewthere is a template constructor template<class T> explicit basic_string(const T& t, const Allocator& alloc = Allocator()); which is enabled only if const T& is convertible to std::basic_string_view<CharT, Traits> (link). In the meantime there is a special deduction guide to deduce basic_string from basic_string_view (link). A comment to the guide says: Guides (2-3) are needed because the std::basic_string constructors for std::basic_string_views are made templates to avoid causing ambiguities in existing code, and those templates do not support class template argument deduction. So I'm curious, what is that ambiguity that requires to have that deduction guide and template constructor instead of simply a constructor that takes std::basic_string_view, e.g. something like explicit basic_string(basic_string_view<CharT, Traits> sv, const Allocator& alloc = Allocator()); Note that I'm not asking why the constructor is marked explicit.
The ambiguity is that std::string and std::string_view are both constructible from const char *. That makes things like std::string{}.assign("ABCDE", 0, 1) ambiguous if the first parameter can be either a string or a string_view. There are several defect reports trying to sort this out, starting here. https://cplusplus.github.io/LWG/lwg-defects.html#2758 The first thing was to make members taking string_view into templates, which lowers their priority in overload resolution. Apparently, that was a bit too effective, so other adjustments were added later.
70,113,466
70,113,582
How do I calculate the sum of all the array numbers after the first negative?
Can you help me with this problem? All I could do was count all the negative numbers. Here is my code: using namespace std; int main() { const int SIZE = 10; int arr[SIZE]{}; int number=0; srand(time(NULL)); cout << "Your array is: " << endl; for (int i=0; i<SIZE; i++) { int newValue = rand()%20-10; arr[i] = newValue; cout << arr[i] << " "; if (arr[i] < 0) { for (int j=-1; j<SIZE; j++) { number = arr[i]; sum += fabs(number); break; } } } cout << endl; cout << "Sum of elements after first element < 0 is: " << sum; cout << endl; }
One way is to have a flag that is zero to start with that is switched on after the first negative: int flag = 0; int sum = 0; for (std::size_t i = 0; i < SIZE; ++i){ sum += flag * arr[i]; flag |= arr[i] < 0; } This approach carries the advantage that you don't need an array at all: substituting the next number from standard input for arr[i] is sufficient.
70,113,566
70,113,657
runtime error: left shift of negative value -1
In fact I am trying this question: 5.4 in γ€ŠCracking the coding interview:189 programming questions and solutions,fifth edition》 the question is: Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. There is an exact same question, but the answers are all wrong. Moreover, the purpose of my question is to understand why the code cannot pass the ub checker, not just to get ideas for solving the problem. 0 What does "last executed input" mean on leetcode? Is it an example of the input that caused the error, and if so, why are there no warnings from the three compilers, even if I turn on all -Wall? 1 Why is the book wrong? Here is the code from the book: class Solution { public: int getNext(int n) { int c = n; int c0 = 0; int c1 = 0; while (((c & 1) == 0) && (c != 0)) { c0++; c >>= 1; } while ((c & 1) == 1) { c1++; c >>= 1; } if (c0 + c1 == 31 || c0 + c1 == 0) { return -1; } int p = c0 + c1; n |= (1 << p); n &= ~((1 << p) - 1); n |= (1 << (c1 - 1)) - 1; return n; } int getPrev(int n) { int temp = n; int c0 = 0; int c1 = 0; while ((temp & 1) == 1) { c1++; temp >>= 1; } if (temp == 0)return -1; while (((temp & 1) == 0 )&& (temp != 0)) { c0++; temp >>= 1; } int p = c0 + c1; n &= ((~0) << (p + 1)); int mask = (1 << (c1 + 1)) - 1; n |= mask << (c0 - 1); return n; } vector<int> findClosedNumbers(int num) { int m = getNext(num); int n = getPrev(num); return {m,n}; } }; The error output is Line 43: Char 14: runtime error: left shift of negative value -1 (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:53:14 I find this and it said "Left Shifting a negative value is Undefined Behavior" But why I used all the Wall flags I can think of at https://godbolt.org/, but I didn't get any prompts. Is there some flag to show this just like the UndefinedBehaviorSanitizer? 2. Someone's answer can't pass The link mentioned in this answer cannot pass lc, what's the problem with it? code: class Solution { public: vector<int> findClosedNumbers(int num) { int m = getNextLarger(num); int n = getNextSmaller(num); return { m,n }; } int getNextLarger(int num) { if (num == 0 || num == -1) return num; // (1) add 1 to the last set bit int largeNum = num + (num & ~(num - 1)); // (2) move the changed bits to the least significant bits. (right side) int flipBits = num & ~largeNum; int lastBits = 0; while (flipBits != 0) { flipBits &= flipBits - 1; lastBits <<= 1; lastBits |= 1; } lastBits >>= 1; // (2.1) move bits to maintain the same number of set bits. largeNum |= lastBits; return largeNum; } //Unhandled exception at 0x0033F4B9 in leetcode.exe: 0xC00000FD: Stack overflow int getNextSmaller(int num) { //with num=2 return ~getNextLarger(~num); } };
why the func can passed in msvc, clang, and gcc ,but just cannot pass the UndefinedBehaviorSanitizer? Because the compiler didn't know at compile time, what value the operand would be at runtime. If compilers were able to detect all UB at compile time, then UB sanitisers wouldn't exist since they would be unnecessary.
70,113,831
70,114,739
How to put projects in one folder in a Visual Studio solution
I did some problem-solving in C++, and the current file structure looks like this. solution_folder/ β”œβ”€β”€ question_1/ β”‚ β”œβ”€β”€ Main.cpp β”‚ β”œβ”€β”€ question_1.vcxproj β”‚ └── question_1.vcxproj.filters β”œβ”€β”€ question_2/... β”œβ”€β”€ (more project folders) └── solution.sln I want to put all projects in one folder and still be able to open the solution in Visual Studio just as I used to before. I don't want to scroll through hundreds of folders to get to the readme section when I upload the solution on GitHub. solution_folder/ β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ question_1/ β”‚ β”‚ β”œβ”€β”€ Main.cpp β”‚ β”‚ β”œβ”€β”€ question_1.vcxproj β”‚ β”‚ └── question_1.vcxproj.filters β”‚ β”œβ”€β”€ question_2/... β”‚ └── (more project folders) └── solution.sln Is this possible? Should I not create a project for each question?
As @drescherjm and @heapunderrun commented, Put all project folders in one folder in File Explorer, Remove all projects from the solution in Solution Explorer, Right-click on the solution and Add β†’ Existing Project all projects. Update: Shortcuts Remove: Delete Add existing project: Alt F D E
70,114,043
70,128,838
Add ros cmake to an already existing cmake
I have a really big code with this cmake that works: cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project(MYPROJECT) set (CMAKE_CXX_STANDARD 11) find_package(PCL 1.7 REQUIRED) if(DEFINED PCL_LIBRARIES) list(REMOVE_ITEM PCL_LIBRARIES "vtkproj4") endif() FIND_PACKAGE(Boost COMPONENTS program_options REQUIRED) include_directories(${PCL_INCLUDE_DIRS}) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) link_directories(${PCL_LIBRARY_DIRS}) add_definitions(${PCL_DEFINITIONS}) add_executable (main src/main.cpp) target_link_libraries (main ${PCL_LIBRARIES}) Now, I want to publish the results of this code to a ros topic. So I added this code to a ros workspace, and need to add ros stuff into the cmake. I changed the project name to the pkg name, and added to the cmake the find_package, include_directories and catkin_package, ending with this CMake: cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project(plc) set (CMAKE_CXX_STANDARD 11) find_package(PCL 1.7 REQUIRED) if(DEFINED PCL_LIBRARIES) list(REMOVE_ITEM PCL_LIBRARIES "vtkproj4") endif() find_package(catkin REQUIRED COMPONENTS pcl_conversions pcl_ros roscpp ) FIND_PACKAGE(Boost COMPONENTS program_options REQUIRED) include_directories(${catkin_INCLUDE_DIRS}) include_directories(${PCL_INCLUDE_DIRS}) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) link_directories(${PCL_LIBRARY_DIRS}) add_definitions(${PCL_DEFINITIONS}) catkin_package(CATKIN_DEPENDS roscpp pcl_ros pcl_conversions) add_executable (main src/main.cpp) target_link_libraries (main ${PCL_LIBRARIES}) also added this to the package.xml: <build_depend>pcl_conversions</build_depend> <build_depend>pcl_ros</build_depend> <build_depend>roscpp</build_depend> <build_export_depend>pcl_conversions</build_export_depend> <build_export_depend>pcl_ros</build_export_depend> <build_export_depend>roscpp</build_export_depend> <exec_depend>pcl_conversions</exec_depend> <exec_depend>pcl_ros</exec_depend> <exec_depend>roscpp</exec_depend> But I keep getting this errors, that according to google means that I made the CMake wrong. usr/bin/ld: main.cpp:(.text+0x6bdc): undefined reference to `ros::Rate::Rate(double)' /usr/bin/ld: main.cpp:(.text+0x6beb): undefined reference to `ros::NodeHandle::ok() const' /usr/bin/ld: main.cpp:(.text+0x6c07): undefined reference to `ros::Time::now()' /usr/bin/ld: main.cpp:(.text+0x6c3e): undefined reference to `ros::spinOnce()' /usr/bin/ld: main.cpp:(.text+0x6c4d): undefined reference to `ros::Rate::sleep()' /usr/bin/ld: main.cpp:(.text+0x6c5e): undefined reference to `ros::Publisher::~Publisher()' /usr/bin/ld: main.cpp:(.text+0x6c6d): undefined reference to `ros::NodeHandle::~NodeHandle()' /usr/bin/ld: main.cpp:(.text+0x6cfc): undefined reference to `ros::Publisher::~Publisher()' /usr/bin/ld: main.cpp:(.text+0x6d0b): undefined reference to `ros::NodeHandle::~NodeHandle()' Any idea how can I fix this? I'm clueless. PS: I have another workspace with python ros that publishes/subscribes without problems, and this code was working perfectly before I added the ros part in cpp.
Make sure you also link agains the catkin specified libraries (${catkin_LIBRARIES}), because there the ROS libs are listed in: target_link_libraries (main ${PCL_LIBRARIES}) ${catkin_LIBRARIES} )
70,114,257
70,115,148
Customizable way to instantiate objects in 1 expression in C++
In Rust, there is this crate which utilize Rust procedural macro to automatically implement builder pattern for any arbitrary struct defined. As there is no flexible way to instantiate Rust struct with some default and some provided values, this helps a lot in reducing boilerplate. Is there any similar thing to generate builders automatically in C++, as instantiating objects in C++ also requires a lot of boilerplate (a lot of overloaded constructors to cover all posible combinations of fields or multiple steps initialization), possibly using C/C++ macros? As the comments suggested, I added an example to clarify my idea. I want to instantiate class A below by just provide some field I want and leave others as default. If so, I either have to implement a lot of constructors or do multiple steps, instantiate and then override fields I want: Multiple constructors #include <string> #include <iostream> class A { public: int a = 2; std::string b = "b"; int c = 5; std::string d = "d"; A() {} A(int a) { this->a = a; } A(std::string b) { this->b = b; } A(int a, std::string b) { this->a = a; this->b = b; } // ... more constructors to cover all combinations // this might not even work as some combinations might // have similar types, which prevent overloading them }; Multiple steps A a; a.b = "hello"; a.c = 10; Multiple steps instantiation is actually nice. However, it does not work if I want to have customized instantiation in 1 expression. With builder pattern, I do that in 1 expression by chaining methods like this: BuilderOfA() .a(7) .c(8) .build(); Can the definition of this builder be automatically generated at compile time in C++? If not, is there anyway I can instantiate an object in a customizable way (by just provide some field I want and leave others as default) without using multiple expressions?
In c++ 20 you can do this: struct S { std::string str = "Hello"; float y = 1.0f; int x = 10; }; auto a = S{ .str = "Hi", .x = 8 };
70,114,706
70,115,679
How to get the base class offset of an inherited struct without creating an instance
Consider this code: struct A { int64 member; int32 member2; virtual void f(); }; struct B { int16 member3; virtual void b(); }; struct C : A, B { virtual void b() override; }; I'm interested in finding the offset of B in C. Previously with other structs with no virtual inheritance and only one base class offsetof of the first member seemed to work. I have decompiled some code (in IDA) and the base classes are nicely highlighted (hex) here: In a function those exact baseclass offsets are used to cast void*'s to derived classes by adding the offset to the void* (by casting to a char*). The structs A, B and C are similar to the one in the compiled code, which include classes with virtual functions and multiple base classes. My question is how did they do that, and how can I do that? I've tried something like i32 offset = (i64)((B*)((C*)NULL)); but no luck.
I tried the following, and it worked: (char*)(B*)(C*)0x100 - (char*)(C*)0x100 It casts C* to B*; this is supposed to do the work. All the rest is support. I used an arbitrary number 0x100; it seems to work with all numbers except 0. Why it doesn't work for 0: it sees a null-pointer of type C*; to convert it to a null-pointer of type B*, it should still be null. A special case. Of course, this uses undefined behavior. It seems to work in Visual Studio in my short test program; no guarantee it will work anywhere else.
70,114,894
70,115,949
What is the c++ approach for upgrading these c style casts for HtmlHelp API?
What is the c++ approach for upgrading these c style casts for HtmlHelp API? void CMeetingScheduleAssistantApp::DisplayHelpTopic(CString strTopic) { CString strURL = _T("https://help-msa.publictalksoftware.co.uk/") + strTopic; if (theApp.UseDownloadedHelpDocumentation()) { // CHM files use 3 letter suffix strTopic.Replace(_T(".html"), _T(".htm")); HtmlHelp((DWORD_PTR)(LPCTSTR)strTopic, HH_DISPLAY_TOPIC); } else ShellExecute(nullptr, nullptr, strURL, nullptr, nullptr, SW_SHOWDEFAULT); } Specifically: HtmlHelp((DWORD_PTR)(LPCTSTR)strTopic, HH_DISPLAY_TOPIC); In answer to the question in the comments: It is odd because the official docs for x86 HtmlHelpA / HtmlHelpW do indicate different calls. It doesn't seem to be listed as part of the CWinApp class in the docs.
reinterpret_cast will always trigger a code analysys warning In that case, you could invent your own pointer cast function. A smart compiler will most probably optimize this away: #include <cstring> template<class D, class T> D ptr_cast(T* x) { D rv; static_assert(sizeof rv == sizeof x); std::memcpy(&rv, &x, sizeof rv); return rv; } Then HtmlHelp( ptr_cast<DWORD_PTR>(strTopic.GetString()), HH_DISPLAY_TOPIC); In g++ and clang++, explicitly instantiating the function template DWORD_PTR ptr_cast<DWORD_PTR,char>(char*); makes it into the assembly code unsigned long ptr_cast<unsigned long, char>(char*): mov rax, rdi ret When inlined and optimized (as it will be in your code) the function call is gone and only the mov (assignment) to the destination DWORD_PTR is left, which is exactly the trace a reinterpret_cast would leave. In MSVC, inlining it results in the similar: lea rdx, OFFSET FLAT:`string'
70,114,988
70,119,548
SDL 2.0 BMP Blit screen / Update won't show picture
I ran into an issue with getting my picture to display. I couldn't get the picture to show up in the window. I accidentally ran the program twice (two windows) and the second window had the image in it. I can close the first and the image holds in the second window. It looks sketchy if I moved the window around. Said all that to ask, why would my picture only show in a 2nd(3rd 4th) window and not the original. Here is the code. #include <iostream> #include <SDL.h> int main(int argc, char ** argv) { bool quit = false; SDL_Event event; SDL_Init(SDL_INIT_VIDEO); SDL_Window * gWindow = SDL_CreateWindow("SDL_Yo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,480,SDL_WINDOW_SHOWN ); SDL_Surface* gScreenSurface = SDL_GetWindowSurface( gWindow ); if( gScreenSurface == NULL ) { SDL_Quit(); } SDL_Surface* gHelloWorld = SDL_LoadBMP("IMG_0004.bmp"); if( gHelloWorld == NULL ) { SDL_Quit(); } SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL ); quit = SDL_UpdateWindowSurface( gWindow ); while (!quit) { SDL_WaitEvent(&event); switch (event.type) { case SDL_QUIT: quit = true; break; } } SDL_Quit(); return 0; }
You can't just throw something to be drawn once and expect it to stay on screen. What you've described in question is exactly how window manager operates - if some part of your window is not shown, there is no need to update it. But once it is visible again, window manager sends you a message that you need to redraw, as there is no image data held anywhere and display system have nothing to display. You didn't redraw, so some garbage (stuff that was there before) is being displayed. As to why you didn't see image initially even though nothing was overshadowing your window - is because you've displayed your image too early. Same deal, SDL gives you an event when you need to draw. Adequate event looop shoold be something like this: while (!quit) { // get all events from event queue while(SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; } } // all your display 'redraw' stuff here SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL ); SDL_UpdateWindowSurface( gWindow ); } If you really want SDL_WaitEvent instead, you should watch for SDL_WINDOWEVENT with SDL_WINDOWEVENT_EXPOSED and SDL_WINDOWEVENT_SHOWN flags as your signal to redraw.
70,115,209
70,115,308
Reversing number in c++ with arrays
I am trying to find the reverse of the number entered by the user : This is my main.cpp code int number=0; cout<< " enter a number"; cin>>number; reverse( number); this is my function .cpp code int reverse( int number){ int last=0; int i=0; int array1[10]={0} ; int check=number; while ( check!=0){ last=check%10; array1[i]=last; i++; check=number/10; } for (int j = 0; j <= i; ++j) { cout<<array1[j]; } return 0; } It only asks me to enter a number then does not give any output. what should I correct?
check=number/10 will be check=check/10 and j<=i will be j<i
70,115,227
70,116,558
C++ Reference - SomeType* &val vs. SomeType* val
I'm solving LeetCode 783. Minimum Distance Between BST Nodes and I've noticed that the difference between a correct solution and an incorrect solution is a reference (&) at my function call, as follows: Correct Solution: class Solution { public: void traverse(TreeNode* root, TreeNode* &curr, int &sol){ if (root == nullptr) return; traverse(root->left, curr, sol); if(curr) sol = min(sol, abs(root->val - curr->val)); curr = root; traverse(root->right, curr, sol); } int minDiffInBST(TreeNode* root) { int sol = INT_MAX; TreeNode* curr = nullptr; traverse(root, curr, sol); return sol; } }; Incorrect Solution: class Solution { public: void traverse(TreeNode* root, TreeNode* curr, int &sol){ //Exactly the same as above! }; As a student, this is the first time I have encountered this case related to Pointers and References. I'll appreciate any explanation of this difference.
If you do this void foo(int * inner_ptr) { ptr++; } int main() { int arr[5] = {1, 2, 3, 4, 5}; int outer_ptr = &arr[1]; foo(outer_ptr); } the outer_ptr will still be equal to &arr[1]. You only changed the inner_ptr, the copy of the outer_ptr. You can change the thing it points to. void foo(int * inner_ptr) { (*ptr) = 42; } But not the outer_ptr itself Therefore you need either this signature: (with reference) void foo(int * & inner_ptr); or this signature: (pointer to pointer) (in this case you would work with it differently in the function body tho) void foo(int * * inner_ptr);
70,115,272
70,115,431
Is it possible that `shared_ptr::use_count() == 0` and `shared_ptr::get() != nullptr`?
From the cppref: Notes An empty shared_ptr (where use_count() == 0) may store a non-null pointer accessible by get(), e.g. if it were created using the aliasing constructor. Is it possible that shared_ptr::use_count() == 0 and shared_ptr::get() != nullptr? Any example to illustrate that is true?
As stated in the notes, the aliasing constructor causes this to happen. For example: #include <memory> #include <iostream> int main() { std::shared_ptr<int> a = nullptr; std::shared_ptr<float> b(a, new float(0.0)); std::cout << b.use_count() << "\n"; std::cout << (b.get() == nullptr) << "\n"; } prints 0 for the use_count() and b.get() is non-null. Note that the float isn't managed by the lifetime of b and is leaked.
70,115,492
70,118,394
Implement a type trait for a class template that is true for the actual class template and classes that inherit it
I have a tuple-like class template like this template <class... T> struct Foo {} Now I need to implement something like this template <class T> void bar (const T& t) { if constexpr (IsFoo<T>::value) // treat it as Foo else // a generic solution } IsFoo can be implemented straightforward like this template <class T> struct IsFoo : std::false_type {} template <class... T> struct IsFoo<Foo<T...>> : std::true_type {} Now, I also need IsFoo to be true in case the type passed is publicly derived from any instantiation of Foo, e.g. struct Derived : public Foo<int, float> {} should also be treated like a Foo in the first if constexpr branch above. However, I can't figure out how to properly implement a template specialisation of my IsFoo trait that would work when Derived is passed to it. But I'm sure Stackoverflow knows how to! Edit: I found out that although all compilers used for the project support concepts, although there is no full C++ 20 support. So I decided to enable that in order to use the concepts-based solutions proposed.
C++20 concepts make things much easier: template <class... Ts> struct Foo {}; template<class T> concept IsFoo = requires(T& t){ []<class... Ts>(Foo<Ts...>&){}(t); }; Demo.
70,115,892
70,116,429
Arrays (driver’s exam scorer)
I am working on this assignment and I am pretty new to c++, we are working with arrays, and I am having trouble reading inputs from a file. What I need to do is create a program that will read inputs from a file which is a driver's exam score, and the program should tell if the person pass or fail, how many answers were right and wrong, and which ones were the wrong answers, this is what I have so far. My compiler tells me there is no erros but when I run it, it just ask for the file, but nothing prints if i enter a file that doens't exists it will report it and quit, but when I put the right one it just do nothing, i tried using (&) to pass variables but it gives me erros, also my teacher wants me to pass information using arguments if you can spot any other problems please let me know i will apreciated the help. #include <iostream> #include <fstream> using namespace std; void check(char[], char[], int, int); int main() { // number of questions const int questions = 20; // the user need 15 right answers to pass const int correct = 15; // this is the order of the right answers char answer[questions] = { 'B','D','A','A','C', 'A','B','A','C','D', 'B','C','D','A','D', 'C','C','B','D','A' }; // this is to store the answer in a file into this variable char user_input[questions]; // I need to ask for the name of the file. ifstream file; string file_name; cout << "Enter the file name: "; cin >> file_name; file.open(file_name); // if file name doesn's exist if (!file) { cout << "The file is not open!!" << endl; // here i am trying to get input from the file while(file >> user_input) { check(answer, user_input, questions, correct); } } return 0; } void check(char answer[], char user_input[], int questions, int correct) { int counter = 0; for(int i = 0; i < questions; i++) { if(answer[i] == user_input[i]); counter++; } cout << endl; cout << "Pass/Fail " << "#correct " << "#incorrect " << "wrong answers" << endl; cout << "----------------------------------------------------------------" << endl; if (counter >= correct) { cout << "pass" << endl; }else{cout << "fail" << endl;} } this is how the file looks like. B B A A C B B A D C B C D A D C C B B C B D A A C A B A C D B C D A D C C B D A B B A A C C B A C D B C D A C C C B D A A B A A C A A A C C B C D A C C C B D A A B C D A B C D A B C D A B C D A B C D B D A A C A A A C D B C D A D C C B D A B D A A C A B A D C B C D A D C C B D A here is more information about my assignment https://kuvapcsitrd01.kutztown.edu/~carelli/website/courses/csc135/Assignments/p6-arrays.pdf
See where you actually read the file. You even commented the place. And then go up the scope and see where you actually do it. You commented that too. I think you made a typo.
70,116,856
70,118,402
Swap nodes (with pointers) on doubly circular linked list
I am trying to write a doubly circular linked list, but I got somewhat stuck in swapping nodes. It's working fine for any node except the head node. I tried adding a check if node1 is the head without a luck. Where am I doing wrong ? Well, I stated earlier but for any other node except head the swap is working just fine, I'm sure this is the key to the problem here, but I cannot see it so far. Appreciate any help. updateNode(*node) simply rearrange prev->next and next->prev accordingly. Update: Currently if node1 is the head node, it swaps node2 with head->next. 1 2 3 4 5 6 becomes 1 6 2 3 4 5. template<class T> void LinkedList<T>::updateNode(Node<T> *node) { node->prev->next = node; node->next->prev = node; } template<class T> void LinkedList<T>::swap(Node<T> *node1, Node<T> *node2) { if (!contains(node1) or !contains(node2)) return; if (node1 == node2) return; else if (node2->next == node1 && node1->prev == node2) { Node<T> *temp = node1; node1 = node2; node2 = temp; } Node<T> *n1_prev = node1->prev; Node<T> *n2_prev = node2->prev; Node<T> *n1_next = node1->next; Node<T> *n2_next = node2->next; if (node1 == head && node2 == head->prev) { head->prev = node1; head = node2; head->next = n1_next; head->prev->prev = n2_prev; } else if (( node1->next == node2 && node2->prev == node1 ) || ( node1->prev == node2 && node2->next == node1 )) { node1->prev = n1_next; node2->prev = n1_prev; node1->next = n2_next; node2->next = n2_prev; } else { node1->prev = n2_prev; node2->prev = n1_prev; node1->next = n2_next; node2->next = n1_next; } updateNode(node1); updateNode(node2); }
Some of the problems include: With head->prev = node1 the node reference node1 is made to refer to itself, as at that moment head and node1 reference the same node. head should be changed also in other cases: it should change when it is equal to either node1 or node2 without any other condition. And then it should just reference the other of the two. The swap logic should not be any different when one of the nodes is the head node. The rewiring for the swap should be exactly the same. It is just (like mentioned above) that if one of them is the head, the head reference should be updated to refer to the other node of the two. In case the list consists only of two nodes (the ones to be swapped) then nothing needs to be rewired. Only the head reference should change. Some conditions could be simplified, as we may assume that the list is consistent. So when node2->next == node1 we may silently assume that node1->prev == node2, ...etc. So here is an update of your code: template<class T> void LinkedList<T>::swap(Node<T> *node1, Node<T> *node2) { if (!contains(node1) or !contains(node2)) return; if (node1 == node2) return; if (node2->next == node1) { Node<T> *temp = node1; node1 = node2; node2 = temp; } if (node2->next != node1) { // More than 2 nodes in the list Node<T> *n1_prev = node1->prev; Node<T> *n2_next = node2->next; if (node1->next == node2) { node1->prev = node1->next; node2->next = node2->prev; } else { node1->prev = node2->prev; node2->next = node1->next; } node2->prev = n1_prev; node1->next = n2_next; updateNode(node1); updateNode(node2); } // If head was swapped, it should reference the other one now if (head == node1) head = node2; else if (head == node2) head = node1; }
70,117,470
70,117,566
How do I get an error from `pop_back()` if `size()` is 0?
I was explaining to a coworker why we have small test with sanitizers on them. He asked about popping a vector too many times and if it was an exception, assert, UB and which sanitizer catches it It appears NONE catches them. Address and memory will if you call back() after popping too many times but if you pop and do size() you get a large invalid value due to wrapping Is there a way I can get an assert or exception or runtime termination when I pop too many times? I really thought a debug build without sanitizers would have caught that (with an assert or exception) I use clang sanitizer but build options with gcc will also be helpful
Both libstdc++ and libc++ have a "debug mode" with assertions, that can be enabled using: -D_GLIBCXX_DEBUG for libstdc++ -D_LIBCPP_DEBUG for libc++ Also -fsanitize=undefined appears to catch it, but the error message is much more cryptic.