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,411,048
70,411,599
Memory allocate in c++
I have a project in which I have to allocate 1024 bytes when my program starts. In C++ program. void* available = new char*[1024]; I write this and I think it is okay. Now my problem starts, I should make a function that receives size_t size (number of bytes) which I should allocate. My allocate should return a void* pointer to the first bytes of this available memory. So my question is how to allocate void* pointer with size and to get memory from my available. I'm a student and I'm not a professional in C++. Also sorry for my bad explanation.
It looks like you're trying to make a memory pool. Even though that's a big topic let's check what's the minimal effort you can pour to create something like this. There are some basic elements to a pool that one needs to grasp. Firstly the memory itself, i.e. where do you draw memory from. In your case you already decided that you're going to dynamically allocate a fixed amount of memory. To do it properly the the code should be: char *poolMemory = new char[1024]; I didn't choose void* pool here because delete[] pool is undefined when pool is a void pointer. You could go with malloc/free but I'll keep it C++. Secondly I didn't allocate an array of pointers as your code shows because that allocates 1024 * sizeof(char*) bytes of memory. A second consideration is how to give back the memory you acquired for your pool. In your case you want to remember to delete it so best you put it in a class to do the RAII for you: class Pool { char *_memory; void *_pool; size_t _size; public: Pool(size_t poolSize = 1024) : _memory(new char[poolSize]) , _pool(_memory) , _size(poolSize) { } ~Pool() { delete[] _memory; } // Forgetting this will leak memory. }; Now we come to the part you're asking about. You want to use memory inside that pool. Make a method in the Pool class called allocate that will give back n number of bytes. This method should know how many bytes are left in the pool (member _size) and essentially performs pointer arithmetic to let you know which location is free. There is catch unfortunately. You must provide the required alignment that the resulting memory should have. This is another big topic that judging from the question I don't think you intent to handle (so I'm defaulting alignment to 2^0=1 bytes). #include <memory> void* Pool::allocate(size_t nBytes, size_t alignment = 1) { if (std::align(alignment, nBytes, _pool, _size)) { void *result = _pool; // Bookkeeping _pool = (char*)_pool + nBytes; // Advance the pointer to available memory. _size -= nBytes; // Update the available space. return result; } return nullptr; } I did this pointer arithmetic using std::align but I guess you could do it by hand. In a real world scenario you'd also want a deallocate function, that "opens up" spots inside the pool after they have been used. You'd also want some strategy for when the pool has run out of memory, a fallback allocation. Additionally the initially memory acquisition can be more efficient e.g. by using static memory where appropriate. There are many flavors and aspects to this, I hope the initial link I included gives you some motivation to research a bit on the topic.
70,411,072
70,411,282
How to make a loop to determine if 2 numbers belong in a given range
I am having problems making a loop which stops when both x and y are in the range/interval [0,1] in c++. double x; double y; while(condition) { if(x < 0) { x = -x; } else { x = 2 - x; } if(y < 0) { y = -y; } else { y = 2 - y; } } This method with 2 loops works: while((x < 0) || (x > 1)) {do sth} while((y < 0) || (y > 1)) {do sth} This doesn't work: while(!((x >= 0) && (x <= 1)) && !((y >= 0) && (y <= 1))) {do sth} And this doesn't work either: while(((x < 0) || (x > 1)) && ((y < 0) || (y > 1))) {do sth} This makes an infinite loop (in my case): while(((x < 0) || (x > 1)) || ((y < 0) || (y > 1))) {do sth} Note: {do sth} changes x and y if needed so they will eventually go in that interval (same as in the first block of code). Note 2: By doesn't work I mean it never goes in the loop when x is in the interval and y < 0 (and some other cases).
while ( !( (x>=0 && x<=1) && (y>=0 && y<=1) ) ) should be the combined conditional check.
70,411,268
70,411,403
Should we NULL every raw pointer after it is used?
int *a; if (true) *a = 2; else *a = 3; As you see, a is not a dynamically allocated pointer. Should I assign it to nullptr before exiting? Does unique_ptr do for me automatically? What about the memory pointer to by a? If I null a before it goes out of scope, will it cause a memory leak?
int *a; if (true) *a = 2; The behaviour of this program is undefined. a does not have a valid pointer value, so you may not indirect through. Should we NULL every raw pointer after it is used? It depends. For example, if the lifetime of the pointer is about to end, then it's redundant to assign it to null. Does unique_ptr do for me automatically? unique_ptr isn't a raw pointer. But no, unique_ptr cannot know whether you've stopped using it or not, so it cannot set itself to null when you've stopped using it. If I null a before it goes out of scope, will it cause a memory leak? There is no difference between setting a pointer null, and not setting it to null before the pointer goes out of scope.
70,411,286
70,419,938
SVM allocation in OpenCL C++
In the case of cl_context and cl::Context, we can do: cl::Context context_ = cl::Context(device); cl_context context = context_(); Now, I have an OpenCL program, with the following snippet in it: ... void* svm_data = clSVMAlloc(context, svm_flags, svm_buffer_size, 0); ... I would like to do something similar here to what we did with cl::Context above (i.e. extract the underlying variable from the header, or in this case, the underlying void pointer): cl::SVMAllocator svm_data_ = cl::SVMAllocator<int, cl::SVMTraitAtomic<>>(context); void* svm_data = svm_data_(); However, after looking through the docs, I have been unsuccessful in finding a method. Anyone got some ideas?
Looks like you need to allocate the shared virtual memory using the allocator to get the pointer to it: cl::SVMAllocator<int, cl::SVMTraitAtomic<>> svm_allocator(context); std::size_t num_elements = 4; int* svm_data = svm_allocator.allocate(num_elements); The SVM allocator holds only the context and the flags that are passed to clSVMAlloc() and if you want to allocate the shared virtual memory, you need to call allocate() method directly. Also, if you want to deallocate the allocated memory, you need to use the allocator as well: svm_allocator.deallocate(svm_data, num_elements);
70,411,314
70,411,808
Is it possible to initialize the template inner class in the C++20 requires clause?
Consider the following class A that defines a template inner class B: struct A { template<class = int> struct B { }; }; We can use the following expression to initialize inner B, where typename is optional: (Godbolt) int main() { A::template B<>(); typename A::template B<>(); } I want to use concept to detect whether a type has a template inner class B: template<class T> concept C = requires { typename T::template B<>(); }; static_assert(C<A>); But only Clang accepted the above code, GCC and MSVC rejected it due to syntax error (Godbolt): <source>:8:27: error: expected ';' before '(' token 8 | typename T::template B<>(); | ^ | ; And if I remove the typename in the require clause: template<class T> concept C = requires { T::template B<>(); }; MSVC accepted it, but Clang and GCC will produce static assertion failed since they think the expression is not well-formed (Godbolt): <source>:11:15: note: because 'A' does not satisfy 'C' static_assert(C<A>); ^ <source>:8:15: note: because 'T::template B<>()' would be invalid: 'A::B' instantiated to a class template, not a function template T::template B<>(); ^ Which compiler should I trust?
My understanding of concepts is, that if you want to check such cases, you have to use the compound statement. struct A { template<class = int> struct B { }; }; template<class T> concept C = requires { { typename T::template B<>() }; }; static_assert(C<A>); I believe you can't use it within a simple requirement clause, because T::template B<> is a dependent name and needs the keyword typename in front because the concept itself is a template and you are sitting in a unevaluated context. If you are using the keyword typename in front, it is not longer a simple requirement but becomes a type requirement. But this one checks for the existence of the type and is not intended to build a expression to instantiate the type. As this you end up in a compound expression where you are able to get the type with keyword typename in the dependent template and do the default initialization of that type. As alternative, shown as C2, you can pick your type upfront in the concept template parameter list which enables you to use the found type without the keyword typename in the simple requires clause. I also added test cases to see the concept failing by "killing" the default constructor of your inner type B. struct A { template<class = int> struct B { }; }; struct A2 { template<class = int> struct B { B()=delete; }; }; template<class T> concept C = requires { { typename T::template B<>() }; }; template<class T, typename Inner = typename T::template B<> > concept C2 = requires { Inner(); }; static_assert(C<A>); static_assert(C<A2>); // fails as expected static_assert(C2<A>); static_assert(C2<A2>); // fails as expected The above code works for all your three given compilers: explore
70,411,448
70,411,524
Cpp predefined structs?
Last time I used C++ was when I attended university, therefor I am not very fluent in it. I wanted to create a small game, and because I am used to C# I wanted to create predefinded struct objects. Here is the C# code for reference: public struct Vector2 : IEquatable<Vector2> { private static readonly Vector2 _zeroVector = new Vector2(0.0f, 0.0f); private static readonly Vector2 _unitVector = new Vector2(1f, 1f); private static readonly Vector2 _unitXVector = new Vector2(1f, 0.0f); private static readonly Vector2 _unitYVector = new Vector2(0.0f, 1f); [DataMember] public float X; [DataMember] public float Y; public static Vector2 Zero => Vector2._zeroVector; public static Vector2 One => Vector2._unitVector; public static Vector2 UnitX => Vector2._unitXVector; public static Vector2 UnitY => Vector2._unitYVector; public Vector2(float x, float y) { this.X = x; this.Y = y; } } In C# I could now use this code to get a Vector with x = 0 and y = 0 var postion = Vector2.Zero; Is there a way to create something like this in C++ or do I have to life with the basicness of c++ and use a struct like this? struct Vector2 { float x, y; Vector2(float x, float y) { this->x = x; this->y = y; } };
First off, with recent versions of C++, you can simplify your struct definition like this: struct Vector2 { float x{}, y{}; }; This guarantees that x and y are initialized with 0, you don't need the separate constructor as you show it. You can then use the struct like this: Vector2 myVec; // .x and .y are set to 0 myVec.x = 1; myVec.y = 2; You can even use what's called an "initializer list" to create a struct with predefined values for x and y instead of the default 0, like this: Vector2 myVec2{1,2}; Regarding your need for "global" instances of your Vector2 struct, you can make use of the static keyword in C++ similarly as in C#: struct Vector2 { float x{}, y{}; static const Vector2 Zero; static const Vector2 Unit; static const Vector2 UnitX; static const Vector2 UnitY; }; In contrast to C++, you cannot specify the value of constant(s) directly in the class though (if you try you get an incomplete type error, since at the time when the compiler encounters the constant, the class definition is not complete yet); you need to "define" the constant(s) somewhere outside your class: const Vector2 Vector2::Zero{}; const Vector2 Vector2::Unit{1.0f, 1.0f}; const Vector2 Vector2::UnitX{1.0f, 0.0f}; const Vector2 Vector2::UnitY{0.0f, 1.0f}; While the above struct Vector2 ... typically goes somewhere in a .h file to be included by multiple other files, the definition should go into a .cpp file, and not in the header, otherwise you will get multiply defined symbol errors.
70,411,495
70,581,660
using unique_ptr with custom deleter for GError
using unique_ptr with custom deleter for c functions that return a ptr is pretty straight forward, but how would i use it for functions that take ptr of ptr as parameter (like GError) I have faced this in couple of cases but but did not find a straightforward way to do this. am i missing something? using Element = std::unique_ptr<GstElement, void (*)(GstElement*)>; using Error = std::unique_ptr<GError, void (*)(GError*)>; ... GError* plain_err; Element pipeline(gst_parse_launch(str, &plain_err), object_unref); // ok Error uniq_err {nullptr, error_free}; Element pipeline(gst_parse_launch(str, &(uniq_err.get())), object_unref); // error: lvalue required as unary ‘&’ operand The only way I could think of is by assigning it later GError* plain_err; Element pipeline(gst_parse_launch(str, &plain_err), object_unref); Error uniq_err {plain_err, error_free}; plain_error = nullptr;
I found returning a tuple from a lambda to be marginally better, auto [pipeline, err] = [&]() noexcept { GError* err = nullptr; auto* pipeline = gst_parse_launch(str, &err); return std::tuple{Element{pipeline, object_unref}, Error{err, error_free}}; }();
70,411,580
70,411,690
How to check whether a string input from the user contains a number or not?
The title says it all. I'm looking to check if a string contains even a single digit somewhere. No idea how to do this. If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean). Thanks!
If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean). You could just use a simple for-loop and check if any of the characters present in the string are digits and return true if any is found, otherwise false: #include <string> #include <cctype> // ... bool contains_number(std::string const& s) { for (std::string::size_type i = 0; i < s.size(); i++) if (std::isdigit(s[i])) return true; return false; } Or if you're fine with using std::string::find_first_of(). bool contains_number(std::string const& s) { return s.find_first_of("0123456789") != std::string::npos; }
70,412,334
70,412,456
How to filter inherited objects?
I have class Set which consists of dynamically allocated IShape where IShape is inherited by Square, Rectangle etc. and I need to make filter function to create new set of only certain type (E.g. Squares). Basically to go through existing set and pick only shape which is defined somehow (through parameters?) and create new set of that shape. How could this be done?
To avoid using dynamic_cast, have your IShape class declare a pure virtual function called (say) GetTypeOfShape. Then override that in each of your derived classes to return the type of shape that each represents (as an enum, say). Then you can test that in your filter function and proceed accordingly. Example code: #include <iostream> class IShape { public: enum class TypeOfShape { Square, Rectangle /* ... */ }; public: virtual TypeOfShape GetTypeOfShape () = 0; }; class Square : public IShape { public: TypeOfShape GetTypeOfShape () override { return TypeOfShape::Square; } }; class Rectangle : public IShape { public: TypeOfShape GetTypeOfShape () override { return TypeOfShape::Rectangle; } }; // ... int main () { Square s; Rectangle r; std::cout << "Type of s is: " << (int) s.GetTypeOfShape () << "\n"; std::cout << "Type of r is: " << (int) r.GetTypeOfShape () << "\n"; } Output: Type of s is: 0 Type of r is: 1 Live demo
70,412,425
70,412,460
Overriding method shadows overloaded final version
I have the following code: struct Abs { virtual void f(int x) = 0; virtual void f(double x) final { std::cout << 2; } }; struct Sub: public Abs { void f(int x) final { std::cout << 1; } }; Abs is an abstract class which comprises a pure member function void f(int) and its overloaded version void f(double x), which is no longer pure and final. If I try to override void f(int) in the derived struct Sub, it shadows void f(double) and the following main function prints 1, converting 1.01 to int: int main() { Sub x = {}; x.f(1.01); return 0; } How do I overcome this problem? Also, why does it work like that?
Given x.f(1.01);, the name f is found in the scope of class Sub, then name lookup stops; the scope of Abs won't be examined. Only Sub::f is put in overload set and then overload resolution is performed. ... name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined. You can use using to introduce the names of Abs into Sub, then Abs::f could be found and take part in overload resolution too. struct Sub: public Abs { using Abs::f; void f(int x) final { std::cout << 1; } };
70,412,738
70,412,759
Why this string is not converting to Integer?
I'm trying to convert the string r to an int(num). But it keeps returning 0. Note: When I was returning the string, the answer(reversed number) was correct. My code looks like this: string n, r = ""; cin >> n; for (int i = n.length(); i >= 0; i--) { r += n[i]; } int num; istringstream(r) >> num; cout << num << endl;
The value of the character n[n.length()] is equal to '\0' That is when the index of the subscript operator is equal to the size of the string then it "returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior." (The C++ Standard) So your reversed string starts with the terminating zero. Rewrite your for loop the following way for ( auto i = n.length(); i != 0; ) { r += n[--i]; } or for ( auto i = n.length(); i != 0; --i ) { r += n[i - 1]; } Of course instead of the for loop you could just write r.assign( n.rbegin(), n.rend() ); Pay attention to that the initialization of the variable r with an empty string string n, r = ""; is redundant. You could just write string n, r;
70,413,195
70,413,403
Partial specialization of a nested class
How to partially specialize nested class without partially specializing the nesting class? Implementation of class C is the same for all N. Implementation of C::iterator is special for N=1. template<class T, int N> class C { class iterator; ... }; template<class T, int N> class C<T, N>::iterator { ... }; // Partial specialization doesn't compile: template<class T> class C<T, 1>::iterator { ... }; I can partially specialize class C for N=1, but that's a lot of code duplication...
If you do not want to specialize whole class then just move the iterator out of class and make it template: template<class T, int N> class C_iterator { ... }; If needed make your specializations: template<class T> class C_iterator<T, 1> { ... }; Then use it in your class as iterator, if needed befriend it: template<class T, int N> class C { using iterator = C_iterator<T, N>; friend iterator; ... };
70,413,446
70,429,200
Linearize nested for loops
I'm working on some heavy algorithm, and now I'm trying to make it multithreaded. It has a loop with 2 nested loops: for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { for (int k = j + 1; k < n; ++k) { function(i, j, k); } } } I know, that the number of function calls will be equal to But I have one last problem: I don't know how to calculate i, j and k based on b (0 <= b < binom(n, 3)) for (int b = start; b < end; ++b) { // how to calculate i, j, k? } How can I calculate these values? EDIT: My main idea is to call function like this from different threads: void calculate(int start, int end) { for (int b = start; b < end; ++b) { int i = ...; int j = ...; int k = ...; function(i, j, k); } } int total = binom(n, 3); // thread A: calculate(0, total / 2); // thread B: calculate(total / 2, total);
Yet another take on your problem. As said in the comments, what you are looking for is basically finding the successor and the unranking of combinations. For this I use the algorithms from the book 'Combinatorial algorithms' of Kreher and Stinson. Here is the corresponding code consisting of the two functions next and unrank as well as a helper for the binomial coefficient which is required in the unranking function: int binomial ( int n, int k ) { int mn = k; if ( n - k < mn ) { mn = n - k; } if ( mn < 0 ) { return 0; } if ( mn == 0 ) { return 1; } int mx = k; if ( mx < n - k ) { mx = n - k; } int value = mx + 1; for (int i = 2; i <= mn; ++i) { value = ( value * ( mx + i ) ) / i; } return value; } auto unrank(int rank, int n, int k) { std::vector<int> t(k); int x = 1; for (int i = 0; i < k; ++i) { while (true) { int b = binomial ( n - x, k - i - 1); if (b > rank) break; rank -= b; ++x; } t[i] = x; ++x; } return t; } auto next(std::vector<int>& index, int n, int k) { for (int i = k-1; i >= 0; --i) { if (index[i] < n - (k-1) + i) { ++index[i]; for (int j = i+1; j < k; ++j) { index[j] = index[j-1]+1; } return true; } } return false; } The idea is then to generate the initial index-configuration from a given start address, and then compute the successor of this index (end-start) times. Here is an example: int main() { int n = 7; int k = 4; int start = 3; int end = 10; auto index = unrank(start,n,k); auto print_index = [&]() { for(auto const& ind : index) { std::cout<<ind<<" "; } std::cout<<std::endl; }; print_index(); for(int i=start; i<end; ++i) { next(index, n, k); print_index(); } } which prints 1 2 3 7 1 2 4 5 1 2 4 6 1 2 4 7 1 2 5 6 1 2 5 7 1 2 6 7 1 3 4 5 And here is the Demo. Enjoy!
70,414,371
70,490,852
Usage of lambda in constant expression
Take the following code: template <typename T, typename U> constexpr bool can_represent(U&& w) noexcept { return [] (auto&& x) { try { return T(std::forward<U>(x)) == std::forward<U>(x); } catch(...) { return false; } } (std::forward<U>(w)); } I am using this function in a constant expression (template). gcc compiles it without a problem. clang and MSVC don't, lamenting that the function does not result in a constant expression. Indeed, gcc did not immediately accept this either; it was getting hung up on the try, that normally wouldn't be allowed in a constexpr function. That's why I had to use an immediately invoked lambda expression. However, now it works, and considering it only works with gcc I'm quite confused. Which compiler is correct? Is there a property of the lambda that permits this to work in a constexpr context, or is this some kind of non-standard gcc extension? [I've used godbolt to compile with clang and MSVC, where as I have gcc 8.1.0 on my machine]
[gcc] was getting hung up on the try, that normally wouldn't be allowed in a constexpr function. This is correct for a C++17 program. (C++20 relaxed this, so a try block can now be used in a constexpr function. However, it is only the try that is allowed; it is not allowed for execution to hit something that throws an exception.) That's why I had to use an immediately invoked lambda expression. The implication here is that your approach made your code valid. This is incorrect. Using an an immediately invoked lambda did not work around the problem; it swept the problem under the rug. The try is still a problem, but now compilers do not have to tell you it is a problem. Using a lambda switches the constexpr criterion from the straight-forward "the function body must not contain a try-block" to the indirect "there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression". The tricky part here is that a violation of the latter criterion is "no diagnostic required", meaning that all the compilers are correct, whether or not they complain about this code. Hence my characterization of this as sweeping the problem under the rug. So why is... that criterion is a long thing to repeat... what's the issue involving "core constant expressions"? C++17 removed the prohibition against lambdas in core constant expressions, so that much looks good. However, there is still a requirement that all function calls within the constexpr function also be themselves constexpr. Lambdas can become constexpr in two ways. First, they can be explicitly marked constexpr (but if you do that here, the complaint about the try block should come back). Second, they can simply satisfy the constexpr function requirements. However, your lambda contains a try, so it is not constexpr (in C++17). Your lambda is not a valid constexpr function. Hence calling it is not allowed in a core constant expression. There is no execution path through can_represent() that avoids invoking your lambda. Therefore, can_represent is not a valid constexpr function, no diagnostic required.
70,414,405
70,414,422
What am i missing that texture isn't working OpenGL
I'm trying to apply textures to a face for now until i get it to work properly, but everytime the application runs the face is just a white color as it is for default, yet i don't know what is going wrong. LoadTexture function: GLuint LoadTexture( const char* texture ) { GLuint textureID = SOIL_load_OGL_texture( texture, SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS ); glBindTexture( GL_TEXTURE_2D, textureID ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glBindTexture( GL_TEXTURE_2D, 0 ); return textureID; } Main code: GLuint tex = LoadTexture("grass.jpg"); int crotate = 0; void Reshape(int w, int h) { if (h == 0) h = 1; float ratio = w * 1.0 / h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); gluPerspective(45.0f, ratio, 0.1f, 1000); glMatrixMode(GL_MODELVIEW); } void Cube() { glTranslatef(0, 0, -5); crotate++; glRotatef(crotate, 1,1,0); glActiveTexture(tex); glEnable(GL_TEXTURE_2D); glBindTexture( GL_TEXTURE_2D, tex); glBegin(GL_POLYGON); glTexCoord2f(0.0, 1.0); glVertex3f(-0.5,-0.5,0); glTexCoord2f(0.0, 0.0); glVertex3f(-0.5,0.5,0); glTexCoord2f(1.0, 0.0); glVertex3f(0.5,0.5,0); glTexCoord2f(1.0, 0.0); glVertex3f(0.5,0.5,0); glTexCoord2f(1.0, 1.0); glVertex3f(0.5,-0.5,0); glTexCoord2f(0.0, 1.0); glVertex3f(-0.5,-0.5,0); glEnd(); glDisable(GL_TEXTURE_2D); } void Display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); Cube(); glutPostRedisplay(); glutSwapBuffers(); } void Init() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Lighting /* glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); GLfloat qaDiffuseLight[] = {0.8, 0.8, 0.8, 1}; glLightfv(GL_LIGHT0, GL_DIFFUSE, qaDiffuseLight); GLfloat qaLightPos[] = {0.5, 0.5, 0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, qaLightPos); */ gluPerspective(45.5, 1.0f, 0.1f, 1000); glMatrixMode(GL_MODELVIEW); glEnable(GL_DEPTH_TEST); glClearColor(0, 0.6, 1, 1); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE); glutInitWindowSize(1280,720); glutCreateWindow("OpenGL Program"); Init(); glutReshapeFunc(Reshape); glutDisplayFunc(Display); glutMainLoop(); return 0; } I have searched many tutorials to texture map but all those i tried still aren't working for me, i'm using GLUT The latest tutorial or rather blog i followed to try adding textures was this https://www.3dgep.com/texturing-and-lighting-in-opengl/
The parameter of glActiveTexture is the texture unit: `glActiveTexture(tex); glActiveTexture(GL_TEXTURE0); The texture object is bound to a texture unit. The current texture unit can be stet with glActiveTexture. The default texture unit is 0 (GL_TEXTURE0). You cannot execute an OpenGL statement until you have a valid and current OpenGL context. Therefore you have to create the texture object after creating the OpenGL window and context. Call GLuint tex = LoadTexture("grass.jpg"); after the window is crated and the Context is made current. GLuint tex = 0; void Init() { tex = LoadTexture("grass.jpg"); // [...] } int main(int argc, char** argv) { // [...] glutCreateWindow("OpenGL Program"); Init(); // [...] }
70,414,454
70,414,523
How function-level exception handling works?
There is the following code, from here class Base { int i; public: class BaseExcept {}; Base(int i) : i(i) { throw BaseExcept(); } }; class Derived : public Base { public: class DerivedExcept { const char* msg; public: DerivedExcept(const char* msg) : msg(msg) {} const char* what() const { return msg; } }; Derived(int j) try : Base(j) { // Constructor body cout << "This won't print" << endl; } catch (BaseExcept&) { throw DerivedExcept("Base subobject threw");; } }; int main() { try { Derived d(3); } catch (Derived::DerivedExcept& d) { cout << d.what() << endl; // "Base subobject threw" } } My question is, why the thrown exception is not caught here catch (BaseExcept&) { throw DerivedExcept("Base subobject threw");; } But the catch in main? catch (Derived::DerivedExcept& d) { cout << d.what() << endl; // "Base subobject threw" } Why does it output "Base subobject threw" According to my understanding, the thrown exception should be caught in the catch after try (or the function body equivalent to try), but there is no, why? What is the propagation path of the exception? code from there My question is this, try catch I have seen before all have this form. try{} catch(){} So I think for the following snippet Derived(int j) try: Base(j) { // Constructor body cout << "This won't print" << endl; } catch (BaseExcept&) { throw DerivedExcept("Base subobject threw");; } When Derived() throws an exception, it should be caught by the catch (BaseExcept&)in the following line, not by the catch (Derived::DerivedExcept& d) in the main function. But when I comment out it here catch (Derived::DerivedExcept& d) { //cout << d.what() << endl; // "Base subobject threw" } There will be no "Base subobject threw" output. This is different from what I expected. I am learning basic exception knowledge. Did I understand something wrong
Derived(int j) try : Base(j) { // Constructor body cout << "This won't print" << endl; } catch (BaseExcept&) { // why the thrown exception is not caught here throw DerivedExcept("Base subobject threw");; } The only way for the program to output Base subobject threw is if the exception is actually caught where you do not think it's caught. The string does not exist anywhere else in the program. But the catch in main? That's because you throw an exception in the catch. That exception is not caught by the same catch (which would result in infinite recursion in this case). It's caught by the outer try..catch which you have in main.
70,414,652
70,414,687
How do I pass in a file name when creating them in C++?
I am newer to C++ and I am trying to make a simple log in system. I am currently working on the signing up a new user and I want to create a directory for that user that I can then save their information in later. I am able to make a directory called "User" but instead of User I want to pass in an argument but I am not finding anyway to do that. Any advice? #include <string> #include <iostream> #include <array> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <bits/stdc++.h> #include "User.h" User::User() { //default values user_name = "user"; password = "12345"; } void User::CreateNewUser() { PromptForNewUserName(); MakeNewUserDir(); } void User::SetUserName(std::string new_user_name) { user_name = new_user_name; } void User::SetPassword(std::string new_password) { password = new_password; } std::string User::GetName() { return user_name; } void User::PromptForNewUserName() { bool is_new_name = false; std::string temp_user_name = "user"; do { std::cout << "Enter your name: "; std::cin >> temp_user_name; if(GetName() != temp_user_name) { SetUserName(temp_user_name); is_new_name = true; }else {std::cout << "That user name is already in use." << std::endl; is_new_name = false;} }while(!is_new_name); } void User::PromptForNewPassword() { } void User::PasswordReset() { } void User::MakeNewUserDir() { if(!GetName().empty()) { int check; int name_length = GetName().length(); char name_array[name_length + 1]; // copies get name in to char array since mkdir takes in a char not a string strcpy(name_array, GetName().c_str()); // mkdir returns an int, so we can assign it to check check = mkdir("C:/Users/3192833/Documents/MobaXterm/Lee/LinuxCheater/User", 0777); // check if the directory is created or not if(!check) { std::cout << std::endl; const char* name_array_ptr = name_array; rename("User", name_array_ptr); std::cout << "\nAn account has been created for " << GetName() << std::endl; }else{ printf("Unable to create account\n"); exit(1); } } }
Add #include <string> to the top of your source file Change your MakeNewUserDir() function to be declared and defined as follows: void User::MakeNewUserDir(const std::string& path) You may need to make a similar change in your class declaration as well. Then you invoke mkdir as follows: check = mkdir(path.c_str(), 0777); And then later on, when you want to invoke MakeNewUserDir with an argument, you can pass a string literal, another instace of std::string, or a char* based C string. User u; u.MakeNewUserDir("C:/Users/3192833/Documents/MobaXterm/Lee/LinuxCheater/User"); OR std::string s = "C:/Users/3192833/Documents/MobaXterm/Lee/LinuxCheater"; s += "/User"; u.MakeNewuserDir(s);
70,415,047
70,420,393
How to decode (from base64) a python np-array and reload it in c++ as a vector of floats?
In my project I work with word vectors as numpy arrays with a dimension of 300. I want to store the processed arrays in a mongo database, base64 encoded, because this saves a lot of storage space. Python code import base64 import numpy as np vector = np.zeros(300, dtype=np.float32) # represents some word-vector vector = base64.b64encode(vector) # base64 encoding # Saving vector to MongoDB... In MongoDB it is saved in as binary like this. In C++ I would like to load this binary data as a std::vector. Therefore I have to decode the data first and then load it correctly. I was able to get the binary data into the c++ program with mongocxx and had it as a uint8_t* with a size of 1600 - but now I don't know what to do and would be happy if someone could help me. Thank you (: C++ Code const bsoncxx::document::element elem_vectors = doc["vectors"]; const bsoncxx::types::b_binary vectors = elemVectors.get_binary(); const uint32_t b_size = vectors.size; // == 1600 const uint8_t* first = vectors.bytes; // How To parse this as a std::vector<float> with a size of 300? Solution I added these lines to my C++ code and was able to load a vector with 300 elements and all correct values. const std::string encoded(reinterpret_cast<const char*>(first), b_size); std::string decoded = decodeBase64(encoded); std::vector<float> vec(300); for (size_t i = 0; i < decoded.size() / sizeof(float); ++i) { vec[i] = *(reinterpret_cast<const float*>(decoded.c_str() + i * sizeof(float))); } To mention: Thanks to @Holt's info, it is not wise to encode a Numpy array base64 and then store it as binary. Much better to call ".to_bytes()" on the numpy array and then store that in MongoDB, because it reduces the document size from 1.7kb (base64) to 1.2kb (to_bytes()) and then saves computation time because the encoding (and decoding!) doesn't have to be computed!
Thank @Holt for pointing out my mistake. First, you can't save the storage space by using base64 encoding. On the contrary, it will waste your storage. For an array with 300 floats, the storage is only 300 * 4 = 1200bytes. While after you encode it, the storage will be 1600 bytes! See more about base64 here. Second, you want to parse the bytes into a vector<float>. You need to decode the bytes if you still use the base64 encoding. I suggest you use some third-party library or try this question. Suppose you already have the decode function. std::string base64_decode(std::string const& encoded_string); // or something like that. You need to use reinterpret_cast to get the value. const std::string encoded(first, b_size); std::string decoded = base64_decode(encoded); std::vector<float> vec(300); for (size_t i = 0; i < decode.size() / sizeof(float); ++i) { vec[i] = *(reinterpret_cast<const double*>(decoded.c_str()) + i); }
70,415,053
70,449,886
Qt(c++) Keybinding with button(for my developing application)
I want to write a function that will work with keybinding for the application I am developing on the Qt platform, but I could not find any example that will work for me, like the picture I added from the discord application, can you help me? Discord keybinding
If you want user to hit a key combination for a selection then just create a class inheriting QLinEdit (even QLabel would work) and override keyPressEvent, void QLineEdit::keyPressEvent(QKeyEvent *event); and then use QKeyEvents function to get key and modifiers (shift, ctrl etc.). Just read the Qt Docs about it. Depending on the key and modifiers, write the modifier name + key's text (e.g. Ctrl + N). To hold actions (QAction), just use std::map<QString,QAction*> or QMap<QString,QAction*> and register/add your QAction objects in the map and assuming your class' name is MyClass and it has getKeyString() , to return key combination as QString, then you will just do, QString str = MyClassObj.getKeyString(); QKeySequence ks(str); actionMap.at("NewFile")->setShortcut(ks);
70,415,110
70,415,173
Getting "No valid copy constructor" in C++ on return struct
I'm currently working on implementing a simple 2D vector class Vector2f in C++ using Visual Studio Community Edition 2019. When I try to return a newly constructed one in a method, such as: return Vector2f((this->x/sum),(this->y/sum); I'm getting a hint: no suitable copy constructor for Vector2f and an on-compile error: 'return': cannot convert from 'Vector2f' to 'Vector2f' I've rewritten the class from scratch a few times, and still seem to be getting the error. I don't understand, what exactly is going wrong? Vector2f_struct.h #pragma once #ifndef PMP_VECTOR2F_STRUCT__H #define PMP_VECTOR2F_STRUCT__H namespace pmp { struct Vector2f { /* Elements */ float x; float y; /* Methods */ // Constructors & Destructor Vector2f(); Vector2f(float i, float j); Vector2f(Vector2f& og); virtual ~Vector2f(); // Unary Operators float magnitude(); Vector2f normal(); }; }; #endif Vector2f_struct.cpp #include "pmp_Vector2f_struct.h" #ifndef PMP_VECTOR2F_STRUCT__CPP #define PMP_VECTOR2F_STRUCT__CPP /* Dependencies */ #include <math.h> namespace pmp { Vector2f::Vector2f() { this->x = 0.0f; this->y = 0.0f; return; }; Vector2f::Vector2f(float i, float j) { this->x = i; this->y = j; return; }; Vector2f::Vector2f( Vector2f& og ) { this->x = og.x; this->y = og.y; return; }; Vector2f::~Vector2f() { this->x = 0.0f; this->y = 0.0f; return; }; float Vector2f::magnitude() { float c2 = (this->x * this->x) + (this->y * this->y); return sqrt(c2); }; Vector2f Vector2f::normal() { float sum = this->x + this->y; return Vector2f(this->x / sum, this->y / sum); // Error here. }; }; #endif
The parameter of the copy constructor has a non-constant referenced type Vector2f(Vector2f& og); In the member function normal there is returned a temporary object that is copied. You may not bind a temporary object with a non-constant lvalue reference. Redeclare the copy constructor like Vector2f(const Vector2f& og); Or just remove its explicit declaration. In this case the compiler generates it for you. Pay attention to that return statements in the constructors and the destructor are redundant.
70,415,131
70,415,274
How can I get a reference of the values in a map in C++?
I want the player of my game to not move if it will collide with other entities. One solution I've thought would be keeping track of all entities in the game, and when trying to move, check if it will collide with any of those. The problem is that when looping the vector, I don't get a reference of the entities, but new values, so they have new IDs and I no more can check if the IDs check. // Actor.cpp Actor::Actor(float x, float y) : x(x), y(y), m_MovementSpeed(1), m_Alive(true) { // ... EntityTracker::addEntity(*this); this->ID = EntityTracker::entityAmount(); } void Actor::move(float _x, float _y) { for (auto& e : EntityTracker::entities()) { if (this->ID != e->ID && this->collides(*e)) { return; } } this->x = this->x + _x * m_MovementSpeed; this->y = this->y + _y * m_MovementSpeed; this->m_Sprite.move(_x * m_MovementSpeed, _y * m_MovementSpeed); } // EntityTracker.cpp uint64_t EntityTracker::s_EntityAmount = 0; std::map<uint64_t, Actor> EntityTracker::s_Entities {}; void EntityTracker::addEntity(const Actor& actor) { EntityTracker::s_Entities.insert(std::pair<uint64_t, Actor>(s_EntityAmount, actor)); s_EntityAmount++; } std::vector<Actor*> EntityTracker::entities() { std::vector<Actor*> actors; for (auto& it : EntityTracker::s_Entities) { std::cout << it.second.ID << std::endl; std::cout << it.first << std::endl; actors.push_back(&it.second); } return actors; } // EntityTracker.h class EntityTracker { public: static void addEntity(const Actor& actor); static bool removeEntity(uint64_t ID); static uint64_t entityAmount(); static std::vector<Actor*> entities(); private: static uint64_t s_EntityAmount; static std::map<uint64_t, Actor> s_Entities; }; When I press a key the std::cout's print this: 1571901079888 // actor's internal ID from vector 0 // ID from vector 1571901079888 1 1571901079888 0 ... How can I solve this?
You can return vector of type std::vector<std::reference_wrapper<Actor>> from EntityTracker::entities(), an example of such use is below: // Original data std::vector<std::string> vec; vec.push_back("one"); vec.push_back("two"); // Now its copied as references to rvec std::vector< std::reference_wrapper<std::string>> rvec; for(auto& r: vec) rvec.push_back(r); // Now output original data using rvec references. for(auto s: rvec) std::cout << s.get() << std::endl; Then inside Actor::move you will have access to reference of real Actor instead of its copy. You may also consider keeping Actors as a smart pointers using std::share_ptr.
70,415,450
70,415,492
C++ does not alter registry even though running without errors
Trying to write code to change the registry keys with c++ after endless amount of time I reached this point but this code still does not edit the registry even when running as admin to change the registry 4 functions are needed according to this question which I used and every single one of them returns a zero which means that the function completed without errors but still no values are changed in the registry gui the SecurityHealth strartup service is running on my machine and has the path %windir%\system32\SecurityHealthSystray.exe and type REG_EXPAND_SZ I even tried creating a new entry similar to the SecurityHealth and still nothing is changed I am compiling as admin and running as admin HKEY open_reg() { int result; LPCSTR lpSubKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; HKEY hKey; result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_QUERY_VALUE|KEY_WRITE|KEY_READ|KEY_SET_VALUE, &hKey); if ( result != 0) { cout << " Failed to open registry. - [ "<< result<< "]" <<endl; } else { cout << "Found registry key. - [" << result<<"]" << endl; } return hKey; } HKEY find_reg_value(HKEY handle) { LPCSTR lpValueName = "SecurityHealth"; DWORD BufferSize = TOTALBYTES; DWORD cbData; int dwRet; PPERF_DATA_BLOCK PerfData = (PPERF_DATA_BLOCK) malloc( BufferSize ); cbData = BufferSize; cout << "\nRetrieving the data..." << endl; dwRet = RegQueryValueExA( handle, lpValueName, NULL, NULL, (LPBYTE) PerfData, &cbData ); if ( dwRet == 0 ) { cout << "Successfully quered [" << dwRet << "]"<<endl; } else { cout << "Failed to query Error code : [" << dwRet << "]"<<endl; } return handle; } void set_reg_value(HKEY handle) { int result; LPCSTR lpValueName = "SecurityHealth"; std::string file = "C:\\Windows\\System32\\cmd.exe"; const char * sth = file.c_str(); unsigned char m_Test[file.size()]; strcpy((char*)m_Test, sth); DWORD DATA_SIZE = file.size()+1; result = RegSetValueExA(handle,lpValueName,0,REG_EXPAND_SZ,m_Test,DATA_SIZE); if ( result == 0 ) { cout << "Successfully changed value [" << result << "]"<<endl; } else { cout << "Failed to change value Error code : [" << result << "]"<<endl; } RegCloseKey (handle); } int main() { cout << "testing windows registry " << endl; HKEY reg_handle = open_reg(); HKEY handler = find_reg_value(reg_handle); set_reg_value(handler); system("PAUSE"); return 0; } the compiled exe output in the terminal testing windows registry Found registry key. - [0] Retrieving the data... Successfully quered [0] Successfully changed value [0] Press any key to continue . . . Compiled with g++ regutil.cpp
I suspect you are compiling as a 32-bit program but looking at a 64-bit registry. Switch to compiling as 64-bit instead. (There is a 32-bit registry instead, which can be found buried within the 64-bit hives but you likely want to change the actual 64-bit version).
70,415,752
70,628,000
How to use the QVector container with a custom class?
Here's a custom class I implemented for a personal project: #include <QtCore/QCommandLineOption> #include <QtCore/QSharedPointer> #include <genepy/cli/CommandLineArgument.h> #include <genepy/cli/CommandLineOption.h> class QCommandLineParser; namespace genepy { class CommandLineParserBuilder; class ConsoleApplication; class GENEPY_EXPORT CommandLineParser { public: static CommandLineParserBuilder create(const ConsoleApplication& application); void doParsing(); template <typename T> T getArgumentValue(const QString& name) const; bool isOptionPresent(const QString& name) const; template <typename T> T getOptionValue(const QString& name) const; private: friend class CommandLineParserBuilder; explicit CommandLineParser(const ConsoleApplication& application); const QSharedPointer<QCommandLineParser> parser_; const QCommandLineOption helpOption_; const QCommandLineOption versionOption_; QVector<CommandLineArgument> arguments_; QVector<CommandLineOption> options_; }; } // namespace genepy The complete code can be found here. When I compile this code with Qt 5.15 on Windows (MinGW, MSVC), there's no problem. However, on Debian 9 with Qt 5.7, I get this error : In file included from /home/erwan/git/genepy/include/genepy/cli/CommandLineParserBuilder.h:29:0, from /home/erwan/git/genepy/src/cli/CommandLineParser.cpp:29: /home/erwan/git/genepy/include/genepy/cli/CommandLineParser.h:94:34: error: field ‘arguments_’ has incomplete type ‘QVector<genepy::CommandLineArgument>’ QVector<CommandLineArgument> arguments_; ^~~~~~~~~~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/qglobal.h:1139:0, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qalgorithms.h:43, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qlist.h:43, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qstringlist.h:41, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qcommandlineparser.h:43, from /usr/include/x86_64-linux-gnu/qt5/QtCore/QCommandLineParser:1, from /home/erwan/git/genepy/src/cli/CommandLineParser.cpp:26: /usr/include/x86_64-linux-gnu/qt5/QtCore/qtypeinfo.h:189:1: note: declaration of ‘class QVector<genepy::CommandLineArgument>’ Q_DECLARE_MOVABLE_CONTAINER(QVector); ^ In file included from /home/erwan/git/genepy/include/genepy/cli/CommandLineParserBuilder.h:29:0, from /home/erwan/git/genepy/src/cli/CommandLineParser.cpp:29: /home/erwan/git/genepy/include/genepy/cli/CommandLineParser.h:97:32: error: field ‘options_’ has incomplete type ‘QVector<genepy::CommandLineOption>’ QVector<CommandLineOption> options_; ^~~~~~~~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/qglobal.h:1139:0, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qalgorithms.h:43, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qlist.h:43, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qstringlist.h:41, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qcommandlineparser.h:43, from /usr/include/x86_64-linux-gnu/qt5/QtCore/QCommandLineParser:1, from /home/erwan/git/genepy/src/cli/CommandLineParser.cpp:26: /usr/include/x86_64-linux-gnu/qt5/QtCore/qtypeinfo.h:189:1: note: declaration of ‘class QVector<genepy::CommandLineOption>’ Q_DECLARE_MOVABLE_CONTAINER(QVector); ^ I've no clue on what's going wrong with this code... Can someone help me? Thank you very much for your help.
Finally, I changed QVector<CommandLineArgument> to QVector<QSharedPointer<CommandLineArgument>> since CommandLineArgument wasn't an assignable data type (it was missing a default constructor among others). Now, it works.
70,415,777
70,415,897
how to improve my class to create output files
As I need this quite often, I would like to write a class handling main ofstream activities. Something that I could use like this: OutputFile out("output.txt"); for (int i = 0; i < 10; ++i) out << i << "\n"; To this end, I wrote the following class: class OutputFile { std::string filename; std::ofstream out; public: explicit OutputFile(std::string filename) { this->filename = filename; out.open("output/" + filename); } ~OutputFile() { out.close(); } std::ofstream& operator()() { return out; } }; which is almost what I wanted, however I'm overloading the operator (), such that in the example above I have to use out() << i << "\n"; How should I modify my class such that I can use as out << i << "\n";
You can overload operator<< in your class. class OutputFile { std::string filename; std::ofstream out; public: explicit OutputFile(const std::string &filename) : filename(filename), out("output/" + filename) {} template<typename T> OutputFile& operator<<(const T &value) { out << value; return *this; } };
70,416,040
70,416,046
If statement on args giving odd outputs
When running this code: ./a.out 5 + 5 i am supposed to get 10. but instead i get Unkown operator. does anyone know why this may be happening? #include <iostream> #include <string> int main(int argc, char *argv[]){ if (argv[2]=="+"){ std::cout << std::stoi(argv[1])+std::stoi(argv[3]) << "\n"; } else if (argv[2]=="-"){ std::cout << std::stoi(argv[1])-std::stoi(argv[3]) << "\n"; } else{ std::cout << "Unkown operator." << "\n"; } return 0; }
This line is comparing pointer values, and not the strings data they point to... if (argv[2]=="+"){ Either use strcmp: if (strcmp(argv[2], "+") == 0){ } Or something along these lines: if (std::string(argv[2]) == "+"){ }
70,416,078
70,416,191
In C or C++, is memory layout of uint64_t guaranteed to be the same as uint32_t[2] ? Can one be cast as the other?
In C or C++, is memory layout of uint64_t guaranteed to be the same as uint32_t[2] ? Can I cast one to the other and have them always work as expected? Does it depend upon if the CPU is 32bit or 64bit or is it compiler implementation dependent?
In C or C++, is memory layout of uint64_t guaranteed to be the same as uint32_t[2] ? No. Endianess. Can one be cast as the other? Maybe, maybe not, in C. A pointer to an array of 2 uint32_t may not be aligned to uint64_t. When the resulting pointer is not properly aligned, it's undefined behavior. https://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p7 Yes in C++. https://eel.is/c++draft/expr#reinterpret.cast-7 Can I cast one to the other and have them always work as expected? No. Possibly, you can cast, but you can't access the data with the handle after casting. It would be a strict alias violation. Does it depend upon if the CPU is 32bit or 64bit Not really. or is it compiler implementation dependent? Because the behavior would be undefined, it's very much compiler dependent.
70,416,086
73,300,814
Correct way to exclude files from source tar ball using CPack
When configuring cpack I would like to not include a few files that are in the source directory when running make package_source, everything works fine when using CPACK_SOURCE_IGNORE_FILES I get the correctly generated source package with the file test.cpp not included in the resulting tar ball. set(CPACK_SOURCE_IGNORE_FILES /.vscode /.vagrant /.git /dist /.*build.* /\\\\.DS_Store test\.cpp ) However, reading the docs for cmake I found the var CPACK_SOURCE_STRIP_FILES. Which says "List of files in the source tree that will be stripped." So, would setting this variable be the correct way to exclude source files from the source tar ball instead of using CPACK_SOURCE_IGNORE_FILES? I have tried several variations and nothing seems to work, so either I am using it wrong or I am miss-using it or ??? set(CPACK_SOURCE_STRIP_FILES "${PROJECT_SOURCE_DIR}/src/test.cpp") set(CPACK_SOURCE_STRIP_FILES "test.cpp") set(CPACK_SOURCE_STRIP_FILES "src/test.cpp") I can't find any examples of any other project using CPACK_SOURCE_STRIP_FILES so maybe I shouldn't be using it at all. Thanks :)
The documentation is pretty confusing for someone (including me) who doesn't already know what it's referring to. I believe it's referring to the command "strip", which is one of the GNU development tools, and is used to "discard symbols and other data from object files". I'm not sure why this would be useful for source files though; I thought source and object files are opposite sides of a coin. There is a similar cpack variable named CPACK_STRIP_FILES, which makes much more sense. TL;DR I'm pretty sure CPACK_SOURCE_STRIP_FILES is not the droid you are looking for and you're right in using CPACK_SOURCE_IGNORE_FILES.
70,416,207
70,427,995
What is the callgraph expansion stage in g++?
I am profiling my program;s compilation and looking for bottlenecks. I originally thought template instantiation would be the most expensive part but seems to be callgraph funciton expansion. Problem is, I have no idea what that stage refers to. callgraph functions expansion : 28.98 ( 80%) 0.95 ( 39%) 29.98 ( 73%) 782M ( 60%) template instantiation : 2.36 ( 7%) 0.47 ( 19%) 2.84 ( 7%) 191M ( 15%) I have tried to search it up online but I find no answers.
It appears to be part of the optimization process implemented by GCC. I was able to find one reference, The GCC call graph module, which describes it as the final step performed by the front-end of the compiler: Expansion: We proceed in reverse DFS order on functions that are still present in the call-graph, applying inter-procedural optimizations such as inlining to the functions, and finally leaving them to the back-end to do the actual optimization and compilation.
70,416,618
70,420,294
Finding all possible occurrences of a matrix in a larger one
This question is a general algorithmic question, but I am writing it in C++ as it is the language in which I have faced this problem. Let's say I have the following function: using Matrix = std::array<std::array<uint8_t, 3>, 3>; void findOccurrences(std::vector<Matrix>& output, const std::vector<std::vector<uint8_t>>& pattern); Assuming that pattern is a certain pattern of numbers from 0 to 255, that can fit in a Matrix as I defined above, and given that 0 means an "empty" slot, I want to be able to generate all the possible occurrences of pattern as a Matrix. For example, given the following pattern: { { 1, 2 }, { 3, 4 } } I want to recive the following vector of matrixes: 1 | 2 | 0 3 | 4 | 0 0 | 0 | 0 0 | 1 | 2 0 | 3 | 4 0 | 0 | 0 0 | 0 | 0 1 | 2 | 0 3 | 4 | 0 0 | 0 | 0 0 | 1 | 2 0 | 3 | 4 The pattern does not have to be a square, but we assume that it is not larger than a Matrix can contain. I have thought of some approaches for this problem, and ended up with what I think is the most obvious way to do it, but I am having a hard time trying to figure out the logic for the entire thing. So far what I have is: void findOccurrences(std::vector<Matrix>& output, const std::vector<std::vector<uint8_t>>& pattern) { Pattern curPattern = {0}; //temporary pattern, to store each time the current we work on const size_t lineOpts = 3 - pattern.size() + 1; //amount of possible line combinations for (size_t i = 0; i < lineOpts; i++) //for each possible combination { for (size_t j = 0; j < pattern.size(); j++) //for each line in pattern { const size_t lineInd = j + i; //index of line in curPattern const auto& line = pattern[j]; //current line in input pattern const size_t colOpts = 3 - line.size() + 1; //amount of possible column combinations for this line for (size_t k = 0; k < colOpts; k++) //for each possible column combination { for (size_t l = 0; l < line.size(); l++) //for each column in line { const size_t colInd = l + k; //index of column in curPattern //got stuck here } } } } } The problem I'm having here is that I can't think of a way to continue this algorithm without losing possibilities. For example, getting only options 0 and 2 from the example result vector I gave earlier. Plus, this approach seems like it might be a inefficient. Is this even the right way to go? And if so, what am I missing? Edit: We also assume that pattern does not contains 0, as it marks an empty slot.
You were already somehow on the right track. Logically it is clear what has to be done. We take the upper left edge of the sub pattern. Then we calculate the resulting upper left edges in the target matrix. The column offset in the resulting matrix, where we will copy the pattern to, will start at 0 and will be incremented up to the size of the matrix - the size of the pattern + 1. Same with the row offset. So, in the above case, with a matrix size of 3,3 and a pattern size, the target position in the resulting matrix will be 0,0, 0,1, 1,0 1,1. And then we copy the complete pattern at these positions. We need to play a little bit with indices, but that is not that complicated. I have created a well documented example code. If you will read this, then you will immediately understand. Please see below one of many possible solutions: #include <iostream> #include <vector> #include <array> #include <cstdint> constexpr size_t MatrixSize = 3u; using MyType = uint8_t; using MatrixRow = std::array<MyType, MatrixSize>; using Matrix = std::array<MatrixRow, MatrixSize>; using Pattern = std::vector<std::vector<MyType>>; using MatrixPattern = std::vector<Matrix>; MatrixPattern findOccurence(const Pattern& pattern) { // Here we will store the resulting matrixes MatrixPattern result{}; // Sanity check 1. Do we have data in the pattern at all if (pattern.empty() or pattern.front().empty()) { std::cerr << "\n\n*** Error: At least one dimension of input pattern is empty\n\n"; } // Sanity check 2. Does pattern fit at all into the matrix else if ((pattern.size() > MatrixSize) or (pattern.front().size() > MatrixSize)) { std::cerr << "\n\n*** Error: At least one dimension of input pattern is empty\n\n"; } else { // Now, we know that we will have a solution // Check, how many horizontol fits we can theoretically have // This will be size of sizeof Matrix - sizeof pattern + 1. const size_t horizontalFits{ MatrixSize - pattern.front().size() + 1 }; // Same for vertical fits const size_t verticalFits{ MatrixSize - pattern.size() + 1 }; // We now know the horizontal and vertical fits and can resize the // Resulting vector accordingly. result.resize(horizontalFits * verticalFits); size_t indexInResult{ 0 }; // For all possible positions of the patern in the resulting matrix for (size_t startRowInResultingMatrix{ 0u }; startRowInResultingMatrix < verticalFits; ++startRowInResultingMatrix) for (size_t startColumnInMatrix{ 0u }; startColumnInMatrix < horizontalFits; ++startColumnInMatrix) { // Now we have the upper left edge position of the pattern in the matrix // Copy pattern to that position for (size_t rowOfPattern{ 0u }; rowOfPattern < pattern.size(); ++rowOfPattern) for (size_t colOfPattern{ 0u }; colOfPattern < pattern.front().size(); ++colOfPattern) // Copy. Calculate the correct indices and copy values from sub pattern to matrix result[indexInResult][startRowInResultingMatrix + rowOfPattern][startColumnInMatrix + colOfPattern] = pattern[rowOfPattern][colOfPattern]; // Next sub matrix ++indexInResult; } } return result; } // Driver/Test code int main() { // Pattern to insert Pattern pattern{ {1,2}, {3,4} }; // Get the result MatrixPattern matrixPattern = findOccurence(pattern); // Show output for (const Matrix& matrix : matrixPattern) { for (const MatrixRow& matrixRow : matrix) { for (const MyType& m : matrixRow) std::cout << (int)m << ' '; std::cout << '\n'; } std::cout << "\n\n"; } }
70,416,911
70,417,003
How to generate preprocess and assmeble code by cmake?
I am trying to get intermediate .i .s file by CMake when compiling .cpp file, but cmake default only output .o file. Is there any command to manipulate cmake to keep these intermediate file, thanks a lot!
If you are using gcc, try adding this line. SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -save-temps=obj")
70,417,120
70,418,912
Template specialization of operator[] within a class with multiple template parameters
I'm having trouble specializing 2 methods of a tokenizer class that's declared with 2 template parameters. I've referenced Template specialization of a single method from a templated class but I am still encountering a few errors with my implementation. Some code (specialized functions near EOF): #pragma once #include "stdafx.h" #include <string> #include <vector> #include <sstream> #include <stdexcept> inline const std::string emptyString = ""; inline const std::wstring emptyWString = L""; template <class stringT = std::string, class delimiterT = char> class Tokenizer { private: std::vector<stringT> tokens; bool enableParserThrow; public: Tokenizer(bool throwOnParseError) : enableParserThrow(throwOnParseError) { } Tokenizer(const stringT& tokenizeMe, delimiterT delimiter) : Tokenizer(true) { TokenizeString(tokenizeMe, delimiter); } void TokenizeString(const stringT& str, delimiterT delimiter) { std::stringstream ss; ss << str; std::string token; while (std::getline(ss, token, delimiter)) { tokens.push_back(token); } } template <class T> T ParseToken(size_t tokenIndex) { if (tokenIndex < 0 || tokenIndex >= tokens.size()) { ThrowParserExceptionIfEnabled("Index out of range."); return T(); } T temp; std::stringstream ss; ss << tokens[tokenIndex]; ss >> temp; if (ss.fail()) ThrowParserExceptionIfEnabled("Parse failure."); return temp; } void Clear() { tokens.clear(); } const std::vector<stringT>& GetTokens() { return tokens; } void ThrowParserExceptionIfEnabled(const char* message) { if (enableParserThrow) { throw std::runtime_exception(message); } } // Trying to specialize these functions so I can return a reference to a global empty std::string or std::wstring if tokeIndex is out of range template<> const std::string& Tokenizer<std::string, delimiterT>::operator[](size_t tokenIndex); //TODO: //template<> //const std::string& Tokenizer<std::wstring, delimiterT>::operator[](size_t tokenIndex); }; template<class stringT, class delimiterT> inline const std::string & Tokenizer<stringT, delimiterT>::operator[](size_t tokenIndex) { return emptyString; } What is the proper specialization definition of Tokenizer<>::operator[]? I'm receiving the following errors with this implementation:
As your operator[] is not a template, you can't specialize it inside your class. What you want is to specialize the non template method for a template class. But you can't do a partial specialization for the class to add definitions of members to it. Working example: template <class stringT = std::string, class delimiterT = char> class Tokenizer { const std::string& operator[](size_t tokenIndex); }; template<> inline const std::string& Tokenizer<std::wstring, char>::operator[](size_t ) { return emptyString; } template< > inline const std::string& Tokenizer<std::string, char>::operator[](size_t ) { return emptyString; } To get rid of that problem you should check if your method really depends on all template parameters. If not, you can simply put them to a base class, which only depends on a single template parm and inherit from there. Maybe other code organization may also help.
70,417,145
70,417,196
error: use of deleted function ‘Node::~Node()’
Here is an oversimplified version of my code #include <vector> #include <string> #include <unordered_map> #include <iostream> struct ElementData { std::string tagName; std::unordered_map<std::string,std::string> attributes; }; enum NodeTypeEnum { None=-1, Text, Element }; struct NodeType { private: union { std::string text; ElementData element; }; public: NodeTypeEnum type; }; struct Node { std::vector<Node> children; NodeType type; }; int main() { Node n; } basically there is a node which has a type and a bunch of children. the type is basically a tagged union, I make sure that if i am reading an element of the union it is the one I last wrote. This seems simple enough to me, so I am not sure why I am getting the errors. here are all the errors Main.cpp: In function ‘int main()’: Main.cpp:55:10: error: use of deleted function ‘Node::Node()’ 55 | Node n; | ^ Main.cpp:41:8: note: ‘Node::Node()’ is implicitly deleted because the default definition would be ill-formed: 41 | struct Node | ^~~~ Main.cpp:41:8: error: use of deleted function ‘NodeType::NodeType()’ Main.cpp:23:8: note: ‘NodeType::NodeType()’ is implicitly deleted because the default definition would be ill-formed: 23 | struct NodeType | ^~~~~~~~ Main.cpp:29:21: error: union member ‘NodeType::<unnamed union>::text’ with non-trivial ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’ 29 | std::string text; | ^~~~ Main.cpp:30:21: error: union member ‘NodeType::<unnamed union>::element’ with non-trivial ‘ElementData::ElementData()’ 30 | ElementData element; | ^~~~~~~ Main.cpp:41:8: error: use of deleted function ‘NodeType::~NodeType()’ 41 | struct Node | ^~~~ Main.cpp:23:8: note: ‘NodeType::~NodeType()’ is implicitly deleted because the default definition would be ill-formed: 23 | struct NodeType | ^~~~~~~~ Main.cpp:29:21: error: union member ‘NodeType::<unnamed union>::text’ with non-trivial ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::~basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’ 29 | std::string text; | ^~~~ Main.cpp:30:21: error: union member ‘NodeType::<unnamed union>::element’ with non-trivial ‘ElementData::~ElementData()’ 30 | ElementData element; | ^~~~~~~ Main.cpp:55:10: error: use of deleted function ‘Node::~Node()’ 55 | Node n; | ^ Main.cpp:41:8: note: ‘Node::~Node()’ is implicitly deleted because the default definition would be ill-formed: 41 | struct Node | ^~~~ Main.cpp:41:8: error: use of deleted function ‘NodeType::~NodeType()’ Why is ~NodeType() deleted? How can i fix this? any help would be appreciated.
You have a union with a member that has a non-trivial destructor. So the union can't know how to destruct itself. That's why NodeType::~NodeType is deleted by default. That's what the message tells you. You need to define the destructor yourself and properly call the destructor on the correct member. Or, better yet, don't use unions at all. They are unsafe. Use std::variant which is the standard library type for "tagged unions", or type-safe unions.
70,417,195
70,417,335
Range-For loop over a string adding a null or empty char at the end
Here is a loop that goes through each character in "(Level:". It adds something to the end which is messing up the rest of my code. #include <iostream> int main() { std::cout << "Output:" << std::endl; for (char letter : "(Level:") { std::cout << "'" << letter << "'" << std::endl; } return 0; } Output: '(' 'L' 'e' 'v' 'e' 'l' ':' '' I'm new to C++ and I don't understand what's happening.
"(Level:" has type const char[8], and is equivalent to { '(', 'L', 'e', 'v', 'e', 'l', ':', '\0' }. You can easily see this is the case by casting the letter to int before printing. Demo This happens, because string literals (anything "...") are C-strings, which are zero terminated. If you want strings to have a size instead of a zero terminator, you can use a string_view literal: #include <iostream> #include <string_view> using namespace std::literals::string_view_literals; int main() { std::cout << "Output:" << std::endl; for (char letter : "(Level:"sv) { std::cout << "'" << letter << "' (" << static_cast<int>(letter) << ")\n"; } return 0; } See the result
70,417,414
70,417,468
Can't open existing semaphore from another process C++
I'm trying to get existing semaphore from another process. To create semaphore i used: Semaphore(std::string name, int startState) { name = "Global\\" + name; Sem = OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, true, (LPCWSTR)name.c_str()); int s = (startState > 0); if (Sem == NULL) { Sem = CreateSemaphore(NULL, s, 1, (LPCWSTR)name.c_str()); } } In first process semaphore created correctly. GetLastError() returns 0. In second process, OpenSemaphore returns NULL. And GetLastError() returns 2. I tried to get semaphore by only "name" - without "Global\", but it got the same result. Help please)
If you ever feel the need to use C-style casting (like in (LPCWSTR)name.c_str()) you should take that as a sign you're doing something wrong. Like you do here: std::string is a narrow character (i.e. char) string, while you use the wide characer (wchar_t) functions. That means the names won't be what you expect. If you continue using std::string you must use the "ANSI" functions (e.g. CreateSemaphoreA). Otherwise switch to std::wstring which uses wide characters.
70,418,364
70,418,687
Range transformations with stateful lambdas and std::views::drop
it's my first time digging into the new <ranges> library and I tried a little experiment combining std::views::transform with a stateful lambda and 'piping' the resulting range to std::views::drop: #include <iostream> #include <ranges> #include <vector> using namespace std; int main() { auto aggregator = [sum = 0](int val) mutable { return sum += val; }; vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "Expected:\n"; int sum = 0; for (int val : data) { cout << (sum += val) << ' '; } cout << '\n'; cout << "Transformation:\n- - - "; for (int val : data | views::transform(aggregator) | views::drop(3)) { cout << val << ' '; } cout << '\n'; } The output was: Expected: 1 3 6 10 15 21 28 36 45 55 Transformation: - - - 4 9 15 22 30 39 49 Now, the difference between each expected and actual output is 1 + 2 + 3 = 6. I am guessing it is a result of the lazy evaluation of ranges that causes std::views::drop to disregard the first three transformations. Is there a way for me to force the evaluation of the aggregator functor for the three elements I drop? Or are stateful lambdas and ranges considered incompatible?
transform_view is required to be a pure function. This is codified in the regular_invocable concept: The invoke function call expression shall be equality-preserving and shall not modify the function object or the arguments. This is important to allow transform_view to not lie about its iterator status. Forward iterators, for example, are supposed to allow multipass iteration. This means that the value at each iterator position within the range must be independent of any other iterator position. That's not possible if the transformation functor is not pure. Note that all predicate functors are also regular_invocable. So this also applies to things like filter_view and take_while_view. Note that the algorithm transform does not have this requirement.
70,418,554
70,418,831
I am not getting the error message in VScode without running it
Earlier I used to get error lines in the file name section and in the line also which contain error, but now I am not getting that. I have to run the program to know about the error in the code. Like in which line I am getting error. As shown in the image also without running the program I am not getting the error message.
Enable Your Squiggles to resolve this: click ctrl+shift+p Search c/c++: enable error squiggles click on it. It will enable your error messages.
70,418,599
70,419,756
replacing string based on user input c++
i want to receive an input from user and search a file for that input. when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input. (I'm writing a hospital management app and this is a part of project that patients and edit their document). i completed 90 percent of the project but i don't know how to replace it. check out following code: #include <iostream> #include <stream> #include <string.h> #include <string> using namespace std; int main(){ string srch; string line; fstream Myfile; string word, replacement, name; int counter; Myfile.open("Patientlist.txt", ios::in|ios::out); cout << "\nEnter your Name: "; cin.ignore(); getline(cin, srch); if(Myfile.is_open()) { while(getline(Myfile, line)){ if (line.find(srch) != string::npos){ cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl; cin >> word >> replacement; } // i want to change in here } }else { cout << "\nSearch Failed... Patient not found!" << endl; } Myfile.close(); } for example my file contains this line ( David , ha , 2002 ) and user wants to change 2002 to 2003
You cannot replace the string directly in the file. You have to: Write to a temporary file what you read & changed. Rename the original one (or delete it if you are sure everything went fine). Rename the temporary file to the original one. Ideally, the rename part should be done in one step. For instance, you do not want to end up with no file because the original file was deleted but the temporary one was not renamed due to some error - see your OS documentation for this. Here's an idea: #include <iostream> #include <fstream> #include <string> #include <cstdio> using namespace std; void replace(string& s, const string& old_str, const string& new_str) { for (size_t off = 0, found_idx = s.find(old_str, off); found_idx != string::npos; off += new_str.length(), found_idx = s.find(old_str, off)) s.replace(found_idx, old_str.length(), new_str); } int main() { const char* in_fn = "c:/temp/in.txt"; const char* bak_fn = "c:/temp/in.bak"; const char* tmp_fn = "c:/temp/tmp.txt"; const char* out_fn = "c:/temp/out.txt"; string old_str{ "2002" }; string new_str{ "2003" }; // read, rename, write { ifstream in{ in_fn }; if (!in) return -1; // could not open ofstream tmp{ tmp_fn }; if (!tmp) return -2; // could not open string line; while (getline(in, line)) { replace(line, old_str, new_str); tmp << line << endl; } } // in & tmp are closed here // this should be done in one step { remove(bak_fn); rename(in_fn, bak_fn); remove(out_fn); rename(tmp_fn, in_fn); remove(tmp_fn); } return 0; }
70,418,840
70,436,462
Initializer list for struct deriving from class (C++)
Can you tell me what is wrong in the following example? I am using C++17, where I thought the following should be supported. class Base { public: virtual ~Base() = default; }; struct Derived : public Base { int m1; }; int main() { /* Results in a compilation error * error C2440: 'initializing': cannot convert from 'initializer list' to 'Derived' * message : No constructor could take the source type, or constructor overload resolution was ambiguous */ Derived d{ {},1 }; return 0; }
It does not work because Derived is not an aggregate since it has a base class with virtual members. The code compiles and runs when removing the virtual destructor in Base and using C++17. If Base requires a virtual destructor, Derived can implement a custom constructor allowing initialization using curly brackets. class Base { public: virtual ~Base() = default; }; struct Derived : public Base { Derived(int m): m1(m) {} int m1; }; int main() { Derived d{ 1 }; return 0; }
70,418,894
70,418,996
Is there a way to merge / concatenate precompiler lists with C++ macros?
I have two lists: #define LIST1 {1, 2, 3} #define LIST2 {4, 5, 6} and using C++ macros I would like to write something like this: // Obviously doesn't work #define MERGE LIST1 ## LIST2 int my_array[] = MERGE; to yield: int my_array[] = {1, 2, 3, 4, 5, 6}; during compile-time. Is something like this possible? There are other questions concerning this with strings, however I can't figure out for the life of me how to do this with non-string array declarations. Edit: I certainly would prefer to not use macros, and would prefer that the list format be different as well. Unfortunately, the header file that contains these list definitions isn’t a file that I can edit.
Don't use macros unless there is no other option, prefer templates. They are typesafe. For example you can make a compile time evaluated function (constexpr) that merges two lists (arrays) and returns an array. #include <array> // type_t is the type held by the array (an int in this example) // N = size of first array // M = size of second array // const type_t(&arr)[N] is the syntax for passing an array by const reference template<typename type_t, std::size_t N, std::size_t M> constexpr auto merge(const type_t(&arr1)[N], const type_t(&arr2)[M]) { std::array<type_t, N + M> arr{}; // this initialization is needed in constexpr std::size_t index{ 0 }; for (const auto& value : arr1) arr[index++] = value; for (const auto& value : arr2) arr[index++] = value; return arr; } int main() { constexpr auto arr = merge({ 1,2,3 }, { 4,5,6 }); constexpr auto strings = merge( {"abc", "def" }, {"ijk", "lmn"} ); // static_assert is like assert, but evaluated at compile time. static_assert(arr.size() == 6); static_assert(arr[4] == 5); return 0; }
70,418,924
70,458,361
View creation works in Firebird 3.0 but not in version 4.0
I created a music database application a few years ago in C++ (Code::Blocks + wxWidgets + SQLAPI++) and Firebird as the database server (running as a service in classic mode) on the Windows platform (v10). It creates a SQL database with tables, views, triggers, generators. So far, it has been running perfectly up to Firebird 3 (Latest version). Now Firebird 4.0 is out, I thought I try it out. In order to narrow down on the problem, I created a new app that only creates the database, tables, triggers, generators,and only 2 views which are focused around the problem area. The code for vew_AlbumDetails I use in my test app is: CREATE VIEW vew_AlbumDetails (Album_Name, Album_NrSeconds) AS SELECT b.Album_Name, SUM(a.NumberOfSamples/NULLIF(b.SampleRate,-1)) FROM tbl_Tracks a INNER JOIN tbl_AlbumNames b ON a.AlbumName_ID = b.ID GROUP BY b.Album_Name ORDER BY b.Album_Name; The code for vew_ReportDetails I use in my test app is: CREATE VIEW vew_ReportDetails (Album_Name, Album_NrSeconds) AS SELECT b.Album_Name, a.NumberOfSamples/NULLIF(b.SampleRate,-1) FROM tbl_Tracks a INNER JOIN tbl_AlbumNames b ON a.AlbumName_ID = b.ID ORDER BY b.Album_Name; When I create the database with Firebird 3 running as a service, and open it in FlameRobin, everything is OK. In VIEW vew_AlbumDetails, Album_NrSeconds type is BIGINT. (see image below) When I create the database with Firebird 4 running as a service, and open it in FlameRobin, everything is NOT OK. In VIEW vew_AlbumDetails, Album_NrSeconds type is (16). (see image below) In VIEW vew_ReportDetails, Album_NrSeconds type is BIGINT. This is OK (see image below) In FlameRobin, I also manually added a new view (vew_Manual_Added_View) with the same code as for vew_AlbumDetails (except for the name). The code is shown in above image. Strange is that the type for Album_NrSeconds is now DOUBLE PRECISION instead of (16) under Firebird 4 service or BIGINT under Firebird 3 service. My problem is the following when running Firebird 4 as a service: My Music app creates the database without errors, but with vew_AlbumDetails, Album_NrSeconds type as (16). It crashes without any error message when the vew_AlbumDetails is being used to show an overview of the stored albums. Album_NrSecondse being of type (16) is causing this. There are 2 things I do not understand when using Firebird 4 as a service. Why is Album_NrSecondse of type (16) when creating vew_AlbumDetails with my app? Why is Album_NrSecondse of type (Double Precision) when the exactly same code is used for adding a view manually? Is there a bug in Firebird 4.0 that causes this strange behaviour?, or do I need to adapt my code somehow? I hope somebody can help me understand what causes the different behavior between Firebird 3.0 and 4.0, and sends me on the way to a solution.
I have added 'DataTypeCompatibility = 3.0' to both databases.conf and firebird.conf. The datatype for Album_NrSeconds is now NUMERIC. My application runs flawlessly under Firebird 4.0 as a service after these 2 edits. Thank you Mark Rotteveel for your suggestion. Its much appreciated.
70,420,518
70,420,980
Confusion on return type deduction with unpacking references
The following code #include <functional> #include <tuple> #include <iostream> struct Point { int x; int y; }; decltype(auto) memrefs(Point &p) { return std::make_tuple(std::ref(p.x), std::ref(p.y)); } int main() { Point p; auto& [x, y] = memrefs(p); x = 1; y = 2; std::cout << p.x << " " << p.y << std::endl; return 0; } does not compile. Reported by GCC 8.1.0: error: cannot bind non-const lvalue reference of type 'std::tuple<int&, int&>&' to an rvalue of type 'std::tuple<int&, int&>' However, it will compile if I change auto& [x, y] = memrefs(p); to auto [x, y] = memrefs(p) My question is why? Aren't x and y references?
decltype(auto) memrefs(Point &p); is std::tuple<int&, int&> memrefs(Point &p); In structured_binding, auto& in auto& [x, y] applies to the "tuple", not to x, y. and you cannot have std::tuple<int&, int&>& tup = memrefs(p); but you can have std::tuple<int&, int&> tup = memrefs(p); then x, y refers to the appropriate part of the tuple.
70,420,542
70,420,795
Injecting class into the JNIEnv in android jni
C++ code: extern "C" JNIEXPORT void JNICALL Java_com_example_afl_MainActivity_stringFromJNI( JNIEnv* env, jobject /* this */) { // env->DefineClass(...) } I'm calling the above function from Java side code: public class MainActivity extends AppCompatActivity { static { System.loadLibrary("native-lib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); stringFromJNI(); // call cpp function } public native String stringFromJNI(); } My question is about the env->DefineClass(...) in cpp code. As you see the android VM passes JNIEnv *env to my native function, so by using env pointer i have access to all of my java classes and i can use them (i have access to all of my java side classes and i can create instance object and do everything). But how can access to a class which is in another apk and it is in another package name ? I wanna decompile the target apk and copy that class and inject that class to my env using the env->DefineClass function but i don't know how can i complete this task. Thanks for any reply :)
Impossible. Android does not implement DefineClass: All JNI 1.6 features are supported, with the following exception: DefineClass is not implemented. Android does not use Java bytecodes or class files, so passing in binary class data doesn't work. Even if that worked, your app's user very probably does not have access rights to another applications .apk.
70,420,709
70,420,765
std::fuction calling convention
I've have observer implementation in my code. It looks like this: template <typename... Args> class Event { std::map<size_t, std::function<void(Args...)>> m_observers; mutable std::mutex m_mutex; public: virtual ~Event() = default; [[nodiscard]] size_t Register(const size_t& object_id, std::function<void(Args...)> observer) { std::lock_guard<std::mutex> lk(m_mutex); m_observers[object_id] = observer; return object_id; } I don't add full class code here for brevity. And the code that connects objects: class Object { std::wstring m_name; size_t m_id=0; public: Object() { GenerateID(); } Object(std::wstring name) : m_name(name) { GenerateID(); } virtual ~Object() = default; size_t GetID() const { return m_id; } template <class T, typename... Args> size_t ObjectConnect(void(T::* callback_fn)(Args...args), Event<Args...>* obj_event); template <typename... Args> size_t ObjectConnect(std::function<void> fn(Args...args), Event<Args...>* obj_event); private: void GenerateID(); }; template<class T, typename... Args> size_t Object::ObjectConnect(void(T::* callback_fn)(Args... args), Event<Args...>* obj_event) { auto fn = [this, callback_fn](Args... args)->void {((static_cast<T*>(this))->*callback_fn)(args...); }; return obj_event->Register(m_id, fn); } template<typename ...Args> inline size_t Object::ObjectConnect(std::function<void> fn(Args...args), Event<Args...>* obj_event) { return obj_event->Register(m_id, fn); } First type of ObjectConnect function works perfectly with member functions of child classes. I've added second overload to be able to pass member functions with additional parameters: std::function<void(bool)> fn1 = [this, serverName](bool param) {this->OnServerConnection(serverName.toStdWString(), param); }; ObjectConnect(fn1, Refactoring::Backend::GetManagerByName(serverName.toStdWString())->GetConnectionEvent()); Sadly it gives me next error: Error C2784 'size_t Design::Object::ObjectConnect(std::function<void> (__cdecl *)(Args...),Design::Event<Args...> *)': could not deduce template argument for 'std::function<void> (__cdecl *)(Args...)' from 'std::function<void (bool)>' From error message it seems like it has something to do with calling convention, but I can't figure out what to do and googling haven't given me any clues.
This is unrelated to calling convention: all member functions have the same calling convention in C++ (sometimes called “thiscall”), and std::function<T>::operator() is a member function. Instead, the issue is that your function prototype for a function taking a std::function<T> is incorrect. The signature goes in the template argument list, like so: template <typename... Args> size_t ObjectConnect(std::function<void(Args...)> fn, Event<Args...>* obj_event);
70,420,794
70,420,925
c++ vector [-2] index returns weird value
I'm new to c++ and just learned about vectors. I'm coming from Python, so of course I checked if I could use negative indexing in c++, which did not seem to work. While trying to check if it works, I met a very weird behaviour for negative indexes in different environments. Using negative indexes with the .at() function raises an error but not when using [] brackets. Are these values contents of previous memory locations, or what do they represent? Is this what's called undefined behaviour? Source: #include <iostream> #include <vector> int main() { std::vector<int> numbers = {3, 6, 9, 12, 15}; std::cout << "Length: " << numbers.size() << "\n"; for (int i = 4; i > -5; i--) { std::cout << "Pos " << i << ": " << numbers[i] << "\n"; } } Output: Length: 5 Pos 4: 15 Pos 3: 12 Pos 2: 9 Pos 1: 6 Pos 0: 3 Pos -1: 0 // other env: 201392090 Pos -2: 33 // other env: 475047512 Pos -3: 0 Pos -4: 0
Are these values contents of previous memory locations, or what do they represent? Is this what's called undefined behaviour? No, it's not actually accessing a memory location prior to the beginning of the backing array, but one past the end: If you use numbers [index], the compiler interprets this as numbers.operator[](index), i.e. the member function operator[]() is used. This function takes a parameter of type size_t which is an unsigned integer. The parameter -1 is implicitly converted to a unsigned integer yields a very large number and this number is out of range of values the contract of std::vector covers. Read or write access to such an element is undefined behaviour. at in contrast to operator[]() does compare the parameter to the vector size guaranteeing an exception in this scenario, but with operator[] there's no such "safety net".
70,421,258
70,503,119
How to print actual(derived) object properties in LLDB
Code example: class IA { public: virtual int getA() = 0; }; class A:public IA { public: int getA() override { return m_a; } private: int m_a = 10; }; void main() { A* a = new A(); IA* ia = a; } In GDB with set print object on I can easily print a object contents using ia pointer. //with print object on p *ia $1 = (A) {<IA> = {_vptr$IA = 0xf330c8 <vtable for A+16>}, m_a = 10} //without print object on p *ia $2 = {_vptr$IA = 0xf330c8 <vtable for A+16>} Is it possible to do the same in lldb? I've failed to find anything in official documentation. That's what i get in lldb: p *ia (IA) $0 = {} p *a (A) $1 = (m_a = 10)
lldb has two methods for accessing typed values from the target program, expr (aliased to p) and frame variable (aliased to v). expr is a full expression evaluator that uses the clang front & backends to parse and evaluate the expression you pass it "as if it were inserted into the code at the point where you are stopped". frame var is a C-ish pseudo-language for accessing elements of variables, or registers or memory regions. Then the resultant value from either method is presented through a common system, first by fetching the "dynamic type" of the result (the equivalent of setting 'print object' on), then passing it through the "data formatters" architecture. When processing: (lldb) p *ia the pointer has been dereferenced by the time it is returned as a value from the expression to the "dynamic type" detection stage, which consequently can't tell it really came from a pointer to A. lldb made the choice to have expr follow the rules of the source language as closely as possible, which gets in the way here, but means you can pass quite complex expressions to the command and have them work as they would in code. Among other things, it can do C++ casts, so if you need to have the dynamic type available (e.g. if you want to call a method that's only in the full type) you can do it by hand: (lldb) p ((A *)ia)->some_A_method() gdb's print uses a hand built parser that evaluates expressions from the deepest subexpression out, so it can stop to get the dynamic type of each subexpression as it goes. Doing it that way makes the job of being an accurate C++ parser harder, however. There are always tradeoffs... OTOH, (lldb) v *ia (A) *ia = (m_a = 10) can fetch the dynamic type because the v parser returns an object: "SBValue" for the dereferenced value of the "SBValue" representing the local variable ia - so the result knows where the value came from, and can fetch all the dynamic types along the way in the printing stage. We haven't taught v to do casting or function calling yet - mostly to keep its parser simple and predictable. But otherwise, v is usually more convenient for variable printing than p. When you are just printing local variables, or their children, v is also more efficient, and less fragile, since it only has to realize the value's type and fetch its memory, not emulate the current context well enough to satisfy clang.
70,421,335
70,425,757
How do I convert std::chrono to int
I have been trying to make a wpm counter and, long story short, am running into an issue: After using the high resolution clock, I need to divide it by 12, but I can't convert std::chrono to int. Here is my code: #include <iostream> #include <chrono> #include <Windows.h> #include <synchapi.h> using namespace std; using namespace std::chrono; int main() { typedef std::chrono::high_resolution_clock Time; typedef std::chrono::seconds s; string text; string ctext = "One two three four five six seven eight nine ten eleven twelve"; cout << "Type: "<< ctext << " in" << "\n" << "5" << endl; Sleep(1000); cout << "4" << endl; Sleep(1000); cout << "3" << endl; Sleep(1000); cout << "2" << endl; Sleep(1000); cout << "1" << endl; Sleep(1000); cout << "GO" << endl; auto start = Time::now(); cin >> text; auto stop = Time::now(); float wpm = stop - start / 12; if (ctext == text) { cout << "Correct! WPM: " << wpm; } else { cout << "You had some errors. Your WPM: " << wpm; } } Are there any alternative methods I could also use to using std::chrono for this?
std::chrono will elegantly do this problem with a few minor changes... Instead of Sleep(1000);, prefer this_thread::sleep_for(1s);. You'll need the header <thread> for this instead of <Windows.h> and <synchapi.h>. cin >> text; will only read one word. To read the entire line you want getline(cin, text);. It is easiest to first compute minutes per word stored in a floating point type. To get the total floating point minutes you can just divide the duration by 1.0min. This results in a long double. Then divide that total minutes by 12 to get the minutes per word: . auto mpw = (stop - start) / 1.0min / 12; Then just invert mpw to get words per minute: . float wpm = 1/mpw; In summary: #include <chrono> #include <iostream> #include <thread> using namespace std; using namespace std::chrono; int main() { typedef steady_clock Time; typedef seconds s; string text; string ctext = "One two three four five six seven eight nine ten eleven twelve"; cout << "Type: "<< ctext << " in" << "\n" << "5" << endl; this_thread::sleep_for(1s); cout << "4" << endl; this_thread::sleep_for(1s); cout << "3" << endl; this_thread::sleep_for(1s); cout << "2" << endl; this_thread::sleep_for(1s); cout << "1" << endl; this_thread::sleep_for(1s); cout << "GO" << endl; auto start = Time::now(); getline(cin, text); auto stop = Time::now(); auto mpw = (stop - start) / 1.0min / 12; float wpm = 1/mpw; if (ctext == text) { cout << "Correct! WPM: " << wpm << '\n'; } else { cout << "You had some errors. Your WPM: " << wpm << '\n'; } }
70,421,369
70,421,422
C++ specialized function template alias syntax
I have class ClassA {}; class ClassB {}; auto func_a() -> ClassA { return ClassA(); // example implementation for illustration. in reality can be different. does not match the form of func_b } auto func_b() -> ClassB { return ClassB(); // example implementation for illustration. in reality can be different. does not match the form of func_a } I want to be able to use the syntax func<ClassA>() // instead of func_a() func<ClassB>() // instead of func_b() (this is as part of a bigger template) but I don't know how to implement this template specialization for the function alias. Help? What is the syntax for this? [Edit] The answers posted so far do not answer my question, so I'll edit my question to be more clear. The actual definition of func_a and func_b is more complex than just "return Type();". Also they cannot be touched. So consider them to be auto func_a() -> ClassA { // unknown implementation. returns ClassA somehow } auto func_b() -> ClassB { // unknown implementation. returns ClassB somehow } I cannot template the contents of func_a or func_b. I need the template for func<ClassA|ClassB> to be specialized for each one of the two and be able to select the correct one to call
You might do something like (c++17): template <typename T> auto func() { if constexpr (std::is_same_v<T, ClassA>) { return func_a(); } else { return func_b(); } } Alternative for pre-C++17 is tag dispatching (which allows customization point): // Utility class to allow to "pass" Type. template <typename T> struct Tag{}; // Possibly in namespace details auto func(Tag<ClassA>) { return func_a(); } auto func(Tag<ClassB>) { return func_b(); } template <typename T> auto func() { return func(Tag<T>{}); }
70,421,465
70,421,504
Switching from a 2D vector into a 1D vector
I have heard that a vector of vectors is bad in terms of performance. For example, I have the following 2D std::vector: std::vector< std::vector<char> > characterMatrix; // for iterating for ( int row = 0; row < getY_AxisLen( ); ++row ) { for ( int column = 0; column < getX_AxisLen( ); ++column ) { std::cout << characterMatrix[ row ][ column ]; } } In this approach, the matrix gets printed in 3-12 milliseconds on my system. I would be glad if I saw a decrease of e.g. 1-3 milliseconds. As far as I know, each of the internal vectors (i.e. rows) is stored in a different location on the heap memory. So this causes lots of fragmentation. Not only that but the sizeof(std::vector) in my compiler returns 24 (bytes). So this means that for instance if characterMatrix has 50 rows (aka internal vectors) then it'll allocate 24*50 == 1200 bytes on the heap just to store the control blocks of those 50 vectors and this is in addition to the space taken by the actual data (chars) in the matrix. Now if I want to keep all the chars in a single contiguous block of memory maybe I can write it as a 1D vector like: std::vector< char > characterMatrix; // for iterating for ( int row = 0; row < getY_AxisLen( ); ++row ) { for ( int column = 0; column < getX_AxisLen( ); ++column ) { std::cout << characterMatrix[ row * getX_AxisLen( ) + column ]; // is this correct? } } Is this a valid way of doing it? Can someone tell me what things should I keep in mind if I want to change the implementation of my matrix variable in such a way? What are the possible downsides?
"have heard" together with performance is never the right approach. To address performance, the golden rule is: Benchmark first! Also, performance isn't always the most important thing. Typically, you should only optimize for performance if you find that your application isn't fast enough for your purposes. Then, follow these steps: First, you need to make sure that the part of the code that you're looking at is actually a performance bottleneck in your application (use a profiler for that). No need to optimize something that takes only 1% of your computation time in total - even if you speed it up by a factor of 10, you would only reduce the overall execution time by 0.9%! If you have discovered that this 2D vector access is indeed the bottleneck, then benchmark it to have a baseline for future experiments. Second, your code needs to be correct. No use in it being fast if it is not doing the right thing after you've optimized it for performance. Here I'd recommend to put tests in place (that is, record the results with the naive/unoptimized approach, so that when you optimize, you know if you still get the same result). Third, performance optimizations tend to negatively affect readability and/or maintanability of your code. However, these can be very important, especially for code parts that are critical to be well understood, or that tend to change a lot. Yes, 2D vectors are an indication that you might have not ideal performance, since as you said, the data is not all in one place. Yet then again, as you do it curently, the computation of indices done on each access inside of innermost loop also is "expensive". So, having your data in one large vector instead of a 2D vector field can be faster; especially if you always have to address all elements anyway and don't need "neighbourhood" access, which means that you can simply have one loop iterating from 0 to what you call getY_AxisLen() * getX_AxisLen(). Having a benchmark in place, as hinted to above, can help you in finding out which optimizations make sense! To address the reduced readability/maintanability, it could be helpful in your case to abstract away the actual data structure used for storing the 2D data, so that the actual implementation of how data is stored is hidden from the places where the data is accessed.
70,421,805
70,422,381
How can I do to keep the value of a variable after a do while loop?
I have been coding a program to simulate a roulette of a casino, thing is that every time I try to repeat the game after is finished I want the game to keep going and the money to be the same, so if you have lost money you start with that certain money, here is the code (It's in Spanish but I think it's pretty clear): #include <cstdlib> #include <ctime> #include <iostream> using namespace std; int num, pri, randum, num2, op, num3 = 10000, col = randum, rep, clear; int main() { do { int num4 = op; cout << "Escoja la opción de la que apostar.\n"; cout << "1 - Apostar a un número. \n2 - Apostar a un color \n"; cout << "Elija opción: "; cin >> pri; cout << " \n"; cout << " \n"; switch (pri) { case 1: { srand(time(0)); randum = rand() % 37 + 1; //si poner 37 + 1 te va cojer números hasta el 37 no? if (num4 != 10000) { cout << "Su saldo actual es " << num3 << " €\n"; } else { cout << "Su saldo actual es 10000 €\n"; } cout << "Ha elegido apostar a un número\n"; cout << "Introduzca el dinero que quiere apostar -->\n"; cin >> num; cout << "Ahora introduzca el número que desee entre el 0 y 36 -->\n"; cin >> num2; if (num2 == randum) { op = num3 + num; cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << op << " €\n"; } else { op = num3 - num; cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << op << " €\n"; cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n"; cin >> clear; if (clear == 1) {} else if (clear == 2) { cout << "Bien, suerte en la próxima tirada.\n\n"; } } break; } case 2: { if (num3 == 10000) { cout << "Su saldo actual es 10000 €\n"; } else { cout << "Su saldo actual es " << num3 << " €\n"; } cout << "Ha elegido apostar a un color\n"; cout << "Introduzca el dinero que quiere apostar -->\n"; cin >> num; srand(time(0)); randum = rand() % 2 + 1; cout << "Ahora escoja rojo (1) o negro (2) -->\n"; cin >> col; if (col == randum) { op = num3 + num; cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << op << " €"; } else { op = num3 - num; cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << op << " €"; } cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n"; cin >> clear; if (clear == 1) {} else if (clear == 2) { cout << "Bien, suerte en la próxima tirada.\n\n"; } } } } while (clear == 1); return 0; }
So, it should be pretty easy to do that. Initialize the starting amount outside the loop before the betting begins. At the end of the loop, ask if user wants to bet more. Would that work for you? Or do you need it to be initialized when you start the code itself? You could use static I am just changing a few things from your code: #include <cstdlib> #include <ctime> #include <iostream> using namespace std; int main() { int money = 10000, bet_amount = 0, clear, pri; cout << "Su saldo inicial es " << money << " €\n"; do { cout << "Escoja la opción de la que apostar.\n"; cout << "1 - Apostar a un número. \n2 - Apostar a un color \n"; cout << "Elija opción: "; cin >> pri; cout << " \n"; cout << " \n"; cout << "Introduzca el dinero que quiere apostar -->\n"; cin >> bet_amount; switch (pri) { case 1: { int number_chosen = -1, randum; cout << "Ahora introduzca el número que desee entre el 0 y 36 -->\n"; cin >> number_chosen; srand(time(0)); randum = rand() % 37; // This will give result in the range 0 - 36 if (randum == number_chosen) { money += bet_amount; cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << money << " €\n"; } else { money -= bet_amount; cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << money << " €\n"; } break; } case 2: { int color = 0, randcol; cout << "Ahora escoja rojo (1) o negro (2) -->\n"; cin >> color; srand(time(0)); randcol = rand() % 2 + 1; if (randcol == color) { money += bet_amount; cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << money << " €\n"; } else { money -= bet_amount; cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << money << " €\n"; } break; } default: break; } cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n"; cin >> clear; if (clear == 2) { cout << "Bien, suerte en la próxima tirada.\n\n"; } } while (clear == 1); cout << "Tu saldo final es " << money << " €\n"; return 0; } It took me a while to figure out the code because I had to use google translate
70,421,874
70,422,461
How to convert a char* to a char array
I'm receiving some data over serial of variable names and values in char. The variable name gets stored in an array pointed to by the char*. I'm trying to compare the char array data I received, to several other char arrays so I can determine which variable I have received data for. How can I convert the char* to a char array, so I can compare it to other arrays, for example by using the strcmp function? Basically the serial data gets fed into an array and processed by this function: void process(char *message) { char *name = strsep(&message, " "); // split at the space if (!message) { Serial.println("Error: no value given"); return; } char *endp; // end of the numeric value long value = strtol(message, &endp, 0); if (endp == message) { Serial.println("Error: could not parse value"); return; } // Successfully parsed. char namestr[] = name; if (strcmp(&namestr, &var1str) == 0) { Serial.print(name); Serial.print(" received value "); Serial.println(value); } } However, when I try char namestr[] = name; I get the following error: initializer fails to determine size of 'namestr'
As @stark mentioned in comment, you just can pass name to the strcmp() function. A char array is internally just a char pointer char *
70,422,421
70,422,452
Creating vector of class with parametrized constructor
I am trying to create a vector of a class with parametrized constructor. #include <iostream> #include <vector> using namespace std; struct foo { foo() { cout << "default foo constructor " << endl; } foo(int i) { cout << "parameterized foo constructor" << endl; } ~foo() { cout << "~foo destructor" << endl; } }; int main() { std::vector<foo> v(3,1); } I was expecting that there would be 3 calls to the parameterized foo constructor but instead I get the output as parameterized foo constructor ~foo destructor ~foo destructor ~foo destructor ~foo destructor What is happening here ? How can I use constructor of vector such that objects of class get created with parametrized constructor?
What is happening here ? You can add a user defined copy constructor to see what happens in your code: #include <iostream> #include <vector> struct foo { foo() { std::cout << "default foo constructor\n"; } foo(int i) { std::cout << "parameterized foo constructor\n"; } ~foo() { std::cout << "~foo destructor\n"; } foo(const foo&) { std::cout << "copy constructor called\n"; } // <--- }; int main() { std::vector<foo> v(3,1); } Output: parameterized foo constructor copy constructor called copy constructor called copy constructor called ~foo destructor ~foo destructor ~foo destructor ~foo destructor From cppreference on the std::vector constructor you are calling: Constructs the container with count copies of elements with value value. So... How can I use constructor of vector such that objects of class get created with parametrized constructor? The elements are created by calling the copy constructor. However, it is only called once, then the vector is filled with copies.
70,423,351
70,426,260
Why override operators aren't working with pointer?
I need to write a class Matrix with override operators + - * = and I've got some code that is works, but there is error. //Matrix.h template <class T> class Matrix { public: Matrix(int rows, int columns); Matrix(const Matrix<T> &m); Matrix<T>& operator=(Matrix<T>& m); Matrix<T> operator+(Matrix<T>& m) const; Matrix<T>* operator*(Matrix<T>* m); }; template <class T> Matrix<T>& Matrix<T>::operator*(Matrix<T>& m) { Matrix<T>* newMatrix = new Matrix<T>(rowCount, m.colCount); for (int i = 0; i < rowCount; ++i) { for (int j = 0; j < m.colCount; ++j) { newMatrix->data[i][j] = 0; for (int k = 0; k < colCount; ++k) newMatrix->data[i][j] += data[i][k] * m.data[k][j]; } } return *newMatrix; } And override operators work fine in this code Matrix<int> matrix(2, 2); matrix = matrix + matrix; //and other operators work fine here But here it gives an error during compilation Matrix<int>* matrix = new Matrix<int>(2, 2); matrix = matrix + matrix; matrix = matrix * matrix; //etc error error C2804: binary "operator +" has too many parameters
Type information is crutal in C++. This: Matrix<int> matrix(2, 2); matrix = matrix + matrix; Here the type of matrix is Matrix. You have defined what the operator + for the type Matrix so this works fine. This second one is different: Matrix<int>* matrix = new Matrix<int>(2, 2); matrix = matrix + matrix; Here the type of matrix is Matrix*. Notice the star on the end of Matrix (this makes it a Matrix Pointer). This is a different type than above. You have not defined what operator + does for Matrix* so the compiler looks at its default operations and finds something close but not exact enough and generates an appropriate error message that tries to help. To use the operator + you defined above you need to make sure the types of the values are Matrix and NOT Matrix*. You can covert a Matrix* into a Matrix by dereferencing the pointer via operator *. Matrix<int>* matrix = new Matrix<int>(2, 2); (*matrix) = (*matrix) + (*matrix); Here: (*matrix) dereferences the Matrix* object and you get a Matrix. This can now correctly be applied to the operator + you defined above. But saying all that. That explains whay your problem is, but I don't think you actually want (or need) to use new in this context. Dynamically allocating memory like this is probably not the correct way to implement this. It is usually better to use automatic variables (as this makes memory management easier). template <class T> Matrix<T> Matrix<T>::operator*(Matrix<T>& m) // I also removed the & from the return value // So that the value is copied out of the function. // because with dynamic allocation the result will disappear // after the function exits. // Note: Though the matrix may be officially copied out // the compiler is likely to optimize away this copy. // and when you upgrade your class with move semantics // then it will definitely be moved. { Matrix<T> newMatrix(rowCount, m.colCount); // Remove the Pointer from the above line. // And fix the -> into . in the code below. for (int i = 0; i < rowCount; ++i) { for (int j = 0; j < m.colCount; ++j) { newMatrix.data[i][j] = 0; for (int k = 0; k < colCount; ++k) newMatrix.data[i][j] += data[i][k] * m.data[k][j]; } } return newMatrix; // Now you can remove the * from the return value. // The code works exactly the same. // But you have not leaked the memory you allocated with `new` }
70,423,353
70,427,545
How iteration over parameter pack going through initializer_list?
Sorry for being vague with my question, but I just don't understand what does this function does and how. Code from here: template<typename ... T> auto sum (T ... t) { typename std::common_type<T...>::type result{}; //zero-initialization? (void)std::initializer_list<int>{(result += t, 0)...}; //why 0 is here return result; } I don't know why but this piece of code seems so odd, it don't look like C++ to me. Semantically, this function sums all the parameters in a result variable, obviously. But I completely do not understand why it was written that way. Using initializer_list here seem like a trick to trigger iteration over arguments in parameter pack but still... Why initializer_list is explicitly was cast to void? To not take up extra memory? And how iteration over parameter pack is going? Why not for example (void)std::initializer_list<int>{(result += t)...}; (it does not compile by the way).
Thanks to the comments, I figured out the answer. I haven't ever come across comma operator, so the line (result += t, 0) made to me no sense until your comments about EXISTENCE of comma operator and this question. So basically we initializing our list with zeros. And since I made type of initializer_list for integers, I can't write (void)std::initializer_list<int>{result += t...}, since returning value of result += t is int& not int. So why don't we write (void)std::initializer_list<int&>{result += t...}? It doesn't compile, and I suspect that because array of references is forbidden in C++. So here's the solution to my problem: template <typename ... T> auto sum1(T ... t) { std::common_type_t<T...> tmp{}; std::initializer_list<std::reference_wrapper<std::common_type_t<T...>>>{tmp += t...}; return tmp; }
70,423,468
70,424,919
How do you check how many times each digit from 0 - 9 appears in an input number
I just can't seem to come up with a way to go about this problem. I've been searching online for logic for this but no luck. One way would be to store the number in an array then comparing each value of the array but in this case your only limited to enter a limited amount of digits because of the size of the array and all. pls help! EDIT: Thanks for the suggested question but unfortunately I was too dumb to understand how it worked by just looking at the code :( I'm here to learn how to actually do this which is why I need explanations on doing it that way and I couldn't find any explanations there. Not to mention it was C code :p. EDIT 2: I finally get it. After reading through what @rturrado said several times and wrecking my brain to actually make sense of this. After that I did a couple random numbers with that method. Now that I finally know how to go through each digit in an integer, I can finally go about checking the frequency by using a loop for each digit from 0 - 9. In this loop I'd run through the whole integer number for each iteration and plus one to a variable each time each time any digit in the number is equal to the outer loop variable. Annnd.....I'm just gonna leave this here incase another poor sod like me comes around trying to make sense of things :)
I understand that you would like to have an explanation and not just a code dump or some comments. So, let me try to explain you. As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a 5*10^0 + 4*10^1 + 3*10^2 + 2*10^3 + 1*10^4. Or, we can write: number = 0; number = number + 1; number = number * 10; number = number + 2; number = number * 10; number = number + 3; number = number * 10; number = number + 4; number = number * 10; number = number + 5; That is nothing new. But it is important to understand, how to get back the digits from a number. Obviously we need to make an integer division by 10 somewhen. But this alone does not give us the digits. If we perform a division o 12345 by 10, then the result is 1234.5. And for the intger devision it os 1234 with a rest of 5. And now, we can see that the rest is the digit that we are looking for. And in C++ we have a function that gives us the rest of an integer division. It is the modulo operator %. Let us look, how this works: int number = 12345; int digit = number % 10; // Result will be 5 // Do something with digit number = number / 10; // Now number is 1234 (Integer division will truncate the fraction) digit = number % 10; // Result is now 4 // Do something with digit number = number / 10; // Now number is 123 (Integer division will truncate the fraction) digit = number % 10; // Result is now 3 // Do something with digit number = number / 10; // Now number is 12 (Integer division will truncate the fraction) digit = number % 10; // Result is now 2 // Do something with digit number = number / 10; // Now number is 1 (Integer division will truncate the fraction) digit = number % 10; // Result is now 1 number = number / 10; // Now number is 0, and we can stop the operation. And later we can do all this in a loop. Like with int number = 12345; while (number > 0) { int digit = number % 10; // Extract next digit from number // Do something with digit number /= 10; } And thats it. Now we extracted all digits. Next is counting. We have 10 different digits. So, we could now define 10 counter variables like "int counterFor0, counterFor1, counterFor2 ..... , counterFor9" and the compare the digit with "0,1,2,...9" and then increment the related counter. But that is too much typing work. But, luckily, we have arrays in C++. So we can define an array with 10 counters like: int counterForDigit[10]. OK, understood. You remember that we had in the above code a comment "// Do something with digit ". And this we will do now. If we have a digit, then we use that as an index in our array and increment the related counter. So, finally. One possible solution would be: #include <iostream> int main() { // Test number. Can be anything int number = 12344555; // Counter for our digits int counterForDigits[10]{}; // The {} will initialize all values in the array with 0 // Extract all digits while (number > 0) { // Get digit int digit = number % 10; // Increment related counter counterForDigits[digit]++; // Get next number number /= 10; } // Show result for (int k = 0; k < 10; ++k) std::cout << k << " : " << counterForDigits[k] << '\n'; } If you do not want to show 0 outputs, then please add if (counterForDigits[k] > 0) after the for statement. If you should have further questions, then please ask
70,423,627
70,424,478
C++ return new instance of object from dictionary
How to achieve something like this in C++? I'd like some method to return instances of object based on provided string. I suspect map might be solution but I don't know how to pass method to it? class Container { dictionary = { A: () => new A(), B: () => new B(), C: () => new C(), }; method(choice: string): Parent { return this.dictionary[choice]; } } class Parent {} class A extends Parent {} class B extends Parent {} class C extends Parent {}
I can propose the following solution: a base class: class Base { } a factory singleton: class Factory { public: static Factory &instance() { static Factory inst; return inst; } bool Register(const std::string &name, CreateCallback funcCreate) { m_classes.insert(std::make_pair(name, funcCreate)); } Base* CreateInstance(const std::string &name) { auto it = m_classes.find(name); if(it != m_classes.end()) { return it->second(); } return nullptr; } private: using CreateCallback = Base *(*)(); std::map<std::string, CreateCallback> m_classes; } #define CLASS_IMPL(T) Base *T::CreateMethod() { return new T(); } #define REGISTER_CLASS(T,N) bool T::m_registered = Factory::instance().Register(N, &T::CreateMethod);\ CLASS_IMPL(T) #define CLASS_DECL protected: \ static Base *CreateMethod(); \ static bool m_registered; \ usage: class declaration: class A: public Base { CLASS_DECL public: A(){} } class definition: REGISTER_CLASS(A, "A"); A::A() : Base() { } create other classes in such manner. usage: Base* a = Factory::Instance().CreateInstance("A"); This is Factory implementation and so a kind of a "self registration" pattern.
70,423,691
70,423,854
C++ access statically allocated objects' members
So I am trying to understand the state of the memory when I run the below code. From my understanding, the two sub-trees left and right that are initialized within the if-statement should be considered non-existent once the if-block ends. However, when I run this code, the output from within the if-block is the same as the output after the if-block. I thought this might be due to the system not actually removing what is allocated, instead simply updating a static memory pointer. So I allocate a large array in hopes of this overwriting anything that could potentially still exist after the if-block. However, this doesn't seem to have any effect on the output. When I instead call the test function, on returning to main, the access to the sub-trees' val members outputs some random value. This is in line with what I would expect. Could someone either explain what is happening. Why does a block not seem to delete any locally allocated memory, while a function does appear to? #include<iostream> using namespace std; class Tree { public: Tree(int init_val) : val{init_val} {}; Tree() = default; Tree* left = nullptr; Tree* right = nullptr; int val; }; void test(Tree* const tree) { Tree left(10); Tree right(20); tree->left = &left; tree->right = &right; cout << "inside function:" << endl; cout << "left = " << tree->left->val << endl; cout << "left = " << tree->right->val << endl; } int main(int argc, char const *argv[]) { Tree root; int input; cin >> input; if(input > 10) { Tree left(10); Tree right(20); root.left = &left; root.right = &right; cout << "inside if-statement:" << endl; cout << "left = " << root.left->val << endl; cout << "left = " << root.right->val << endl; } int arr[1000000]; //test(&root); cout << "outside test and if-block:" << endl; cout << "left = " << root.left->val << endl; cout << "left = " << root.right->val << endl; \ }
Suppose you own a plot of land and bury a body in it. Later you sell the land to someone else. Then you remember the body and freak out, so you go back and dig it up in the night. Luckily for you, it's still there. Yes, you were trespassing, and there was no guarantee you'd find it, but since the new owner hadn't done anything yet to their land, it was still intact.
70,424,014
70,424,239
Building boost for different versions of Visual Studio
I have Visual Studio 2019 and 2022 installed. I want to build boost libraries for 2019 vc142. How do I build vc142 libs instead of vc143? My current method for building is as follows. I'm using Developer Command Prompt for 2019, and running the following, bootstrapper.bat b2.exe install --prefix=MY_PATH Unfortunately the output lib files are all vc143. I've also tried commenting out IF "%1"=="vc143" SET TOOLSET=msvc : 14.3 in bootstrap.bat with no success. One of the first outputs when running bootstrap.bat is Found with vswhere C:\Program Files\Microsoft Visual Studio\2022\Community. I suspect this could be the problem
adding toolset=msvc-14.2 to the b2.exe builds the correct version. b2.exe install --prefix=MY_PATH toolset=msvc-14.2
70,424,038
70,424,154
Compiler warning for statement on same line as #endif
Consider code: #include <stdio.h> int main() { int a = 4; #if 1 printf("Hello world\n"); #endif a++; printf("a is %d\n", a); } Inadvertently, statement a++; is on the same line as a #endif and is not evaluated. As a result, the final output is: Hello world a is 4 On x86-64 clang 12, this is captured as a warning with using option -Wextra-tokens. See here. I tried compiling this on Visual Studio 2019 MSVC, with command line options: /JMC /permissive- /ifcOutput "Debug\" /GS /analyze- /W3 /Zc:wchar_t /I"../include/" /ZI /Gm- /Od /sdl /Fd"Debug\vc142.pdb" /Zc:inline /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /FC /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\windows.pch" /diagnostics:column There is no warning of any sort on compilation. Is there a setting that can be passed to the compiler in MSVC that detects extra tokens? Edited to add: As answered by user Nathan Pierson, it was indeed option /Za that worked. It does not seem to be on by default. I was also unable to use the Visual Studio Project Properties dialog to find out the option to set. Yet, one can feed in extra options manually thus:
There's compiler warning C4067. It looks like you need to set the flag /Za for it to apply to #endif directives. In the Visual Studio properties page, this flag is controlled by the setting "Disable Language Extensions" in the Language subsection of the C/C++ section.
70,424,070
70,424,264
What is wrong with below C++ regex code to extract names and value?
#include <iostream> #include <regex> using namespace std; int main() { string s = "foo:12,bar:456,b:az:0,"; regex c("(.*[^,]):([0-9]+),"); smatch sm; if(regex_search(s, sm, c)) { cout << "match size:"<<sm.size()<<endl; for(int i=0; i < sm.size();i++){ cout << "grp1 - " << sm[i] << "\tgrp2 - " << sm[i+1] << endl; } } return 0; } I wanted to extract names and corresponding value, I wrote following code but I get following output match size:3 grp1 - foo:12,bar:456,b:az:0, grp2 - foo:12,bar:456,b:az grp1 - foo:12,bar:456,b:az grp2 - 0 grp1 - 0 grp2 - I expected it to be following match size:3 grp1 - foo, grp2 - 12 grp1 - bar grp2 - 456 grp1 - b:az grp2 - 0
You confuse multiple match extraction with capturing group values retrieval from a single match (yilded by the regex_search function). You need to use a regex iterator to get all matches. Here, match size:3 means you have the whole match value (Group 0), a capturing group 1 value (Group 1, the (.*[^,]) value) and Group 2 value (captured with ([0-9]+)). Also, the .* at the start of your pattern grabs as many chars other than line break chars as possible, so you actually can't use your pattern for multiple match extraction. See this C++ demo: #include<iostream> #include<regex> using namespace std; int main() { string s = "foo:12,bar:456,b:az:0,"; regex c("([^,]+?):([0-9]+)"); int matches = 0; smatch sm; sregex_iterator iter(s.begin(), s.end(), c); std::sregex_iterator end; while(iter != end) { sm = *iter; cout << "grp1 - " << sm[1].str() << ", grp2 - " << sm[2].str() << endl; matches++; ++iter; } cout << "Matches: " << matches << endl; } Output: grp1 - foo, grp2 - 12 grp1 - bar, grp2 - 456 grp1 - b:az, grp2 - 0 Matches: 3 The regex - see its demo - matches ([^,]+?) - Group 1: one or more chars other than a comma, as few as possible : - a colon ([0-9]+) - Group 2: one or more digits. See the regex demo.
70,424,212
70,484,957
C++ MFC reading Cstring from editbox for file reading (std::filesystem Exception unhandled memory problem)
What my code is suppose to achieve is to read in the file names after given a file path input and output (switch 1: the files under the same folder)(switch 2: all the file names under the directory including sub-directories), and to not store the folder names into vector (1.png 2.png 3.png but not ChildFolder). If you need extra information regarding the folder structures it is provided in my previous question. #define IDC_RADIO1 1000 #define IDC_RADIO2 1001 #define IDC_EDIT1 1002 #define IDC_BUTTON1 1003 #define IDC_LIST1 1004 This window app have 2 radiobox, 1 editbox for user to input path name, 1 button to start the whole process, and 1 listbox to display the files read Main function starts below: void CMFCApplication3Dlg::OnBnClickedButton1() { string a; vector<string> caseOne, caseTwo; The bottom two lines of code is where I have issues The a = "C:\Users\User... code works but the output seems to have a array element logic problem going on where the output in the listbox is Nothing,1.png,2.png instead of 1.png,2.png Edit Note :this part works now The code directory_iterator list(str); seems to have a memory problem caused by a = enterPath.GetBuffer(); and I don't know what to do to fix it. ErrorMessage Unhandled exception at 0x7525B502 in MFCApplication3.exe: Microsoft C++ exception: std::filesystem::filesystem_error at memory location 0x0133E438. The screen shot is provided below I would ideally delete a = "C:\Users\User... and use a = enterP.. if it works a = "C:\\Users\\User\\Desktop\\ParentFolder";//This line is used to test code, will move on to having user input to IDC_EDIT1 //a = enterPath.GetBuffer();//Code I want to use path str = a; directory_iterator list(str); CListBox* listBox = (CListBox*)GetDlgItem(IDC_LIST1); UpdateData(TRUE);//update the data int checkRadio = GetCheckedRadioButton(IDC_RADIO1, IDC_RADIO2); switch (checkRadio) { case IDC_RADIO1: list = directory_iterator(a); //reset directory_iterator evertime button clicked to read new file for (auto& it : list) { //go through the directory_iterator list string filename1 = it.path().filename().string(); //get file names then convert filename into string format if (filename1.find(".") < filename1.length()/*or != string::npos*/ ) { // find file name to rule out folders cause files contain '.' caseOne.push_back(filename1); //putting the filenames into the vector CString fileunderPath; //bottom 3 lines of code convert string to CString fileunderPath = filename1.c_str(); listBox->AddString(fileunderPath); } } break; //same problem that should be resolved if case 1 is fixed case IDC_RADIO2://NOTE: NEED TO ADD CLEAR LISTBOX FUNCTION and vector list = directory_iterator(a); for (auto& dirEntry : recursive_directory_iterator(a)) { string filename2 = dirEntry.path().filename().string(); if (filename2.find(".") != string::npos) { // find file name to rule out folders cause files contain '.' caseTwo.push_back(filename2); } } break; } UpdateData(FALSE);//finish updating the data } Edit: This is what I want to achieve(UI screenshot) Working version where I predetermine the folder path for user This is what I want user to enter Error message I got What the folder content looks like A child folder of the parent folder The complete code of button 1 I also found a new bug I didn't notice before,The output is png.1 png.2 instead of 1.png 2.png, this should not have happened since I made it work without problem when I used cout<<; a while back Working version where I predetermine the folder path for user
After some research,I changed my code and finally got it working //Answer string a; CString stri;//Read text from edit control box and convert it to std::string GetDlgItem(IDC_EDIT1)->GetWindowText(stri); a = CT2A(stri); //This code is something I also tried but the string a it passed back is "" /*CString b; b = enterPath;//a control variable I added from IDC_EDIT1 a = CT2A(b);*/ Regarding the filename1.find(".") < filename1.length() it works becasue find() passes back the first location of the find character so < filename1.length() means the return of the find() cannot be longer than the string it self, and when nothing is found it returns -1 the if statement still runs but passes nothing to the AddString.(That why it felt like a band aid fix) So the better way to write the if statement is either if(filename1.find(".") != -1) //or if(filename1.find(".") != string::npos)//npos is -1 and since I found a better way to distinguish file names from folder in the #include filesystem, I ended up deleting the code above anyway because for some reason I thought folder names can't have"." in them //code I switched to if(is_regular_file(it))
70,424,243
70,424,438
How to use the return value from one function in another in C++
Is it possible to use the return value from one function in another? The code is something like this: double process () { //doing something return result; } double calculation () { double sum = 0; sum = result + 10; //Want to use the result from the previous function here return sum; } Thanks!
You have two options - you could store the return value in a variable and then use that variable, or you can use the function call directly. Store in a variable like this - double sum = 0, result = process(); sum = result + 10; or use the call directly like this - double sum = 0; sum = process() + 10;
70,424,244
70,424,509
there is a problem in this code its deleting everything in cur->calendar linked list not just the one in the condition
I tried everything and i have no idea what to do now so any help is appreciated! void DeleteAtPosition(Appointment* head, int pos) { Appointment* cur = head->next; Appointment* prev = head; int i = 1; if (isEmptylist(head)) { cout << "LIST IS EMPTY" << endl; } if (pos == 0) { delete head; head = cur; } while (i < pos && cur->next != NULL) { cur = cur->next; prev = prev->next; i++; } prev->next = cur->next; delete cur; } void cancel(Company* c, string title) { Employee* cur = c->head; Appointment* curr=cur->Calendar; int pos = 0; while (cur != NULL) { while (cur->Calendar != NULL) { if (cur->Calendar->Title == title) { DeleteAtPosition(curr, pos); } pos++; cur->Calendar = cur->Calendar->next; } cur = cur->next; } } I think the problem is in the cancel fucntion not the delete one but I have no idea how to solve it
The problem is that you are doing cur->Calendar = cur->Calendar->next;. You are moving the original pointer over the list, so at the end of the inner while loop, cur->Calendar going to be null. You should instead use the curr variable to go over the list like this: void cancel(Company* c, string title) { Employee* cur = c->head; int pos = 0; while (cur != NULL) { Appointment* curr=cur->Calendar; // reset curr pointer in every iteration while (curr != NULL) { // use the curr pointer to go over the list if (curr->Title == title) { // check the title of the current appointment with the "curr" pointer DeleteAtPosition(cur->Calendar, pos); // use the original pointer as the head of the list for deletion } pos++; curr = curr->next; // move the "curr" pointer to the next element of the list } cur = cur->next; } }
70,424,260
70,424,535
I am very much new at coding in c++ i can not setup vs code giving error
I am very much new at coding in c++. I am following code with harry youtube channel for coding. in the first video vs code installation setup I followed every step he did in the same but in my vs code,it is displaying an error. see in image image
I think your code is not saved. Do Ctrl+S and then try running it again.
70,424,379
70,425,013
What does the PACKED keyword mean in Android aosp?
When I read some C++ code in the Android aosp, I see some classes are declared with a PACKED keyword. For example, in <android_source_root>/art/runtime/image.h, a class ImageSection is declared this way: class PACKED(4) ImageSection { public: ImageSection() : offset_(0), size_(0) { } ImageSection(uint32_t offset, uint32_t size) : offset_(offset), size_(size) { } ImageSection(const ImageSection& section) = default; ImageSection& operator=(const ImageSection& section) = default; What does the PACKED(4) mean?
It is defined in <android_source_root>/art/libartbase/base/macros.h #define PACKED(x) __attribute__ ((__aligned__(x), __packed__))
70,424,712
70,448,182
Call C++ Hello World from Julia
I have a C++ program that parses a binary file and outputs a std::string. I would like to call this function directly from Julia and convert the steam into a DataFrame. I need it to work in Linux and Windows. Currently, I have the program write the output to a text file, and then I read it into Julia. Cxx is no longer supported, and trying to get CxxWrap to work has been an exercise in frustration. Toy Problem: If someone could show me how to call the code below from Julia, that would be awesome. // the example from https://github.com/JuliaInterop/CxxWrap.jl #include <string> std::string greet() { return "hello, world"; }
There's a new package which might fit your needs here: https://github.com/eschnett/CxxInterface.jl It is intended as a successor to Cxx.jl and more stable, so I'd recommend giving it ago although I haven't tried it myself!
70,425,047
70,425,241
How to remove an item of Vectors c++
i have this code and i want to find a word in my vector and delete the item that includes that word but, my code will delete from the first line until the item that i want, how can i fix that? std::string s; std::vector<std::string> lines; while (std::getline(theFile, s)) { lines.push_back(s); } //finding item in vector and changing it for (unsigned i = 0; i < lines.size(); i++) { std::size_t found = lines[i].find(name); if (found != std::string::npos) { lines.erase(lines.begin() + i); } } Update 1: this is my full Code: I'm opening a file that contains some elements in this format ( David, 2002 , 1041 , 1957 ) ( cleve, 2003 , 1071 , 1517 ) ( Ali, 2005 , 1021 , 1937 ) i'm getting a user input and finding the line that contains it. then i want to remove that line completely so i import it to a vector and then i can't modify it #include <iostream> #include <string> #include <vector> #include <stream> #include <algorithm> using namespace std; using std::vector; int main(){ string srch; string line; fstream Myfile; string name; int counter; Myfile.open("Patientlist.txt", ios::in | ios::out); cout <<"Deleting your Account"; cout << "\nEnter your ID: "; cin.ignore(); getline(cin, srch); if (Myfile.is_open()) { while (getline(Myfile, line)) { if (line.find(srch) != string::npos) { cout << "\nYour details are: \n" << line << endl; } break; } } else { cout << "\nSearch Failed... Patient not found!" << endl; } Myfile.close(); ifstream theFile("Patientlist.txt"); //using vectors to store value of file std::string s; std::vector<std::string> lines; while (std::getline(theFile, s)) { lines.push_back(s); } //finding item in vector and changing it for (unsigned i = 0; i < lines.size(); i++) { std::size_t found = lines[i].find(name); if (found != std::string::npos) { lines.erase(lines.begin() + i); } } //writing new vector on file ofstream file; file.open("Patientlist.txt"); for (int i = 0; i < lines.size(); ++i) { file << lines[i] << endl; } file.close(); cout << "Done!"; }
The erasing loop is broken. The proper way is to use iterators and use the iterator returned by erase. Like so: // finding item in vector and changing it for (auto it = lines.begin(); it != lines.end();) { if (it->find(name) != std::string::npos) { it = lines.erase(it); } else { ++it; } } Or using the erase–remove idiom: lines.erase(std::remove_if(lines.begin(), lines.end(), [&name](const std::string& line) { return line.find(name) != std::string::npos; }), lines.end()); Or since C++20 std::erase_if(std::vector): std::erase_if(lines, [&name](const std::string& line) { return line.find(name) != std::string::npos; });
70,425,137
70,425,867
Exporting template function requiring std concepts
IDE : MSVS 2022, /std:c++latest, /experimental:module, x86 ; Goal : to export T add(T,T) that requires std::integral<T> ; This compiles (test.ixx) : export module test; template < typename T > concept addable = requires ( T t1, T t2 ) { t1 + t2 ; }; export template < typename T > requires addable<T> T add ( T t1, T t2 ) { return t1 + t2; } This does not (test.ixx) : export module test; #include <concepts> export template < typename T > requires std::integral<T> T add ( T t1, T t2 ) { return t1 + t2; } The above code causes 2 errors LNK2019, details below ; Tried to #include <concepts> in a separate implementation file - failed ; import std.core;, which seems to not yet be supported - failed ; Usage sample (main.cpp) : import test; #include <iostream> int main () { using namespace std; int i = add(22,20); // = 42 double d = add(0.5,0.77); // = 1.27 cout << i << ", " << d << endl ; // "42, 1.27" return 0; } Any ideas ? Linker error details : LNK2019 : unresolved external symbol __imp__ldiv::<!test> referenced in function "struct test::_ldiv_t __cdecl div(long,long)" (?div@@YA?AU_ldiv_t@test@@JJ@Z::<!test>) LNK2019 : unresolved external symbol __imp__lldiv::<!test> referenced in function "struct test::_lldiv_t __cdecl div(__int64,__int64)" (?div@@YA?AU_lldiv_t@test@@_J0@Z::<!test>)
The thing is, you shouldn't use #include after the module declaration export module xxx. The introduction of modules does not change what #include means (well, in most cases), #include still means "copy-paste this file here". Your #include-ing of <concepts> pasted all its content and its transitive includes into your module, and your module now "owns" these definitions (they have module linkage). The compiler mangles names belong to modules differently, and that's what causes the linker errors. You should instead use the global module fragment for #include-ing things: module; #include <concepts> export module test; // contents Or use "header units" (provided your compiler supports them) instead: export module test; import <concepts>; // contents
70,425,876
70,426,111
How to convert extremely small exp values to 0?
I'm doing Gram-Schmidt Orthogonalization process. At some point I'm getting output 3D vectors with values extremely small. Basically the values are zeros. How to deal with values such as -3.5527136788005009 * 10^-15? How to convert them to zero or compare if it is almost zero?
I did research on my old code and I've found this little func: static const double eps = 1e-10; bool isZero(double value) const { return std::abs(value) <= eps; }
70,425,955
70,426,134
Is the compiler required to emit stores to raw addresses?
Two popular compilers (gcc, clang) emit a store instruction in the body of the following function: void foo(char x) { *(char *)0xE0000000 = x; } This program might behave correctly on some hardware architectures, where the address being written to is memory-mapped IO. Since this access is performed through a pointer not qualified as volatile, is the compiler required to emit a store here? Could a sufficiently-aggressive optimizer legally eliminate this store? I'm curious about whether this store constitutes an observable side effect with respect to the abstract machine. Additionally, do C17 and C++20 differ in this regard?
The C standard does not require an implementation to issue a store because C 2018 5.1.2.3 6 says: The least requirements on a conforming implementation are: — Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine. — At program termination, all data written into files shall be identical to the result that execution of the program according to the abstract semantics would have produced. — The input and output dynamics of interactive devices shall take place as specified in 7.21.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input. This is the observable behavior of the program. None of these includes assignment to a non-volatile lvalue.
70,426,203
70,435,624
Iterate Through All Nodes In yaml-cpp Including Recursive Anchor/Alias
Given a YAML::Node how can we visit all Scalar Nodes within that node (to modify them)? My best guess is a recursive function: void parseNode(YAML::Node node) { if (node.IsMap()) { for (YAML::iterator it = node.begin(); it != node.end(); ++it) { parseNode(it->second); } } else if (node.IsSequence()) { for (YAML::iterator it = node.begin(); it != node.end(); ++it) { parseNode(*it); } } else if (node.IsScalar()) { // Perform modifications here. } } This works fine for my needs except for in one case: if there is a recursive anchor/alias. (I think this is permitted by the YAML 1.2 spec? yaml-cpp certainly doesn't throw an Exception when parsing one) e.g.: first: &firstanchor a: 5 b: *firstanchor The code above will follow the alias to the anchor repeatedly until crashing (SEGFAULT) presumably due to stack issues. How would one overcome this issue? Is there a better way to iterate through an entire unknown Node structure that would solve this? Is there a way to check from the Node with the public API if it is an alias so we can maintain a stack of previous visited aliases to detect looping and break. Or is there a way to fetch some unique Node identifier so I can maintain a stack of previously visited nodes? Or finally is this recursive anchor/alias just not spec-compliant - in which case how can I check for its occurrence to ensure I can return an appropriate error?
The most obvious way to identify nodes would be to use their m_pNode pointer; however that is not publicly queryable. The next best way is to use bool Node::is(const Node& rhs) const, which sadly doesn't allow us to do any sorting to speed up performance when searching for cycles. As you probably do not only want to avoid cycles, but also want to avoid descending into the same subgraph twice, you actually need to remember all visited nodes. This means that eventually you'll store all nodes in the subgraph you walk and have space complexity O(n), and since there is no order on nodes we can use, time complexity is O(n²) since each node must be compared to all previously seen nodes. That is horrible. Anyway, here's the code that does it: class Visitor { public: using Callback = std::function<void(const YAML::Node&)>; Visitor(Callback cb): seen(), cb(cb) {} void operator()(const YAML::Node &cur) { seen.push_back(cur); if (cur.IsMap()) { for (const auto &pair : cur) { descend(pair.second); } } else if (node.IsSequence()) { for (const auto &child : cur) { descend(child); } } else if (node.IsScalar()) { cb(cur); } } private: void descend(const YAML::Node &target) { if (std::find(seen.begin(), seen.end(), target) != seen.end()) (*this)(target); } std::vector<YAML::Node> seen; Callback cb; }; (We can use std::find since operator== uses Node::is internally.) And then you can do Visitor([](const YAML::Node &scalar) { // do whatever with the scalar })(node); (forgive me for errors, my C++ is a bit rusty; I hope you get the idea.)
70,426,294
71,421,615
boost::python::init<>() undefined reference
I'm trying to expose a simple class and constructor using boost python. I have the following: files: boost_test    ├── boost_test.cpp    └── CMakeLists.txt CMakeLists.txt: cmake_minimum_required(VERSION 3.22.1) project(boost_test) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED YES) find_package(PythonLibs 3.8 REQUIRED) find_package(Boost COMPONENTS python38 REQUIRED) add_library(${PROJECT_NAME} MODULE boost_test.cpp) set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") set(CMAKE_SHARED_MODULE_PREFIX "") target_include_directories(${PROJECT_NAME} PRIVATE ${PYTHON_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARIES}) target_link_libraries(${PROJECT_NAME} Boost::python38) boost_test.cpp: #include <boost/python.hpp> using namespace boost::python; struct A { }; BOOST_PYTHON_MODULE(boost_test) { class_<A>("A", init<>()); } When I try to import the library in python I get the following: >>> import boost_test Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: .../src/boost/boost_test/boost_test.so: undefined symbol: _ZN5boost6python15instance_holder8allocateEP7_objectmmm If I replace the init<>() with no_init in the boost_test.cpp I don't get the error, but I won't be able to instantiate the class. I'm really not sure how to fix this. Any help is greatly appreciated.
It turned out boost was installed incorrectly. I'm not sure what I did wrong, but rebuilding the boost library fixed the issue.
70,426,472
70,426,580
c++ How do I initialize a member array in a constructor?
I am trying to initialize a member array in the default constructor of a class which I've created. However, nothing I've tried has worked. I'm quite new to c++ and programming in general, and I haven't found the answer I was looking for online yet. In my .hpp file I have: class thing { private: std::string array[8][8]; public: thing(); }; And in the corresponding .cpp file I have: thing::thing() { array = { {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"} }; //error: Array type 'std::string [8][8]' is not assignable } I've also tried the following: Board::Board() { std::string array[8][8] = { {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"} }; } Doing it this way doesn't cause any compiler errors, but it doesn't seem to actually work. When I try to cout the elements in the array I get nothing. Is there a way to do what I want to do?
Either use a constructor initializer list, or use a default member initializer. #include <string> class thing { std::string array[8][8]; public: thing(); }; thing::thing() : array{ {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, } { } class thing2 { std::string array[8][8] = { {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, {"a", "b", "c", "d", "e", "f", "g", "h"}, }; }; int main() { thing t; (void)t; thing2 t2; (void)t2; }
70,426,700
70,426,725
Vector constructor identified as function
Consider this piece of code: #include <iostream> #include <sstream> #include <iterator> #include <vector> #include <string> int main() { std::istringstream ss("abcabc abc a b e"); std::vector<std::string> words(std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>()); std::string deciphered; int shift = 5; for (size_t i = 0; i < shift; i++) { for (size_t j = 0; i + j < words.size(); j += shift) { deciphered += words[i + j]; } } } Basically, I want to split words and store them to my words array. But I get compile errors: main.cpp: In function 'int main()': main.cpp:14:40: error: request for member 'size' in 'words', which is of non-class type 'std::vector<std::__cxx11::basic_string<char> >(std::istream_iterator<std::__cxx11::basic_string<char> >, std::istream_iterator<std::__cxx11::basic_string<char> > (*)())' 14 | for (size_t j = 0; i + j < words.size(); j += shift) | ^~~~ main.cpp:16:33: warning: pointer to a function used in arithmetic [-Wpointer-arith] 16 | deciphered += words[i + j]; | ^ main.cpp:16:33: error: invalid conversion from 'std::vector<std::__cxx11::basic_string<char> > (*)(std::istream_iterator<std::__cxx11::basic_string<char> >, std::istream_iterator<std::__cxx11::basic_string<char> > (*)())' to 'char' [-fpermissive] 16 | deciphered += words[i + j]; | ~~~~~~~~~~~^ | | | std::vector<std::__cxx11::basic_string<char> > (*)(std::istream_iterator<std::__cxx11::basic_string<char> >, std::istream_iterator<std::__cxx11::basic_string<char> > (*)()) In file included from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\string:55, from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\locale_classes.h:40, from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\ios_base.h:41, from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ios:42, from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ostream:38, from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:39, from main.cpp:1: c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\basic_string.h:1186:25: note: initializing argument 1 of 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator+=(_CharT) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' 1186 | operator+=(_CharT __c) | ~~~~~~~^~~ Judging by the errors, my variable words was identified as a function. I'm so confused, what's the reason for this behavior? And how do I fix it?
This is what is known as most vexing parse, in this case you should use the braced initialization syntax which will let the compiler know you are trying to construct an instance of a class instead of declaring a function. i.e std::vector<int> a{} instead of std::vector<int> a()
70,426,702
70,427,201
Constrain template template parameter to be one of two types
I have the following classes: template <typename T, int N0, int N1, int N2> struct A{}; template <typename T, int N0, int N1, int N2> struct B{}; I want templated functions to only be able to take one of these two types: template <typename AorB> void foo(AorB& arg) { } Where all A<T,N0,N1,N2> and B<T,N0,N1,N2> are accepted. What is the best way to approach this? Edit: This is intended to work for base-classes where inheritance is used. A<...> would have some derived-class A_derived<N0, N1, N2>, and B<...> would have some derived-class B_derived<N0, N1, N2>. How would AorB be constrained to only be of type A<...> or B<...>?
You could define a helper variable like this: template<typename T> constexpr static bool is_ab = false; template <typename T, int N0, int N1, int N2> constexpr static bool is_ab<A<T, N0, N1, N2>> = true; template <typename T, int N0, int N1, int N2> constexpr static bool is_ab<B<T, N0, N1, N2>> = true; And then the function foo for either is_ab or not: template <typename T, std::enable_if_t<is_ab<T>, int> = 0> void foo(T arg) { std::cout << "AB\n"; } template <typename T, std::enable_if_t<(!is_ab<T>), int> = 0> void foo(T arg) { std::cout << "not AB\n"; } If you need other types use the first overload, you can just define the is_ab for them as shown. Full example here. Or, as @NathanOliver commented, use a concept.
70,426,877
70,427,050
How does std::array constructor initialize its array?
Im trying to understand how std::array constructor work and how can he take a array and initialize it to its array. I was searching on the standard library file and i find this piece of code #if _HAS_CXX17 template <class _First, class... _Rest> struct _Enforce_same { static_assert(conjunction_v<is_same<_First, _Rest>...>, "N4687 26.3.7.2 [array.cons]/2: " "Requires: (is_same_v<T, U> && ...) is true. Otherwise the program is ill-formed."); using type = _First; }; template <class _First, class... _Rest> array(_First, _Rest...) -> array<typename _Enforce_same<_First, _Rest...>::type, 1 + sizeof...(_Rest)>; #endif // _HAS_CXX17 Is this the constructor? how does it work exacly? Thanks!
As already mentioned in comments above, std::array is an aggregate type, so you are not calling a constructor but actually initializing a data member. The code you point at in the question allows creation of std::array without stating array's type and size. This is done, with deduction guides, as seen in the code below. Here is how it may look if you implement it by yourself: template<typename T, std::size_t SIZE> struct MyArray { T arr[SIZE]; }; // MyArray deduction guides: // similar code was added to std::array in C++17 to allow the // creation of a2 below, without providing template arguments template <class _First, class... _Rest> MyArray(_First, _Rest...) -> MyArray<_First, 1 + sizeof...(_Rest)>; int main() { MyArray<int, 5> a1 = {1, 2, 3}; // since C++11 MyArray a2 {1, 2, 3}; // deduced to MyArray<int, 3>, since C++17 // creation of a2 is based on the deduction guides above } The code above ignores the case of sending different types to MyArray, like this: MyArray a2 {1, 2.0, 3}; // still deduced to MyArray<int, 3> with our code There are several options to treat the above: decide that the type of the array is based on the type of the first value (as we actually do in our naive implementation), decide that the type would be based on the common_type of the values, or disallow such initialization. The C++ standard decided to disallow it, so there is a need to check that all types are the same and raise compilation error if not, e.g. using static_assert. As done in the original code posted, using the _Enforce_same struct. The initialization of the inner data member is based on aggregate initialization, values sent to a struct are passed into its fields like in the examples below: struct A { int a; }; struct B { int a, b; }; struct C { int a[5]; }; int main { A a = {1}; // goes to a.a B b = {1, 2}; // goes to b.a and b.b C c = {1, 2, 2}; // goes into the array c.a }
70,427,057
70,427,447
sfinae vs concepts with non type template parms
For academic reasons I want to implement an example which select a template if a non type template parameter fulfills a given criteria. As example I want to have a function which is only defined for odd integer numbers. It can be done like: template < int N, bool C = N%2> struct is_odd: public std::false_type{}; template<int N > struct is_odd< N,true >: std::true_type{}; template < int N> constexpr bool is_odd_v = is_odd<N>::value; template < int N, typename T=typename std::enable_if_t<is_odd_v<N>, int> > void Check(){ std::cout << "odd number template specialization " << std::endl; }; int main() { Check<1>(); Check<2>(); // fails, as expected, ok } I think it is much code for doing such a simple thing. Quite clear, I directly can use the modulo operation inside the std::enable_if but lets assume there will be a more complex check for the non type template parameter value. Q: Can this be done without so many steps of indirection but still having some std::is_xxx in use? BTW: If concepts can handle non type template parms, it can be done much simpler, but I know, not designed for it... template < int N > concept ODD = !(N % 2); template < ODD N > void Check() { std::cout << "odd number template specialization " << std::endl; } Bonus: Maybe someone have an idea why concepts are not made for non type template parms?
After some more experimental work I found that concepts can be used for non type template parms. I simply did not find anything about that in the docs I read. template < int I > concept ODD = !(I%2); template< int N > requires( ODD<N> ) void Check() { std::cout << "odd number template spezialisation " << std::endl; } template< int N > requires( !ODD<N> ) void Check() { std::cout << "even number template spezialisation " << std::endl; } int main() { Check<2>(); Check<4>(); Check<3>(); } Live demo
70,427,098
70,428,870
QSerialPortInfo::serialNumber() always returns an empty string
QSerialPortInfo::serialNumber() always returns an empty string, which happens when it's unavailable. I tried connecting different ports, everything seems allright, but it doesn't show a Serial Number of a port no matter what I do! Port name, manufacturer, product ID, however, can be correctly outputted. I didn't connect any devices to the ports, however. Why can serial number be unavailable? Can this be fixed somehow? I guess the mistake is somewhere outside code, but here is a slot that I use to access serialNumber() in : void PortBrowser::onPortChange() { int i; if(comsCombo->currentIndex()>-1) i =comsCombo->currentIndex(); else i = 0; QSerialPort currPort(comsList[i]); bool opened = currPort.open(QIODevice::ReadOnly); const QString seriNum = comsList[i].serialNumber(); serNum->setText(seriNum); manufact->setText(comsList[i].manufacturer()); QTextStream out(stdout); out<<comsList[i].serialNumber(); currPort.close(); }
If you take a look at the relevant source code parseDeviceSerialNumber() you will see quite some fancy logic where Qt tries to isolate a serial number from some device-identification string. That's the string you are likely also seeing in the Windows device manager way down in the details. Why can serial number be unavailable? Can this be fixed somehow? You seem to have a serial port that does not provide its identifier in a format Qt would understand. You could try to come up with a patch for Qt to make it recognize your serial port or you might go and buy a serial port that Qt does recognize. One chipset that is explicitly mentioned in the source code is FTDI.
70,427,135
70,428,469
Implement a struct in WASM text format
Does WASM text format have structs? (module (type (; can a type be a `struct` like in C or rust? ;) ) (; rest of module ;) ) I've compiled the following c++ to wasm using this WasmExplorer tool struct MyStruct { int MyField; long MyOtherField; }; MyStruct returnMyStruct(int myField){ return MyStruct { MyField: myField, MyOtherField: myField * 2 }; } It outputs the following, but I'm having trouble understanding what the WASM is doing. (module (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "_Z14returnMyStructi" (func $_Z14returnMyStructi)) (func $_Z14returnMyStructi (; 0 ;) (param $0 i32) (param $1 i32) (i32.store (get_local $0) (get_local $1) ) (i32.store offset=4 (get_local $0) (i32.shl (get_local $1) (i32.const 1) ) ) ) ) The function generated does not have a return type, it uses i32.store and i32.shl along with an offset. Is it storing the struct in memory somewhere? An explanation of how and why this works would be much appreciated.
Does WASM text format have structs? It does not. Like with other low-level assembly languages, wasm only has a few integer data types, and views memory as a big block of bytes. This is a simplification, but when a high level language like C is compiled to assembly, struct variables are allocated a spot in memory, with each field laid out at a different address. When you write to a field, it: Takes the address of the struct variable Adds the offset of the field from the root of the struct Writes to the resulting address The function generated does not have a return type, it uses i32.store and i32.shl along with an offset. Is it storing the struct in memory somewhere? What you're observing is a C++ feature, Return Value Optmization (RVO). Compilers are required since C++11 to avoid making extra copies of a PR-value struct (e.g. a temporary expression) getting returned from a function. While the standard doesn't dictate how to do that, many compilers accomplish this by converting the return value to an output parameter, e.g. this: MyStruct myFunc(int); MyStruct myStruct; myStruct = myFunc(42); gets converted to this: void myFunc(MyStruct&, int); MyStruct myStruct; myFunc(myStruct, 42); Now look again at the function signature: (func $_Z14returnMyStructi (; 0 ;) (param $0 i32) (param $1 i32) There are two parameters: $0 is the address of a MyStruct, where the return value will be written $1 is myField. So this instruction: (i32.store (get_local $0) (get_local $1) ) Writes myField to the output address. In this case, the MyField member of MyStruct sits at offset zero, and is getting written. And this instruction: (i32.store offset=4 (get_local $0) (i32.shl (get_local $1) (i32.const 1) ) ) i32.shl shifts myField left by 1 bit, effectively multiplying it by two. The result is written to an address 4 bytes after the output address. Since MyOtherField is laid out 4 bytes from the root of MyStruct, this is writing to MyOtherField.
70,427,448
70,427,645
Remove dot prefix "./" from std::filesystem::path
Is there a simple way to strip away the starting ./ of a path. For example: I have a path ./x/y and i want to convert it to x/y (without the first dot and slash). Is there a standard way of doing it? #include <iostream> #include <filesystem> namespace filesystem = std::filesystem; int main() { auto path = filesystem::path{"./x/y"}; std::cout << path << std::endl; std::cout << ???? << std::endl; // How do I do this? }
Apparently the problem could be solved with std::filesystem::relative(): #include <iostream> #include <filesystem> namespace filesystem = std::filesystem; int main() { auto path = filesystem::path{"./x"}; std::cout << path << std::endl; std::cout << filesystem::relative(path, "./") << std::endl; // } Produces "./x" "x"
70,427,890
70,428,027
std::vector to Eigen::VectorXf
I have a vector int N = 100; std::vector<float> v(N, 1.0f); which I'd like to convert to an Eigen vector type ( Eigen::VectorXf?) I have tried Eigen::VectorXf ev(N); ev = Eigen::Map<Eigen::VectorXf>(&v[0], N); but I am not sure if it right or wrong. I can only see ev has 1 value in my visual studio.
Your code seems correct. No need to initialize ev(N), though. You can just write Eigen::VectorXf ev = Eigen::VectorXf::Map(&v[0], N);
70,428,046
70,429,098
trying to break a line into multiple tokens
My problem is this, i have this string RGM 3 13 GName 0005 32 funny 0000 44 teste 0000\n and i want to split it like this 13 GName 32 funny 44 teste so i can save the numbers and names in an array, but the problem is for some reason declaring an "" like i did is invalid in c++ and it is breaking the line at all. Program: #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <iostream> #define line "RGM 3 13 GName 0005 32 funny 0000 44 teste 0000\n" int main() { char s[] = ""; char* token; strtok(line,s); strtok(line,s); while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL,s); } return(0); }
If your lines are always going to have the format A B n1 str1 code1 ... nn strn coden, where you seem to discard A B, the simple C++ code below will suffice: [Demo] #include <iostream> // cout #include <sstream> // istringstream #include <string> int main() { const std::string line{"RGM 3 13 GName 0005 32 funny 0000 44 teste 0000"}; std::istringstream iss{line}; std::string token1{}; std::string token2{}; iss >> token1 >> token2; // get rid of header (RGM 3) std::string token3{}; while (iss >> token1 >> token2 >> token3) { std::cout << token1 << " " << token2 << "\n"; } } Notice this is doing almost no checks at all. Should you need more control over your input, something more advanced could be implemented. For example, the code below, using regular expressions, would try to match each line header to a RGM m (RGM text and 1-digit m); then, it would search for groups of the form n str code (2-digit n, alphabetic str, 4-digit code): [Demo] #include <iostream> // cout #include <regex> // regex_search, smatch #include <string> int main() { std::string line{"RGM 3 13 GName 0005 32 funny 0000 44 teste 0000"}; std::regex header_pattern{R"(RGM\s+\d)"}; std::regex group_pattern{R"(\s+(\d{2})\s+([a-zA-Z]+)\s+\d{4})"}; std::smatch matches{}; if (std::regex_search(line, matches, header_pattern)) { line = matches.suffix(); while (std::regex_search(line, matches, group_pattern)) { std::cout << matches[1] << " " << matches[2] << "\n"; line = matches.suffix(); } } }
70,428,563
70,428,826
Union's default constructor is implicitly deleted
The following code: struct non_trivially { non_trivially() {}; }; union U { bool dummy{false}; non_trivially value; }; int main() { U tmp; } https://godbolt.org/z/1cMsqq9ee Produces next compiler error on clang (13.0.0): source>:11:7: error: call to implicitly-deleted default constructor of 'U' U tmp; ^ <source>:7:19: note: default constructor of 'U' is implicitly deleted because variant field 'value' has a non-trivial default constructor non_trivially value; But successfully compiles using MSVC (19.30). According to the cppreference it should be a valid code: https://en.cppreference.com/w/cpp/language/union If a union contains a non-static data member with a non-trivial default constructor, the default constructor of the union is deleted by default unless a variant member of the union has a default member initializer . In my example there is an alternative in U with a default member initializer so default constructor shouldn't be deleted, but it is. What am I missing?
This is CWG2084. Clang and gcc are just wrong in deleting the default constructor if you provide a default member initializer. The relevant quote that was added to the standard after the change was adopted (in [class.default.ctor]): A defaulted default constructor for class X is defined as deleted if: X is a union that has a variant member with a non-trivial default constructor and no variant member of X has a default member initializer, [...] X is a union and all of its variant members are of const-qualified type (or array thereof), (being the only two points that refer to union types, neither one applies, so it should not be implicitly deleted) The workaround is to user-provide a constructor: union U { constexpr U() : dummy{false} {} bool dummy; non_trivially value; }; // Or this also seems to work union U { constexpr U() {} bool dummy{false}; non_trivially value; };
70,428,773
70,432,964
references are a pain for my mocks in TDD
I am new with c++/tdd, embraced gtest/gmock, and fell in love. One thing kind of puzzles me though. Are reference pointers really the way to go? I find myself producing a lot of boiler plate injecting all mocks (even when I don't have any business mocking that behavior). Example: namespace { class set_configuration_command_tests : public testing::Test { protected: void SetUp() override { _uart_peripheral = new uart8_peripheral_mock(); _uart = new uart8_mock(*_uart_peripheral); _logger = new logger_mock(*_uart); _mqtt_client = new mqtt_client_mock(*_logger); _set_configuration_command = new set_configuration_command(*_mqtt_cient); } void TearDown() override { delete _set_configuration_command; } uart8_peripheral_mock *_uart_peripheral; uart8_mock *_uart; logger_mock *_logger; mqtt_client_mock *_mqtt_cient; set_configuration_command *_set_configuration_command; }; TEST_F(set_configuration_command_tests, execute_update_configuration) { // arrange // act // assert } } What I rather did here, is create my sut as _mqtt_client = new mqtt_client_mock(nullptr); // will not compile of course _set_configuration_command = new set_configuration_command(*_mqtt_cient); All the other mocks, I don't need in this case. Is this the drawback of using reference pointers? Or is there a better approach I should follow?
Found a better alternative. Providing interfaces (pure virtual classes) heavily reduces the need to provide an entire tree of mocks. e.g class flash_api : public iflash_api { public: flash_api(iflash_peripheral &flash_peripheral) : _flash_peripheral(flash_peripheral) { } virtual ~flash_api() { } } Before my mock inherited from flash_api directly. When I gave this class an interface too (`iflash_api') I can let my mock inherit from iflash_api, which gives me a parameter-less constructor. class flash_api_mock : public iflash_api { public: flash_api_mock() { } virtual ~flash_api_mock() { } } Then I can write my unit test based on the mocks I actually want to give behavior. class set_configuration_command_tests : public testing::Test { protected: void SetUp() override { _mqtt_cient = new mqtt_client_mock(); _flash_api = new flash_api_mock(); _set_configuration_command = new set_configuration_command(*_mqtt_cient, *_flash_api); } void TearDown() override { delete _set_configuration_command; } flash_api_mock *_flash_api; mqtt_client_mock *_mqtt_cient; set_configuration_command *_set_configuration_command; };
70,429,220
70,430,463
C++ Write Macro for finding an integer type given another integer type
I have a function which looks like this: template<class T, class E, class U = T> T function(T input1, E input2) { // implementation here } Instead of the above declaration, I want the default for U to be a macro which takes T for input. More specifically, I want the default for U to be boost::multiprecision::cpp_int if T is boost::multiprecision::cpp_int, and I want the default for U to be an integer with double the precision of T for fixed precision T. I know the second part can be accomplished with: U = boost::uint_t<2 * std::numeric_limits<T>::digits>::fast How do I check for T being a cpp_int (or any other arbitrary precision integer within std and boost), and put everything together in a macro? Edit: I found that testing for arbitrary precision can be done through: std::numeric_limits<T>::is_bounded I still do not know how to combine these 2 tests into 1 macro.
Defined a custom boost multiprecision int using a macro, and hid the function backends behind another function which checks types. U is void so that the user has the option of customizing it. If T is fixed precision, the function calls the macro, otherwise passes cpp_int as a template argument. The type deduction of the custom boost int is done at compile time and the if statements are probably evaluated at compile time as well. #include <limits> #include <type_traits> #ifndef BOOST_UINT #define BOOST_UINT(bit_count) boost::multiprecision::number<boost::multiprecision::cpp_int_backend<bit_count, bit_count, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>> #endif template<class T, class E, class U = void> T function(T input1, E input2) { if(std::is_same<U, void>::value) { if(std::numeric_limits<T>::is_bounded) { return function_backend<T, E, BOOST_UINT( ((std::numeric_limits<T>::digits + 1) >> 1) << 2)>(input1, input2); } else { return function_backend<T, E, cpp_int>(input1, input2); } } else { return function_backend<T, E, U>(input, input2); } } template<class T, class E, class U> T function_backend(T input1, E input2);
70,429,512
70,429,883
c++ - how to list all keys inside a boost::bimap
What would be a simple way to iterate through and store all keys of boost::bimap into a vector. Would it work just like we would for std::map
This would be one way: #include <boost/bimap.hpp> #include <vector> template<class L, class R> std::vector<L> to_vector(const boost::bimap<L, R>& bm) { std::vector<L> rv; rv.reserve(bm.size()); // or bm.size() * 2 if you want to store the right keys too for(auto&[l, r] : bm) { // loop through all the entries in the bimap rv.push_back(l); // store the left key // rv.push_back(r); // if you want to store the right key too } return rv; } Then calling it: auto vec = to_vector(your_bimap);
70,429,541
70,429,749
Overloading static and non-static member function with constraint
Is this code valid? template<bool b> struct s { void f() const { } static void f() requires b { } }; void g() { s<true>().f(); } clang says yes, but gcc says no <source>: In function 'void g()': <source>:10:20: error: call of overloaded 'f()' is ambiguous 10 | s<true>().f(); | ~~~~~~~~~~~^~ <source>:3:14: note: candidate: 'void s<b>::f() const [with bool b = true]' 3 | void f() const { | ^ <source>:5:21: note: candidate: 'static void s<b>::f() requires b [with bool b = true]' 5 | static void f() requires b { | ^ Compiler returned: 1 https://godbolt.org/z/f4Kb68aee
If we go through [over.match.best.general], we get: a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...] The only argument is the object argument, and we have earlier that: If F is a static member function, ICS1(F) is defined such that ICS1(F) is neither better nor worse than ICS1(G) for any function G, and, symmetrically, ICS1(G) is neither better nor worse than ICS1(F); otherwise, So the premise holds: all arguments for one function have a conversion sequence no worse than the conversion sequence for the other function. So we move on to our tiebreakers... for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that, The only argument that we could have a better conversion sequence for is the object argument, and as established, that one is equivalent. So this tiebreaker does not apply. the context is an initialization by user-defined conversion (see [dcl.init], [over.match.conv], and [over.match.ref]) and [...] Nope. the context is an initialization by conversion function for direct reference binding of a reference to function type, [...] Nope. F1 is not a function template specialization and F2 is a function template specialization, or, if not that, Nope. F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in [temp.func.order], or, if not that, Nope. F1 and F2 are non-template functions with the same parameter-type-lists, and F1 is more constrained than F2 according to the partial ordering of constraints described in [temp.constr.order], or if not that, Aha! In this example, we have non-template functions with the same parameter-type-lists (both are just empty). The static member function is constrained and the non-static member function is not constrained, which is the most trivial kind of "more constrained" (see [temp.constr.order]). As such, I think that clang (and msvc) are correct to accept the program and gcc is incorrect to reject it. (submitted 103783).
70,429,668
70,429,868
Segmentation Fault from a While Loop C++
I'm trying to do a search from inside a map that would push all related children and later generations into a stack. mined is a json object declared before. if ( !mined[source].empty() ) { std::vector<std::string> minedDataVec = mined[source]; while ( !minedDataVec.empty() ) { for (std::string s: minedDataVec) { stack.push(s); if ( !mined[s].empty() ) { std::vector<std::string> minedDataVec = mined[s]; } else { minedDataVec.clear(); } } } } However, I'm getting a Segmentation Fault that I'm pretty sure has something to do with the while loop inside this code. Removing the while loop works but that would mean I'd have to manually add more code each time I want to search deeper within my map.
First, the vector named minedDataVec declared in the if block seems meaningless... As for the Segmentation Fault, maybe it's because minedDataVec.clear() "Invalidates any references, pointers, or iterators referring to contained elements." (source). The range-for loop for (std::string s: minedDataVec) has an implicit iterator to minedDataVec, which may become invalidated and cause a Segmentation Fault from an invalid read access.
70,429,673
70,429,682
std::thread in constructor referencing it's deleted copy constructor?
I'm having a surprising amount of trouble with a constructor I'm writing. It's something incrediably basic, but I'm having a bad day because I'm totally stumped. class RenderThread { public: RenderThread(std::thread && threadToGive) : m_renderThread(threadToGive) {} private: std::thread m_renderThread; }; int test() { std::thread thread; RenderThread rt(std::move(thread)); } My constructor is trying to call std::thread::thread(const std::thread &) which is definitely not my goal, even if it was possible. I want to move the argument threadToGive into m_renderThread, not copy it. What am I doing wrong here?
You have to std::move() the RenderThread constructor's parameter into the constructor of the m_renderThread member: : m_renderThread(std::move(threadToGive)) {}
70,429,993
70,430,055
How to get data in resource file?
I get the NULL(hRsrc) when it is running. .cpp HINSTANCE hInstance = AfxGetInstanceHandle(); HRSRC hRsrc = FindResource(hInstance, MAKEINTRESOURCE(IDR_EXE1), _T("EXE")); if (hRsrc == NULL) { MessageBox(NULL, TEXT("LoadEmbedded"), TEXT("1"), MB_OK); } HANDLE hRes = LoadResource(hInstance, hRsrc); if (hRes == NULL) { MessageBox(NULL, TEXT("LoadEmbedded"), TEXT("2"), MB_OK); } LPSTR lpRes = (LPSTR)LockResource(hRes); if (lpRes == NULL) { MessageBox(NULL, TEXT("LoadEmbedded"), TEXT("3"), MB_OK); } .rc IDR_EXE1 EXE "crashpad_handler.exe" I set the data id and type. resource.h #define IDR_EXE1 105
Does the .rc file have an #include "resource.h" statement? If not, then the IDR_EXE1 macro won't be defined when the .rc is compiled, and thus the resource's ID will be the literal string "IDR_EXE1" and not the numeric 105 (use a resource viewer tool to verify that). In which case, you would have to use _T("IDR_EXE1") instead of MAKEINTRESOURCE(IDR_EXE1) when calling FindResource(): HRSRC hRsrc = FindResource(hInstance, _T("IDR_EXE1"), _T("EXE")); Otherwise, fix the .rc file: #include "resource.h" // <-- add this! IDR_EXE1 EXE "crashpad_handler.exe"
70,430,566
70,444,118
c++ filesystem, get files in directory alphabetically, rename inputs
I have the following code: /* This function conditions folders into a standard format with the following specifications The first file in the folder to render has an index starting at 0 with the name of outPutName[Index].fileExtension dataType is preserved */ void vCanvas::conditionFolder(vizModule target){ vector<string> fileNames; int index = 0; string outputName = "output"; string oPath = target.path; string temp; cout << "vCanvas::conditionFolder is processing" << oPath << endl; //https://en.cppreference.com/w/cpp/filesystem/rename for (const auto & entry : fs::directory_iterator(oPath)){ if (entry.is_regular_file()){ temp = entry.path().stem().string(); cout << oPath+temp << " modified to " << oPath+(outputName+to_string(index)+"."+target.dataType) << endl; fs::rename(oPath+temp, oPath+(outputName+to_string(index)+"."+target.dataType)); index++; } } } I was hoping fs::directoryiterator would give me entrys in alphabetical order and it doesn't. I am getting 0007.png before 0001.png, which is unworkable. Is there any simple solution that will let me get all files in a folder, in alphabetical order, and rename them? Second iteration on the above code, using std::sort //see https://www.cplusplus.com/reference/algorithm/sort/ bool alphabetSort(string i, string j){ int val = i.compare(j); if (val == -1) {return true;} else if (val == 1) {return false;} else {return false;} } /* This function conditions folders into a standard format with the following specifications The first file in the folder to render has an index starting at 0 name of outPutName. dataType is preserved */ void vCanvas::conditionFolder(vizModule target){ string outputName = "output"; string oPath = target.path; string temp; vector<string> fileStrings; cout << "vCanvas::conditionFolder is processing" << oPath << endl; //https://en.cppreference.com/w/cpp/filesystem/rename for (const auto & entry : fs::directory_iterator(oPath)){ if (entry.is_regular_file()){ temp = entry.path().stem().string(); fileStrings.push_back(temp); } } for (int i = 0; i < fileStrings.size(); i++){ cout << fileStrings[i] << ","; } sort(fileStrings.begin(), fileStrings.end(),alphabetSort); cout << "Directory sorted" << endl; for (int i = 0; i < fileStrings.size(); i++){ cout << fileStrings[i] << ","; } cout << endl; for (int k = 0; k < fileStrings.size(); k++){ temp = fileStrings[k]; cout << oPath+temp << " modified to " << oPath+(outputName+to_string(k)+"."+target.dataType) << endl; fs::rename(oPath+temp, oPath+(outputName+to_string(k)+"."+target.dataType)); } } Which gives vCanvas::conditionFolder is processing./unit_tests_folder/testpng1/ 0007,0014,0018,0008,0012,0002,0005,0010,0016,0003,0001,0006,0015,0019,0017,0004,0011,0013,0009,0020, 0007,0009,0008,0002,0005,0004,0003,0001,0006,0014,0013,0011,0017,0019,0015,0016,0010,0012,0018,0020,
I wrote and ran unit tests on this function, which does what I want, which, in specific, is to first sort alphabetically, but then, if the program is comparing 2 digits, to take the smaller size string. This works for my purposes, which is simply to handle consistent but arbitrarily named series of .pngs and turn them into a standardized format. bool alphaNumerSort(string i, string j){ string shorterStr; (i.size() <= j.size()) ? shorterStr = i : shorterStr = j; for (int k = 0; k < shorterStr.size(); k++) { if (i[k] != j[k] && isdigit(i[k]) && isdigit(j[k]) ) { if (i.size() == j.size()) { return i[k] < j[k]; } return (i.size() < j.size()); } if (i[k] != j[k]) { return i[k] < j[k]; } } return false; //returns true if i is alphabetically before j }
70,430,857
70,430,991
Strange behavior found in Sublime and Vim at EOF
Ι have a file called position.txt which has been formatted in a particular fashion. This is the content of position.txt: START POLYMER 1 1 0 0 2 0 0 3 0 0 4 0 0 4 1 0 5 1 0 5 0 0 6 0 0 END POLYMER 1 However, when I look at position.txt using vi, I see this: When I look at positions.txt in sublime, I see: Clearly, there seems to be an additional line added in Sublime, which is not even visible in Vi. This shouldn't be a problem, but I am running the following code: int Grid::ExtractNumberOfPolymers(std::string filename){ std::regex start("START"); std::regex end ("END"); std::ifstream myfile (filename); if ( !myfile ){ std::cerr << "File named " << filename << " could not be opened!" << std::endl; exit(EXIT_FAILURE); } std::string myString; // std::vector <std::string> StartContents; // std::vector <std::string> EndContents; int numberOfStarts {0}, numberOfEnds {0}; if (myfile.is_open() && !myfile.eof() ) { while (myfile.good()) { std::getline(myfile, myString); // pipe file's content into stream if (std::regex_search(myString, start)){ numberOfStarts++; } else if (std::regex_search(myString, end)){ numberOfEnds++; } else if ( myString.empty()){ std::cerr << "ERROR: Empty line found. Bad positions file. " << std::endl; exit (EXIT_FAILURE); } } } if (numberOfStarts==numberOfEnds){ return numberOfStarts; } else { std::cerr << "Number of starts is not the same as number of ends. Bad input file." << std::endl; return 0; } } When I ran this code, I was exiting with the std::cerr << "ERROR: Empty line found. Bad positions file. " << std::endl; exit (EXIT_FAILURE); error. I could not locate the error until I opened positions.txt and DELETING the final line. What is going wrong here? Why is Vim showing something like this? I need the empty line error message because I do not want an interruption in the input file. I want coordinates at each line to not corrupt other parts of the code. Any advice you have for me will be appreciated. edit: using xxd on positions.txt, I get the following [faraway_server] src $ xxd positions.txt 00000000: 5354 4152 5420 504f 4c59 4d45 5220 310a START POLYMER 1. 00000010: 3120 3020 3020 0a32 2030 2030 0a33 2030 1 0 0 .2 0 0.3 0 00000020: 2030 0a34 2030 2030 0a34 2031 2030 0a35 0.4 0 0.4 1 0.5 00000030: 2031 2030 0a35 2030 2030 200a 3620 3020 1 0.5 0 0 .6 0 00000040: 3020 0a45 4e44 2050 4f4c 594d 4552 2031 0 .END POLYMER 1 00000050: 0a What should I do next?
There is only one newline (\n) after the last line with text so the fact that you read one empty line is due to a bug in your program. This: while (myfile.good()) { std::getline(myfile, myString); should be this: while (std::getline(myfile, myString)) { See Why is iostream::eof() inside a loop condition (i.e. while (!stream.eof())) considered wrong?
70,431,146
70,431,271
Sorting by struct data inside unordered_map
I have an std::unordered_map<id, town_data> data, where town_data is a struct of different information - name (string), taxes collected (int) and distance from capital town (int). I'm supposed to build a std::vector<id>, which is sorted by beforementioned distance, lowest to high. I'm quite struggling to figure out how can this be done efficiently. I suppose I could simply loop through the data, create std::map<distance, id> through that loop/insertion, sort it by distance unless maps are sorted by default, and copy it key by key to new vector, std::vector<id>. But this seems really wasteful approach. Am I missing some shortcut or more efficient solution here?
You could create a std::vector of iterators into the map and then sort the iterators according to your sorting criteria. After sorting, you could transform the result into a std::vector<id>. Create a std::vector of iterators: std::vector<decltype(data)::iterator> its; its.reserve(data.size()); for(auto it = data.begin(); it != data.end(); ++it) its.push_back(it); Sort that std::vector: #include <algorithm> // std::sort, std::transform std::sort(its.begin(), its.end(), [](auto& lhs, auto&rhs) { return lhs->second.distance < rhs->second.distance; }); And finally, transform it into a std::vector<id>: #include <iterator> // std::back_inserter std::vector<id> vec; vec.reserve(its.size()); std::transform(its.begin(), its.end(), std::back_inserter(vec), [](auto it) { return it->first; });
70,431,452
70,431,525
Why "ios::sync_with_studio(0) and cin.tie(0);" doesn't work with strings in C++
I was solving one problem using C++ where I have to take a string as an input. So instead of using the standard input/output method, I tried to use fast input/output method. #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_studio(0); cin.tie(0); string str; cin>>str; cout<<str; return 0; } it shows an error:- error: 'sync_with_studio' is not a member of 'std::ios {aka std::basic_ios<char>}' ios::sync_with_studio(0); ^~~ but if I use ios_base::sync_with_stdio(false); cin.tie(NULL); it worked. can someone tell why the above code doesn't work and why this work
That's the way it is. You need to make sure that you're writing the names correctly. You can always take a look at https://en.cppreference.com/w/. But in this case, check this: std::ios_base::sync_with_stdio Also keep in mind that if set to false, the C++ standard stream objects such as cout, clog, cerr, wcout, etc. will not be synchronized and you might see unexpectedly interleaved output if you mix them.
70,432,293
70,432,381
Dealing with unsigned integers
I know that unsigned integers are infamous and generally avoided by C++ devs. I have a class with two int member variables that should not contain negative values: . . . private: int m_Y_AxisLen; int m_X_AxisLen; . . . I have designed the logic of the member functions in a way that prevents any input of negative numbers. So I have made sure that those two members won't be assigned negative values. But this also brings up some warnings when I use PVS-Studio. For example here: for ( int row = 0; row < getY_AxisLen( ); ++row ) { for ( int column = 0; column < getX_AxisLen( ) - 1; ++column ) { if ( m_characterMatrix[ row ][ column ] == getFillCharacter( ) ) { m_characterMatrix[ row ][ column ] = fillCharacter; } } } PVS-Studio blames me for the indices row and column not being of memsize type. It probably means that I should have used std::size_t row and std::size_t column?? But if I had done it that way then it would still complain and say that comparing unsigned integral type with getY_AxisLen( ) (which returns an int) is dangerous. So this is the reason that I want to rewrite parts of my class to switch to this: private: uint32_t m_Y_AxisLen; uint32_t m_X_AxisLen; I am humbly looking for insights and advice from professionals who have dealt with these kinds of problems before. What would be your approach when it comes to these issues?
A lot of those "you shouldn't use unsigned integers" are just basically scared that you will mix up signed integers and unsigned ones, causing a wrap-around, or to avoid complex integer promotion rules. But in your code, I see no reason not to use uint32_t and std::size_t, because m_X_AxisLen and m_Y_AxisLen should not contain negative values, and using uint32_t and std::size_t makes a lot more sense here: So, I suggest changing m_X_AxisLen and m_Y_AxisLen to: std::size_t m_Y_AxisLen; std::size_t m_X_AxisLen; // for consistency Change row and column to std::size_t row = 0; // and std::size_t column = 0; Make getX_AxisLen( ) returns an std::size_t And make the for loop: for ( int column = 0; column < getX_AxisLen( ) - 1; ++column ) to: for ( int column = 0; column + 1 < getX_AxisLen( ); ++column ) Because if getX_AxisLen() returns 0, getX_AxisLen( ) - 1 will cause a wrap-around. Basically, use the thing that makes sense. If a value cannot be negative, use the unsigned type.
70,432,554
70,433,055
gtkmm hello world error: glibmm/ustring.h: No such file or directory
I am new to GTK and gtkmm. I have been trying to compile an example hello world code for gtkmm which resulted in a gtkmm/button.h: No such file or directory I fixed this by providing the header path, but now I am getting this new error which I am unable to fix. In file included from /home/kshitij/Tutorials/HMI/libhelloworld/helloworld.h:4, from /home/kshitij/Tutorials/HMI/main.cc:1: /usr/include/gtkmm-3.0/gtkmm/button.h:6:10: fatal error: glibmm/ustring.h: No such file or directory 6 | #include <glibmm/ustring.h> | ^~~~~~~~~~~~~~~~~~ compilation terminated. make[2]: *** [CMakeFiles/main.dir/build.make:63: CMakeFiles/main.dir/main.cc.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/main.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 Below I am attaching the tree and the code files and the CMake file for reference. Please let me know if more details are required. Tree: ├── build ├── CMakeLists.txt ├── libhelloworld │   ├── CMakeLists.txt │   ├── helloworld.cc │   └── helloworld.h └── main.cc main.cc #include "libhelloworld/helloworld.h" #include <gtkmm/application.h> int main (int argc, char *argv[]) { auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example"); HelloWorld helloworld; //Shows the window and returns when it is closed. return app->run(helloworld); } helloworld.cc #include "helloworld.h" #include <iostream> HelloWorld::HelloWorld() : m_button("Hello World") // creates a new button with label "Hello World". { // Sets the border width of the window. set_border_width(10); // When the button receives the "clicked" signal, it will call the // on_button_clicked() method defined below. m_button.signal_clicked().connect(sigc::mem_fun(*this, &HelloWorld::on_button_clicked)); // This packs the button into the Window (a container). add(m_button); // The final step is to display this newly created widget... m_button.show(); } HelloWorld::~HelloWorld() { } void HelloWorld::on_button_clicked() { std::cout << "Hello World" << std::endl; } helloworld.h #ifndef GTKMM_EXAMPLE_HELLOWORLD_H #define GTKMM_EXAMPLE_HELLOWORLD_H #include <gtkmm-3.0/gtkmm/button.h> #include <gtkmm/window.h> class HelloWorld : public Gtk::Window { public: HelloWorld(); virtual ~HelloWorld(); protected: //Signal handlers: void on_button_clicked(); //Member widgets: Gtk::Button m_button; }; #endif // GTKMM_EXAMPLE_HELLOWORLD_H CMake # Set the name and the supported language of the project project(hello-world C CXX) # Set the minimum version of cmake required to build this project cmake_minimum_required(VERSION 3.10) add_subdirectory(libhelloworld) add_executable(main main.cpp) target_link_libraries(main PUBLIC libhelloworld) libhelloworld/CMake # Set the name and the supported language of the project project(hello-world C CXX) # Set the minimum version of cmake required to build this project cmake_minimum_required(VERSION 3.10) find_package(PkgConfig REQUIRED) pkg_check_modules(gtkmm REQUIRED IMPORTED_TARGET gtkmm-3.0 glibmm-2.4) add_library(libhelloworld helloworld.cc) target_link_libraries(libhelloworld PUBLIC PkgConfig::gtkmm) Edit 1: The changes suggested seem to solve the error but now I am getting this error instead. /usr/bin/ld: cannot find -llibhelloworld collect2: error: ld returned 1 exit status make[2]: *** [CMakeFiles/main.dir/build.make:104: main] Error 1 make[1]: *** [CMakeFiles/Makefile2:96: CMakeFiles/main.dir/all] Error 2 make: *** [Makefile:84: all] Error 2
Your CMake file does not actually use glibmm, it just searches for it. Here is a modernized version of your libhelloworld/CMakeLists.txt: # Set the name and the supported language of the project project(hello-world C CXX) # Set the minimum version of cmake required to build this project cmake_minimum_required(VERSION 3.10) find_package(PkgConfig REQUIRED) pkg_check_modules(gtkmm REQUIRED IMPORTED_TARGET gtkmm-3.0 glibmm-2.4) add_library(libhelloworld helloworld.cc) target_link_libraries(libhelloworld PUBLIC PkgConfig::gtkmm) The IMPORTED_TARGET option creates a special target that automatically configures the header and library search path. Your main CMakeLists.txt can now use that target as follows: # Set the name and the supported language of the project project(hello-world C CXX) # Set the minimum version of cmake required to build this project cmake_minimum_required(VERSION 3.10) add_subdirectory(libhelloworld) add_executable(main main.cpp) target_link_libraries(main PUBLIC libhelloworld)
70,432,629
70,437,243
How to use C++ module :private fragment with templates?
I'm experimenting with C++20 to better understand how they work in practice. I learned about the module :private fragment that can be used to separate the interface from the implementation, while keeping both in the same file. That seems to work for standard functions, but not for template functions. I have the following files: // File "main.cpp" #include <iostream> import mymodule; int main() { std::cout << "greeting(): " << mymodule::greetings() << std::endl; int x = 1; int y = 2; std::cout << "add(x, y): " << mymodule::add(x, y) << std::endl; } // File "mymodule.ixx" module; #include <string> // declare interface export module mymodule; export namespace mymodule { template<typename T> T add(T x, T y); std::string greetings(); } // implement interface module :private; std::string mymodule::greetings() { return "hello"; } template<typename T> T mymodule::add(T x, T y) { return x + y; } And get a compiler warning and a linker error (using Visual Studio 2022, MSVC): Rebuild started... 1>------ Rebuild All started: Project: PlayingWithModules, Configuration: Debug x64 ------ 1>Scanning sources for module dependencies... 1>mymodule.ixx 1>Compiling... 1>mymodule.ixx 1>C:\Users\Sam\Development\Cpp\Sandbox\PlayingWithModules\mymodule.ixx(29,13): warning C5226: 'mymodule::add': exported template defined in private module fragment has no reachable instantiation 1>main.cpp 1>main.obj : error LNK2019: unresolved external symbol "int __cdecl mymodule::add<int>(int,int)" (??$add@H@mymodule@@YAHHH@Z::<!mymodule>) referenced in function main 1>C:\Users\Sam\Development\Cpp\Sandbox\x64\Debug\PlayingWithModules.exe : fatal error LNK1120: 1 unresolved externals 1>Done building project "PlayingWithModules.vcxproj" -- FAILED. ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ========== My understanding is that mymodule::greetings() is fine, but mymodule::add(x, y) is not because the function call mymodule::<int, int>(x, y) cannot be seen by the compiler, which results in no function <int, int> being generated. If I instead implement the template function as part of the interface: module; #include <string> // declare interface export module mymodule; export namespace mymodule { template<typename T> T add(T x, T y) { return x + y; } std::string greetings(); } // implement interface module :private; std::string mymodule::greetings() { return "hello"; } Then everything compiles and works as expected. Is it possible to use module :private with function template, and if yes how? Or should template functions always be implemented as part of the interface? I cannot find details online regarding templates usage in the context of modules, and cannot find references to the compiler warning I get.
Modules do not change the nature of C++, merely how you access different components. It is part of the nature of C++ that, in order for a translation unit to use a template, that translation unit must have access to the definition of that template. Modules doesn't change that. The private module fragment specifically contains things that are not part of the interface of the module. That's the whole point of them: to be able to stick something that isn't part of the interface into a module file. A private module fragment therefore can only contain the stuff that you would put into a traditional .cpp file. Indeed, that's why they exist: so that (for short modules) you can put all the usual .cpp stuff in a single file without affecting what gets generated by the module.
70,432,649
70,433,994
Why do I see strange UDP fragmentation on my C++ server?
I have build an UDP server with C++ and I have a couple questions about this. Goal: I have incomming TCP trafic and I need to sent this further as UDP trafic. My own UDP server then processes this UDP data. The size of the TCP packets can vary. Details: In my example I have a TCP packet that consists of a total of 2000 bytes (4 random bytes, 1995 'a' (0x61) bytes and the last byte being 'b' (0x62)). My UDP server has a buffer (recvfrom buffer) with size larger then 2000 bytes. My MTU size is 1500 everywhere. My server is receiving this packet correctly. In my UDP server I can see the received packet has a length of 2000 and if I check the last byte buffer[1999], it prints 'b' (0x62), which is correct. But if I open tcpdump -i eth0 I see only one UDP packet: 09:06:01.143207 IP 192.168.1.1.5472 > 192.168.1.2.9000: UDP, bad length 2004 > 1472. With the tcpdump -i eth0 -X command, I see the data of the packet, but only ~1472 bytes, which does not include the 'b' (0x62) byte. The ethtool -k eth0 command prints udp-fragmentation-offload: off. So my questions are: Why do I only see one packet and not two (fragmented part 1 and 2)? Why dont I see the 'b' (0x62) byte in the tcpdump? In my C++ server, what buffer size is best to use? I have it now on 65535 because the incomming TCP packets can be any size. What will happen if the size exceedes 65535 bytes, will I have to make an own fragmentation scheme before sending the TCP packet as UDP?
OK, circumstances are more complicated as they appear from question, extracted from your comments there's the following information available: Some client sends data to a server – both not modifiable – via TCP. In between both resides a firewall, though, only allowing uni-directional communication to server via UDP. You now intend to implement a proxy consisting of two servers residing in between and tunneling TCP data via UDP. Not being able for the server to reply backwards does not impose a problem either. My personal approach would then be as follows: Let the proxy servers be entirely data unaware! Let the outbound receiver accept (recv or recvfrom depending on a single or multiple clients being available) chunks of data that yet fit into UDP packets and simply forward them as they are. Apply some means to assure lost data is at least detected, better such that lost data can be reconstructed. As confirmation or re-request messages are impossible due to firewall limitation, only chance to increase reliability is via redundancy, though. Configure the final target server to listen on loopback only. Let the inbound proxy connect to the target server via TCP and as long as no (non-recoverable) errors occur just forward any incoming data as is. To be able to detect lost messages I'd at very least prepend a packet counter to any UDP message sent. If two subsequent messages do not provide consecutive counter values then a message has been lost in between. As no communication backwards is possible the only way to increase reliability is unconditional redundancy, trading some of your transfer rate for, e.g. by sending every message more than once and ignoring surplus duplicates on reception side. A more elaborate approach might distribute redundant data over several packets such that a missing one can be reconstructed from the remaining ones – maybe similar to what RAID level 5 does. Admitted, you need to be pretty committed to try that... Final question would be how routing looks like. There's no guarantee with UDP for packets being received in the same order as they are sent. If there's really only one fix route available from outbound proxy to inbound one via firewall then packets shouldn't overtake one another – you might still want to at least log to file appropriately to monitor the inbound UDP packets and in case of errors occurring apply appropriate means (buffering packets and re-ordering them if need be).
70,432,999
70,434,636
What is mbstate_t and why to reset it?
Could you please explain to me what exactly is mbstate_t? I have read the cppreference description, but I still don't understand its purpose. What I do understand is that mbstate_t is some static struct visible for a limited set of functions like mbtowc(), wctomb() etc., but I am still confused about how to use it. I can see in cppreference examples that this struct should be reset before calling some functions. Assume, I want to count characters in a multi-language string like this one: std::string str = "Hello! Привет!"; Apparently, str.size() cannot be used in this example, because it simply returns the number of bytes in the string. But something like this does the job: std::locale::global(std::locale("")); // Linux, UTF-8 std::string str = "Hello! Привет!"; std::string::size_type stringSize = str.size(); std::string::size_type nCharacters = 0; std::string::size_type nextByte = 0; std::string::size_type nBytesRead = 0; std::mbtowc(nullptr, 0, 0); // What does it do, and why is it needed? while ( (nBytesRead = std::mbtowc(nullptr, &str[nextByte], stringSize - nextByte)) != 0) { ++nCharacters; nextByte += nBytesRead; } std::cout << nCharacters << '\n'; According to cppreference examples, before entering the while loop mbstate_t struct should be reset by calling mbtowc() with all arguments being zeros. What is the purpose of this?
The interface to mbtowc is kind of crazy. A historical mistake, I guess. You are not required to pass it a complete string, but can pass a buffer (perhaps a network package) that ends in an incomplete multi-byte character. And then pass the rest of the character in the next call. So mbtowc will have to store its current (possibly partial) conversion state between calls. Possibly as a static variable. A call to std::mbtowc(nullptr, 0, 0); will clear this internal state, so its is ready for a new string. You might want to use mbrtowc instead and provide a non-hidden mbstate_t as an extra parameter. https://en.cppreference.com/w/cpp/string/multibyte/mbrtowc
70,433,152
70,434,490
Missed optimization with string_view::find_first_of
Update: relevant GCC bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103798 I tested the following code: #include <string_view> size_t findFirstE_slow(std::string_view sv) { return sv.find_first_of("eE"); } size_t findFirstE_fast(std::string_view sv) { auto it{sv.begin()}; for (; it != sv.end() && *it != 'e' && *it != 'E'; ++it) ; return it == sv.end() ? std::string_view::npos : size_t(it - sv.begin()); } quick-bench test: https://quick-bench.com/q/dSU3EBzI8MtGOFn_WLpK3ErT3ok Compiler Explorer output: https://godbolt.org/z/eW3sx61vz Both findFirstE_slow() and firstFirstE_fast() functions are meant to do the same thing, but findFirstE_slow() runs significantly slower (at least 5x on the quick-bench test). Here's the assembly output for x86-64 gcc (trunk) -std=c++20 -O3. findFirstE_slow(): .LC0: .string "eE" findFirstE_slow(std::basic_string_view<char, std::char_traits<char> >): push r12 push rbp push rbx test rdi, rdi je .L4 mov rbx, rdi mov rbp, rsi xor r12d, r12d jmp .L3 .L8: add r12, 1 cmp rbx, r12 je .L4 .L3: movsx esi, BYTE PTR [rbp+0+r12] mov edx, 2 mov edi, OFFSET FLAT:.LC0 call memchr test rax, rax je .L8 mov rax, r12 pop rbx pop rbp pop r12 ret .L4: mov r12, -1 pop rbx pop rbp mov rax, r12 pop r12 ret findFirstE_fast(): findFirstE_fast(std::basic_string_view<char, std::char_traits<char> >): add rdi, rsi cmp rdi, rsi je .L13 mov rax, rsi jmp .L12 .L15: add rax, 1 cmp rdi, rax je .L13 .L12: movzx edx, BYTE PTR [rax] and edx, -33 cmp dl, 69 jne .L15 sub rax, rsi ret .L13: mov rax, -1 ret Interestingly, findFirstE_slow() calls memchr("eE", *current_char, 2) for every character in sv. On the other hand, findFirstE_fast() does what we would reasonably expect, by comparing each character in sv with 'e' and 'E'. Clang generates similar output. Question: Is there a missed optimization here for short strings like the one in my test? Am I missing something to get GCC to generate faster code?
libstdc++'s std::string_view::find_first_of looks something like: size_type find_first_of(std::string_view v, std::size_t pos = 0) { if (v.empty()) return npos; for (; pos < size(); ++pos) { const char_type* p = traits_type::find(v.data(), v.size(), this->data()[pos]); if (p) return pos; } return npos; } You can see how traits_type::find gets transformed into memchr. The crux of the issue is that memchr("eE", this->data()[pos], 2) != nullptr isn't compiled the same way as this->data()[pos] == 'e' || this->data()[pos] == 'E', even though the latter is much more efficient. You can check this by trying to compile this: constexpr unsigned char characters[] = "eE"; bool a(unsigned char* p) { return __builtin_memchr(characters, *p, 2); } bool b(unsigned char* p) { return *p == characters[0] || *p == characters[1]; } This is a missed optimisation, but you can hint to the compiler to not use memchr with a custom traits type: struct char_traits : std::char_traits<char> { static constexpr const char_type* find(const char_type* p, std::size_t count, const char_type& ch) { if (__builtin_constant_p(count) && count < 5) { switch (count) { case 0: return nullptr; case 1: return ch == *p ? p : nullptr; case 2: return ch == *p ? p : ch == *++p ? p : nullptr; case 3: return ch == *p ? p : ch == *++p ? p : ch == *++p ? p : nullptr; case 4: return ch == *p ? p : ch == *++p ? p : ch == *++p ? p : ch == *++p ? p : nullptr; } } return std::char_traits<char>::find(p, count, ch); } }; using string_view = std::basic_string_view<char, char_traits>; size_t findFirstE_slow(string_view sv) { return sv.find_first_of(characters); } // Also your "fast" version needs to return // return it == sv.end() ? string_view::npos : size_t(it - sv.begin()); // to be equivalent (https://godbolt.org/z/bhPPxjboE) And https://quick-bench.com/q/QVxVTxGEagUUCPuhFi9T8wjI1qQ says the slow version is now only 1.3x slower. Using a larger string (https://quick-bench.com/q/el0ukDywBNMoGsEb33PM_g4WUaY; 8000 chars before an 'e'), the difference is mostly unnoticeable. The main difference now is that one iterates over indices and the other over pointers (returning the difference at the end). The two differing instructions in the assembly are movzx edx, BYTE PTR [rsi+rax] and movzx edx, BYTE PTR [rax] sub rax, rsi, where you should find the second version is ever so slightly faster (especially asymptotically, since the subtraction happens outside the loop)
70,433,778
70,434,114
C++ dynamically linked library and void pointer
I'm in the following situation: I'm writing a C++ program which has to dynamically load a C++ library (i.e. via dlopen and friends in Linux and LoadLibrary and friends in Windows). This can be done creating a C interface. Now, both in the program and in the library I manage some object which has some specified template members and some methods: struct MyObject { std::vector<int> _vec; //... void do_something(); }; Now, if the library would have loaded statically I would have written a library function such as void some_function(MyObject& o); but since it is dynamically loaded I need some other signature. I was thinking the following: a common header like //interface.hpp extern "C" { void ob_w(void*); } struct MyObject { //... } Then, on the library side //lib.cpp #include "interface.hpp" void ob_w(void* ptr) { MyObject* p = (MyObject*)ptr; p->do_something(); } and, for the main program //main.cpp #include "interface.hpp" int main() { void* handle = nullptr; void (*fptr)(void*); handle = dlopen(...) fptr = dlsym(...) MyObject foo; fptr((void*)&foo); //... } Looking around I found other similar questions, but in all of them the library was written in C and so different solution were adopted. Here both library and program are written in C++ and the void pointer is there just to avoid some adaptors. I would like to know whether my approach is correct (I tried on a linux machine and seems go give the correct result) and safe. In the case it is not, how could I pass the pointer of the object without introducing any overhead (for instance of some adaptor)?
Hoisting my comment into an answer: you definitely don’t need to change the signature of your function to make it work with dynamic linking, if you’re happy to require C++. That is, the following works: extern "C" void some_function(MyObject& o) { o.do_something(); } And then you could have a main.cpp as follows (fragment): void* lib = dlopen("myobject.so", RTLD_LAZY); if (not lib) fail_spectacularly(); void (*some_function)(MyObject&) = reinterpret_cast<decltype(some_function)>(dlsym(lib, "some_function")); if (not some_function) fail_spectacularly(); MyObject obj = whatever; some_function(obj);