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,057,456
70,057,559
No type named 'iterator_category' in 'struct std::iterator_traits<int* const>'
I'm writing a custom vector class: #include <iterator> template <typename T> class vector { public: using value_type = T; using pointer = value_type*; using iterator = pointer; using const_iterator = const iterator; using const_reverse_iterator = std::reverse_iterator<const_iterator>; auto crbegin() const -> const_reverse_iterator { return const_reverse_iterator(data_); } private: pointer data_{}; }; int main(int argc, char* argv[]) { vector<int> v; auto i = v.crbegin(); return 0; } When compiling the code above, I get this error (on GCC and MSVC): error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<int* const>’ The error goes away when I change the reverse iterator definition to std::reverse_iterator<const T*>. What's the difference compared to std::reverse_iterator<const_iterator>?
The problem can be reduced to this: #include <iterator> template <typename T> class vector { public: using value_type = T; using pointer = value_type*; using const_reverse_iterator = std::reverse_iterator<const pointer>; auto crbegin() const -> const_reverse_iterator { return const_reverse_iterator(data_); } private: pointer data_{}; }; int main() { vector<int> v; auto i = v.crbegin(); (void) i; return 0; } And the error message from clang makes the nature of the problem clearer: no type named 'reference' in 'std::iterator_traits<int *const>' ^^^^^^^^^^ And so we see that what you thought was a const *int (i.e. the pointed-to object is const) is in fact an int *const (i.e the pointer itself is const). Here's a simple fix: #include <iterator> template <typename T> class vector { public: using value_type = T; using pointer = value_type*; using const_pointer = const value_type*; using const_reverse_iterator = std::reverse_iterator<const_pointer>; auto crbegin() const -> const_reverse_iterator { return const_reverse_iterator(data_); } private: pointer data_{}; }; int main() { vector<int> v; auto i = v.crbegin(); (void) i; return 0; } Live demo
70,057,585
70,057,640
How to convert java merge sort algo to cpp
Problem I have a source code in Java for sorting array elements using the merge sort algorithm. The principle uses a loop to compare an element in the array with the element in the next index in the array. If the earlier is bigger than the later then the numbers are swapped logically to reassign the array elements in the indices. My problem is that the Java algo works but the C++ algo does not. The logic is the same, what am I doing wrong.... Code Working Java Code static void sort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } C++ Code built on the same merge sort pseudocode as the Java Source code but fails to work void sorting(int d[]) { for (int i = 0; i < sizeof(d); i++) { for (int j = i + 1; j < sizeof(d); j++) { if (d[i] > d[j]) { int temp = d[i]; d[i] = d[j]; d[j] = temp; } } } } Input Format Both methods got parameters from arrays initialized to a fixed size and then a loop was used to get input from user and asign to the array, the user has to enter the size of the array first. Reliability of the merge sort algo in other languages I have applied the mergesort pseudocode in JavaScript, Python and C# and they all worked. I do not know why C++ would be an exception, please help...
For starters there is no merge sort algorithm in your question. In fact there is a modified selection sort algorithm. This function declaration void sorting(int d[]) is adjusted by the compiler to the declaration void sorting(int *d) That is the parameter has a pointer type. So the expression sizeof(d) yields the size of a pointer not the number of element in the passed array. You need also to pass to the function the number of elements in the array. The function can look the following way void sorting( int a[], size_t n ) { for ( size_t i = 0; i < n; i++ ) { size_t min = i; for ( size_t j = i + 1; j < n; j++ ) { if ( a[j] < a[min] ) min = j; } if ( i != min ) std::swap( a[i], a[min] ); } } Another approach is using a template function that accepts an array by reference. For example template <size_t N> void sorting( int ( &a )[N] ) { for ( size_t i = 0; i < N; i++ ) { size_t min = i; for ( size_t j = i + 1; j < N; j++ ) { if ( a[j] < a[min] ) min = j; } if ( i != min ) std::swap( a[i], a[min] ); } } Here is a demonstration program that shows usage of the two functions. #include <iostream> #include <utility> void sorting( int a[], size_t n ) { for (size_t i = 0; i < n; i++) { size_t min = i; for (size_t j = i + 1; j < n; j++) { if (a[j] < a[min]) min = j; } if (i != min) std::swap( a[i], a[min] ); } } template <size_t N> void sorting( int ( &a )[N] ) { for (size_t i = 0; i < N; i++) { size_t min = i; for (size_t j = i + 1; j < N; j++) { if (a[j] < a[min]) min = j; } if (i != min) std::swap( a[i], a[min] ); } } int main() { int a[] = { 5, 4, 3, 2, 1 }; for (const auto &item : a) { std::cout << item << ' '; } std::cout << '\n'; sorting( a, sizeof( a ) / sizeof( *a ) ); for (const auto &item : a) { std::cout << item << ' '; } std::cout << '\n'; int b[] = { 5, 4, 3, 2, 1 }; for (const auto &item : b) { std::cout << item << ' '; } std::cout << '\n'; sorting( b ); for (const auto &item : b) { std::cout << item << ' '; } std::cout << '\n'; } The program output is 5 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5
70,057,715
70,079,186
How to #include inside .cpp file?
In the following example, the FileA header is included in FileB header; Some of the classes in FileB.h are forwardly declared inside FileA.h; in FileA.h //Forward Declaration. class classB; //Main classes. class ClassA { //... private: void MemberFunction(ClassB* PtrToClassBObj); } In FileB.h //Includes. #include FileA.h //Main classes. class ClassB { //... public: int MemberVariable = 0; } Then in FileA.cpp #include FileA.h //Member functions definitions. void ClassA::MemberFunction(ClassB* PtrToClassBObj) { if(PtrToClassBObj) PtrToClassBObj->MemberVariable++; } Is that enough to make FileA.cpp capable of accessing public members of said classes from FileB.h? or should FileA.cpp itself include FileB.h? And was the forward declaration needed (assuming no use of the class name inside FileA.h, and only used inside FileA.cpp exclusively)? What is the general best practice advice if any?
Is that enough to make FileA.cpp capable of accessing public members of said classes from FileB.h? No, it is not "enough" - the full definition of ClassB needs to be visible. or should FileA.cpp itself include FileB.h? It should, because it uses the class at PtrToClassBObj->MemberVariable. was the forward declaration needed As presented, no - you can remove #include FileA.h from FileB and make FileA include FileB. (assuming no use of the class name inside FileA.h, and only used inside FileA.cpp exclusively)? Assuming there is no use of ClassB inside FileA.h, there is no use for forward declaring ClassB, so the forward declaration is not needed. The assumption conflicts with presented code, as the symbol ClassB is used in ClassA::MemberFunction declaration. What is the general best practice advice if any? Follow code guidelines. Do not write spaghetti code and do not have circular dependencies. Prefer clear, easy-to-understand, readable code structured in a hierarchical tree. Compile with all warnings enabled, use code linters and sanitizers. Exercise regularly. Eat healthy.
70,057,831
70,058,075
Why is not possible to have a queue implemented as a vector?
What are the drawbacks of using a std::vector for simulating a queue? I am naively thinking that push_back is used for push and for pop one just stores the position of the first element and increments it. Why does not std::queue allow a std::vector implementation like this in principle (I know the reason is it has no push_front method, but maybe there is something deeper that makes it slow this way)? Thank you for helping.
Why does not std::queue allow a std::vector implementation like this std::queue is a simple container adapter. It works by delegating pop function to the pop_front function of the underlying container. Vector has no pop front operation, so std::queue cannot adapt it. but maybe there is something deeper that makes it slow this way Pushing and popping from the front of the vector is slow because it has to shift all elements which has linear cost. This is why vector doesn't provide pop_front. stores the position of the first element and increments it. It's possible to implement a container that does store the position of first element within a buffer, but vector is not an implementation of such container. Storing that position has an overhead that vector doesn't need to pay, and so it doesn't.
70,058,063
70,058,099
c++ opengl 4.5 doesn't show the object
I writed code which must to show triangle but it doesn't. I really don't know where is problem. I checked everything and don't find out what is the problem. If you can please help me. Here is code: #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm.hpp> int width = 800, height = 600; int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(width, height, "engine", NULL, NULL); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); glViewport(0, 0, width, height); const char* VertexShaderData = "#version 450 core\n" "layout(location = 0) in vec2 pos;\n" "void main(){\n" "gl_Position = vec4(pos, 0, 1);\n" "}\0"; GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexShader, 1, &VertexShaderData, NULL); glCompileShader(VertexShader); const char* FragmentShaderData = "#version 450 core\n" "out vec4 Color;\n" "void main(){\n" "Color = vec4(0.25, 0.8, 0.65, 1);\n" "}\0"; GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentShader, 1, &FragmentShaderData, NULL); glCompileShader(FragmentShader); GLuint ShaderProgram = glCreateProgram(); glAttachShader(ShaderProgram, VertexShader); glAttachShader(ShaderProgram, FragmentShader); glLinkProgram(ShaderProgram); float Points[] = { -1, -1, 0, 1, 1, -1 }; GLuint VAO, VBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0); glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW); glClearColor(0.3, 0.5, 0.7, 1); while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(VAO); glEnableVertexAttribArray(0); glUseProgram(ShaderProgram); glDrawArrays(GL_TRIANGLES, 0, 3); } } Before I was believe what problem is in array, but now i don't think so. Problem is must be in something else.
The 2nd argument to glBufferData is the size of the buffer in bytes: glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, 6*sizeof(float), Points, GL_STATIC_DRAW);
70,058,259
70,058,359
How does copy constructor that returns value, discards the temp?
having this code: #include <iostream> class Base { public: Base() = default; explicit Base(int val) : _var(val) {} Base operator=(const Base &rhs) { _var = rhs._var; return *this; } void print() const { std::cout << _var << std::endl; } private: int _var; }; int main() { Base b[] = {Base(10), Base(), Base(), Base()}; (b[1] = b[2]) = b[0]; for (Base base: b) { base.print(); } } the output is: 10 0 0 0 but I would expect 10 10 0 0 As the second element in array b[1] should get assign from b[0], but the assignment operator returns value, not reference and thus copy-constructing happen. But still, why is not b[1] copy-constructed to have _var=10? If the operator= returned Base &, the output would be my expectation
To get the desired result of your assignment operator (which, by the way, is different from copy constructor), you need to return a reference: Base& operator=(const Base &rhs) This is the canonical form. Without the reference, the result of (b[1] = b[2]) is stored in a temporary. (b[1] = b[2]) = b[0]; assigns to that temporary, which is discarded and has no effect on b[1].
70,058,310
70,058,452
What is the big-O of this for loop...?
The first loop runs O(log n) time but the second loop's runtime depends on the counter of the first loop, If we examine it more it should run like (1+2+4+8+16....+N) I just couldn't find a reasonable answer to this series... for (int i = 1; i < n; i = i * 2) { for (int j = 1; j < i; j++) { //const time } }
It is like : 1 + 2 + 4 + 8 + 16 + ....+ N = 2 ^ [O(log(N) + 1] - 1 = O(N)
70,058,519
70,058,586
Data lost after assigning object to linked list and jumping between functions (C++)
I am trying to implement an application that will involve creating a custom object (containing pointer to another customer object) and organising them into a linked list. I have created some functions to attempt to add them to linked list. Based on debugging using gdb, all values are passed to Event constructor and addEvent() function without problem, but once jumping back to the main test programme, at least some values (such as timestamp and value in EventValue) are turned into gibberish, and I have no idea where in the process they are lost. This is the info I got from gdb - as can be seen the timestamp is changed into gibberish: (Event &) @0x7fffffffd8a0: { type = "P\222yUUU\000\000P\222yUUU\000\000\001\000\000\000\000\000\000\000\062\000\000\000UU\000\000C", '\000' <repeats 79 times>, "\220\213xUUU", '\000' <repeats 13 time s>, "\004\000\000\000\000\300C\302\367\377\177\000\000\000\000\000\000\000\000\000\000\300C\302\367\377\177\000\000`\263xUUU\000\000p\333\377\377\377\177\000\000\000\265A\3 54\070\065\256\374\337\333\377\377\377\177\000\000\001\000\000\000\000\000\000\000"..., ev = 0x7fffffffd8f0, timestamp = 93824994611792} I have tried things like building/removing copy constructors but nothing seems to have worked so far. I have been working on this for days without a clue so any help on this is appreciated! Snippets of the test programme below: SECTION("Adding an event to an instance works") { ... application.addEventToApplication(50, {"measurement", 12345}); application.addEventToApplication(50, {"measurement", 123456, new EventValue{200}}); ... } template <t> void addEventToApplication(long Id, Event&& e) { ... applicationInstance.addEvent(std::move(e)); ... } A brief structure of the objects and functions as follows: class EventValue{ private: long value = 0; public: EventValue(long value); long getValue() const; void setValue(long value); }; class Event{ private: std::string type; EventValue* ev = nullptr; long timestamp; public: Event& operator=(Event const& other); Event(Event const& other); ~Event(); Event(std::string type, long timestamp, EventValue* ev); Event(std::string type, long timestamp); }; class EventNode{ public: Event& data; EventNode* next = nullptr; EventNode(Event& e); }; EventNode::EventNode(Event& e) : data(e){}; Event::Event(string type, long timestamp, EventValue* ev) : type(type), timestamp(timestamp), ev(ev){}; Event::Event(string type, long timestamp) : type(type), timestamp(timestamp){}; Event& Event::operator=(Event const& other){ if (other.ev != nullptr){ this->ev = new EventValue(*other.ev); } else { this->ev = nullptr; } this->timestamp = other.timestamp; this->type = other.type; return *this; } Event::Event(Event const& other){ *this = other; } Event::~Event(){ delete ev; } void Roast::addEvent(Event e){ EventNode *tmpNode = new EventNode(e); if (eventList != nullptr){ tmpNode->next = eventList; } eventList = tmpNode; }
In addEvent, your line EventNode *tmpNode = new EventNode(e); will store a reference to e in your new node. Since you pass e by value, you've made a copy and this copy will be destroyed at the end of the function, so the reference stored in the event node will be dangling. You likely want to pass e by reference: void Roast::addEvent(Event &e) then you'll want to verify that whatever value is passed in will stay alive while the event exists.
70,058,537
70,059,740
Cannot read with `std::cin.read`: return key not recognized
I am trying to read a string from the keyboard with the std::cin.read() function. What happens is that it looks like the string is being read as I type it, but the [Return] character is treated as a normal new line, and not as a terminator. What is the terminator for this function? Is it possible to modify it? #include <iostream> char* text; char text_length = 0; int main() { std::cout << "Text length: "; std::cin.get(text_length); std::cout << "\nText length: " << text_length << std::endl; text = new char[1024]; std::cout << "\n\nText: "; std::cin.read(text, text_length); std::cout << "\n\nText: " << text << std::endl; return 0; } Code tested on: GCC 11, clang 13. OS: Linux.
On Windows console, the EOF indicator is Ctrl+Z (not the Ctrl+C, which will invoke a signal handler routine instead, which will call ExitProcess by default). But the problem with Ctrl+Z on Windows is that it has to be the first character of a separate line (i.e., you have to press Enter and then Ctrl+Z, otherwise the Ctrl+Z will not be recognized as an EOF). This means that the newline will also be read before EOF. The std::cin.get(text_length); line is not doing what you expect. It treats the input as a character, not as a number. So, if you press 5 and Enter, the extracted value will be 53 (the ASCII code for the character 5). Instead, do std::cin >> text_length;. Also, the text_length should be declared as std::streamsize, not as char. If it is supposed to fit in 8 bits, just clamp the value before further processing. There are other bugs as well: you don't null-terminate your buffer, and you never explicitly delete the memory dynamically allocated by new (although it will be freed implicitly when the OS ends the process, of course). To sum it up, check out this code: #include <algorithm> #include <iostream> #include <limits> int main() { constexpr std::streamsize min_text_length{ 0 }; constexpr std::streamsize max_text_length{ 255 }; char* text{ nullptr }; std::streamsize text_length{ 0 }; std::cout << "Enter text length: "; std::cin >> text_length; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Text length entered: " << text_length << '\n'; text_length = std::clamp(text_length, min_text_length, max_text_length); std::cout << "Text length to be used: " << text_length << '\n'; text = new char[max_text_length + 1]{}; // Note this zero-fills the buffer std::cout << "Enter text: "; std::cin.read(text, text_length); std::cout << "Text entered BEGINS-->" << text << "<--ENDS\n"; delete[] text; } After entering the length, enter some text, and when finished, press Enter, followed by Ctrl+Z, and Enter again. (As already mentioned, the newline character preceding the Ctrl+Z will unfortunately be read in as well, but at least the Ctrl+Z allows you to terminate the input.)
70,058,562
70,089,564
Align a matrix to a vector in OpenGL
I'm trying to visualize normals of triangles. I have created a triangle to use as the visual representation of the normal but I'm having trouble aligning it to the normal. I have tried using glm::lookAt but the triangle ends up in some weird position and rotation after that. I am able to move the triangle in the right place with glm::translate though. Here is my code to create the triangle which is used for the visualization: // xyz rgb float vertex_data[] = { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.25f, 0.0f, 0.025f, 0.0f, 1.0f, 1.0f, 0.25f, 0.0f, -0.025f, 0.0f, 1.0f, 1.0f, }; unsigned int index_data[] = {0, 1, 2}; glGenVertexArrays(1, &nrmGizmoVAO); glGenBuffers(1, &nrmGizmoVBO); glGenBuffers(1, &nrmGizmoEBO); glBindVertexArray(nrmGizmoVAO); glBindBuffer(GL_ARRAY_BUFFER, nmrGizmoVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, nrmGizmoEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_data), index_data, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glBindVertexArray(0); and here is the code to draw the visualizations: for(unsigned int i = 0; i < worldTriangles->size(); i++) { Triangle *tri = &worldTriangles->at(i); glm::vec3 wp = tri->worldPosition; glm::vec3 nrm = tri->normal; nrmGizmoMatrix = glm::mat4(1.0f); //nrmGizmoMatrix = glm::translate(nrmGizmoMatrix, wp); nrmGizmoMatrix = glm::lookAt(wp, wp + nrm, glm::vec3(0.0f, 1.0f, 0.0f)); gizmoShader.setMatrix(projectionMatrix, viewMatrix, nrmGizmoMatrix); glBindVertexArray(nrmGizmoVAO); glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } When using only glm::translate, the triangles appear in right positions but all point in the same direction. How can I rotate them so that they point in the direction of the normal vector?
Your code doesn't work because lookAt is intended to be used as the view matrix, thus it returns the transform from world space to local (camera) space. In your case you want the reverse -- from local (triangle) to world space. Taking an inverse of lookAt should solve that. However, I'd take a step back and look at (haha) the bigger picture. What I notice about your approach: It's very inefficient -- you issue a separate call with a different model matrix for every single normal. You don't even need the entire model matrix. A triangle is a 2-d shape, so all you need is two basis vectors. I'd instead generate all the vertices for the normals in a single array, and then use glDrawArrays to draw that. For the actual calculation, observe that we have one degree of freedom when it comes to aligning the triangle along the normal. Your lookAt code resolves that DoF rather arbitrary. A better way to resolve that is to constrain it by requiring that it faces towards the camera, thus maximizing the visible area. The calculation is straightforward: // inputs: vertices output array, normal position, normal direction, camera position void emit_normal(std::vector<vec3> &v, const vec3 &p, const vec3 &n, const vec3 &c) { static const float length = 0.25f, width = 0.025f; vec3 t = normalize(cross(n, c - p)); // tangent v.push_back(p); v.push_back(p + length*n + width*t); v.push_back(p + length*n - width*t); } // ... in your code, generate normals through: std::vector<vec3> normals; for(unsigned int i = 0; i < worldTriangles->size(); i++) { Triangle *tri = &worldTriangles->at(i); emit_normal(normals, tri->worldPosition, tri->normal, camera_position); } // ... create VAO for normals ... glDrawArrays(GL_TRIANGLES, 0, normals.size()); Note, however, that this would make the normal mesh camera-dependent -- which is desirable when rendering normals with triangles. Most CAD software draws normals with lines instead, which is much simpler and avoids many problems: void emit_normal(std::vector<vec3> &v, const vec3 &p, const vec3 &n) { static const float length = 0.25f; v.push_back(p); v.push_back(p + length*n); } // ... in your code, generate normals through: std::vector<vec3> normals; for(unsigned int i = 0; i < worldTriangles->size(); i++) { Triangle *tri = &worldTriangles->at(i); emit_normal(normals, tri->worldPosition, tri->normal); } // ... create VAO for normals ... glDrawArrays(GL_LINES, 0, normals.size());
70,059,428
70,059,601
Convert uint64_t to int64_t generically for all data widths
How does one generically convert signed and unsigned integers into each other without having to specify the specific width? For example: uint8_t <-> int8_t uint16_t <-> int16_t uint32_t <-> int32_t uint64_t <-> int64_t It would be nice to write: uint32_t x; int32_t y; static_cast<signed>(x) static_cast<unsigned>(y) However, I suspect that doesn't do what I want. I think I can achieve a similar effect using this method but I would think doing it for the same data width might have some syntactic sugar. Conditional template type math
However, I suspect that doesn't do what I want. Indeed, your suspicion is valid: the expression, static_cast<signed>(x), is exactly equivalent to static_cast<signed int>(x), so the cast will always be to an object of the 'default' size of an int on the given platform (and, similarly, unsigned is equivalent to unsigned int). However, with a little bit of work, you can create 'generic' cast template functions that use the std::make_signed and std::make_unsigned type-trait structures. Here's a possible implementation of such functions, with a brief test program that shows some deduced result types for different input type widths: #include <type_traits> // For make_signed and make_unsigned template<typename T> static inline auto unsigned_cast(T s) { return static_cast<std::make_unsigned<T>::type>(s); } template<typename T> static inline auto signed_cast(T s) { return static_cast<std::make_signed<T>::type>(s); } #include <typeinfo> // For "typeid" #include <iostream> int main() { int16_t s16 = 42; auto u16 = unsigned_cast(s16); std::cout << "Type of unsigned cast is: " << typeid(u16).name() << "\n"; uint64_t u64 = 39uLL; auto s64 = signed_cast(u64); std::cout << "Type of signed cast is: " << typeid(s64).name() << "\n"; return 0; }
70,059,527
70,059,863
Reorder simple 2D matrix in-place
I have a simple 2D (row, column) matrix which I currently reorder according to the algorithm below, using another array as final container to swap items. The problem is that I need to save memory (the code is running on a very low end device), and thus I need to figure a way to reorder the array in-place. The algorithm is as follows: for (int iRHS = 0; iRHS < NUM_VARS; iRHS++) for (int iRow = 0; iRow < _numEquations; iRow++) { coef[iRHS][iRow] = _matrixCoef(iRow, iRHS); } Note: coef is a pointer to double accessed via subscript, _matrixCoef is a matrix helper class and uses a vector of double accessed by operator(row,col). Here I want to eliminate coef, so that all values are reordered in _matrixCoef in-place instead. Edit: NUM_VARS is a define set to 2. Is this possible in-place after all? Edit 2: Here is the matrix class which is accessed above via operator overload (row, col): struct Matrix { /// Creates a matrix with zero rows and columns. Matrix() = default; /// Creates a matrix with \a rows rows and \a col columns /// Its elements are initialized to 0. Matrix(int rows, int cols) : n_rows(rows), n_cols(cols), v(rows * cols, 0.) {} /// Returns the number or rows of the matrix inline int getNumRows() const { return n_rows; } /// Returns the number or columns of the matrix. inline int getNumCols() const { return n_cols; } /// Returns the reference to the element at the position \a row, \a col. inline double & operator()(int row, int col) { return v[row + col * n_rows]; } /// Returns the element at the position \a row, \a col by value. inline double operator()(int row, int col) const { return v[row + col * n_rows]; } /// Returns the values of the matrix in column major order. double const * data() const { return v.data(); } /// Returns the values of the matrix in column major order. double * data() { return v.data(); } /// Initialize the matrix with given size. All values are set to zero. void initialize(int iRows, int iCols) { n_rows = iRows; n_cols = iCols; v.clear(); v.resize(iRows * iCols); } void resize(int iRows, int iCols) { n_rows = iRows; n_cols = iCols; v.resize(iRows * iCols); } private: int n_rows = 0; int n_cols = 0; std::vector<double> v; };
After you posted code, I will suggest another solution, that's rather simple and quick to implement. In your current Matrix class: struct Matrix { // ... // add this: void transpose() { is_transposed = !is_transposed; } // ... // modify these: /// Returns the number or rows of the matrix inline int getNumRows() const { return (is_transposed) ? n_cols : n_rows; } /// Returns the number or columns of the matrix. inline int getNumCols() const { return (is_transposed) ? n_rows : n_cols; } /// Returns the reference to the element at the position \a row, \a col. inline double & operator()(int row, int col) { if (is_transposed) return v[col + row * n_rows]; return v[row + col * n_rows]; } /// Returns the element at the position \a row, \a col by value. inline double operator()(int row, int col) const { if (is_transposed) return v[col + row * n_rows]; return v[row + col * n_rows]; } private: // ... // add this: bool is_transposed = false; }; You may want to modify other member functions, depending on your application.
70,059,528
70,072,382
How can I convert a std::string to UTF-8?
I need to put a stringstream as a value of a JSON (using rapidjson library), but std::stringstream::str is not working because it is not returning UTF-8 characters. How can I do that? Example: d["key"].SetString(tmp_stream.str());
rapidjson::Value::SetString accepts a pointer and a length. So you have to call it this way: std::string stream_data = tmp_stream.str(); d["key"].SetString(tmp_stream.data(), tmp_string.size()); As others have mentioned in the comments, std::string is a container of char values with no encoding specified. It can contain UTF-8 encoded bytes or any other encoding. I tested putting invalid UTF-8 data in an std::string and calling SetString. RapidJSON accepted the data and simply replaced the invalid characters with "?". If that's what you're seeing, then you need to: Determine what encoding your string has Re-encode the string as UTF-8 If your string is ASCII, then SetString will work fine as ASCII and UTF-8 are compatible. If your string is UTF-16 or UTF-32 encoded, there are several lightweight portable libraries to do this like utfcpp. C++11 had an API for this, but it was poorly supported and now deprecated as of C++17. If your string encoded with a more archaic encoding like Windows-1252, then you might need to use either an OS API like MultiByteToWideChar on Windows, or use a heavyweight Unicode library like LibICU to convert the data to a more standard encoding.
70,059,598
70,059,653
Assigning value to integer literal
Whenever a prvalue appears as an operand of an operator that expects a glvalue for that operand, the temporary materialization conversion is applied to convert the expression to an xvalue. Source: https://eel.is/c++draft/basic.lval#7 Why is 5 = 6 ill-formed? Should it not perform a temporary materialization conversion, and create an assignable temporary?
5 = 6 is illegal by fiat. That is, it's illegal because [expr.ass]/1 explicitly says so: All [assignment operators] require a modifiable lvalue as their left operand 5 is not a modifiable lvalue. Therefore, this rule is violated and the code is il-formed. Note that it doesn't expect a "glvalue" generally; it requires a "modifiable lvalue" specifically.
70,060,476
70,063,066
How do I get an int with a maximum/minimum width?
I'd like to get an int with a certain width for vectorization purposes. Something like int_atleast< 3 /*bytes*/ > should give int32_t, and int_atmost< 5 > should give the same int32_t. I tried to implement this with template specialization, but hit a wall because I'd need to specialize every possible argument. I thought of recursion but it seems like an overcomplicated solution to something probably already in the standard. What should I do?
A C++17 solution is surprisingly simple. if constexpr allows us to alter the return type of a function based on a constant expression. This allows one to write the algorithm rather succinctly namespace detail { template<unsigned W> auto compute_atleast_integer() { if constexpr (W <= 1) return uint8_t{}; else if constexpr (W <= 2) return uint16_t{}; else if constexpr (W <= 4) return uint32_t{}; else if constexpr (W <= 8) return uint64_t{}; } } template<unsigned W> using int_atleast = decltype(detail::compute_atleast_integer<W>()); This also has the emerging property of giving void when no such integer is available. This is a softer error that may be used in a SFINAE context to do something intelligent.
70,060,501
70,063,886
The last node in linked list not working in Bubble sort
i try to sort a linked list using bubble sort algorithm, but the last node seems to not sorted in the list. Every element in the list can be sorted but except the last one. Can anyone suggest me where i'm doing wrong and how to fix it? Thanks a lot! ( Sorry for bad English ), Here is my code: struct Node{ int data; Node *next; }; bool isEmpty(Node *head){ if (head == NULL){ return true; } else{ return false; } } void insertAsFirstElement(Node *&head, Node *&last, int number){ Node *temp = new Node; temp -> data = number; temp -> next = NULL; head = temp; last = temp; } void insert(Node *&head, Node *&last, int number){ if (isEmpty(head)){ insertAsFirstElement(head , last , number); } else{ Node *temp = new Node; temp->data = number; temp->next = NULL; last->next = temp; last = temp; } } void BubleSort(Node *&head){ struct Node *i ,*j; int num; for (i = head; i-> next != NULL;i=i->next){ for (j = i->next; j->next != NULL; j = j->next){ if (i->data > j-> data){ num = j->data; j->data = i->data; i->data = num; } } } } void display(Node *current){ if (current == NULL){ cout<<"Nothing to display "; } while(current!= NULL){ cout<<current -> data<<"-> "; current = current -> next; } } int main(){ Node *head = NULL; Node *last = NULL; int T;cin>>T; for (int i=0 ;i<T;i++){ int number;cin>>number; insert(head,last,number); } BubleSort(head); display(head); } Input: 6 1 7 4 6 9 3 Output: 1-> 4-> 6-> 7-> 9-> 3->
first of all, j->next will be 0 if j is the last element in the list. so j will skip the last element. second of all, if you let j iterate from i to the end of the list and increase i every time, you'll skip elements. you need to move the end point to the left (aka decrease the end index) instead of moving the start to the right (aka increasing the start index). edit: to get what i mean you might wanna check this out this is hard to do, because your list is built up with pointers pointing to the next element, not reverse. but is definitely managable by stopping j before reaching the end (unfixing the 1st point) and replacing i with j. void BubleSort(Node*& head) { struct Node* i, * j; //move i to the end for (i = head; i->next != NULL; i = i->next) { } do { //loop from the start to i for (j = head; ; j = j->next) { //compare the element 'at index' j with the next element ('j + 1') if (j->data > j->next->data) { //nice simple function to do swapping, provided by the std library. std::swap(j->data, j->next->data); } if (j->next == i) { //move i one to the 'left' aka decrease by it by one aka move it up one step in the recursion i = j; break; } } } while (i != head); }
70,060,573
70,061,944
Loading Qt Versions property page error in Qt Vs Tools
I meet the same problem as "Qt VS Tool is not loading properly the Qt Versions in VS 2019". sceenshot is here. what I tried: Reinstall Visual Studio 2019. Reinstall Qt and Qt Vs Tools several times. Set QTDIR in my pc environment. The problem is still present. Could you give me some suggestions?
I fix it now. The cause of the problem is that the previous Qt version information remains in registry. The solution steps are following: Open regsitry editor. you can pressed keys win+r, then input regedit. Find 计算机\HKEY_USERS\S-1-5-21-1609438195-1965026858-116498148-500\Software\Digia\Versions. Delete the contents of Versions folder. Reference screenshot ps: The key S-1-5-21-1609438195-1965026858-116498148-500 may be different in your pc.
70,060,699
70,060,878
Why is my code expecting a primary expression in a switch case before curly brackets?
I am trying to use a switch case as a sort of menu selection for the user in my code. I have this enum list: enum menuChoice {ADD = 1, REMOVE = 2, DISPLAY = 3, SEARCH = 4, RESULTS = 5, QUIT = 6}; Then I have this code: menuChoice switchChoice; Student student; cout << "1. Add\n" << "2. Remove\n" << "3. Display\n" << "4. Search\n"; cout << "5. Results\n" << "6. Quit" << endl; for (int i = 0; i < 999; ++i) { cout << "Please enter choice:"; cin >> userChoice; if (userChoice > 6 || userChoice < 1) { cout << "Incorrect choice. Please enter again" << endl; } else { break; } } switchChoice = static_cast<menuChoice>(userChoice); switch(switchChoice){ case 1: add_Student(student); break; case 2: break; case 3: break; case 4: break; case 5: break; case 6: break; default: } Which is kicking back this error: error: expected primary-expression before ‘}’ token I am really scratching my head over this. What is the mistake here? How am I not implementing a primary expression? I know that you aren't supposed to pass types to switch parameters but this is an enum variable I'm passing. Some help on this would be greatly appreciated.
default: } is a syntax error. The default label must be followed by a statement or a block. (This applies to any othe sort of label too). For example it could be default: break; or default: ; or default: {} .
70,060,871
70,060,879
Does the synthesized destructor destroy the memory allocated on the heap?
I have a class without a destructor and a constructor like this: class Foo { public: Foo(int a) : p(new int(a)) {} private: int *p; }; { Foo a(4); } After this block of code will the memory allocated on the heap be released ? Or do i have to explicitly provide a destructor like this: class Foo { public: Foo(int a) : p(new int(a)) {} ~Foo(); private: int *p; }; Foo::~Foo() { delete p; }
Any memory we allocate on the heap using new must always be freed by using the keyword delete. So,you have to explicitly free the memory allocated by new on the heap using the keyword delete as you did in the destructor. The synthesized destructor will not do it for you. Note if you don't want to deal with memory management by yourself then you can use smart pointers. That way you will not have to use delete explicitly by yourself because the destructor corresponding to the smart pointer will take care of freeing up the memory. This essentially means if the data member named p was a smart pointer instead of a normal(built in) pointer, then you don't have to write delete p in the destructor of your class Foo.
70,060,959
70,062,171
understanding c++ move_constructible concept implementation
I've got the following implementation of the c++ concept move_constructible from cppreference template<typename _Tp> concept move_constructible = constructible_from<_Tp, _Tp> && convertible_to<_Tp, _Tp>; I don't get why this works. I presume any type can be converted to itself, so the second requirement is pointless (God, I must be very wrong about something). Also, for the first requirement I would have expected something like constructible_from<_Tp, _Tp&&> to check if the type can be constructed from rvalue-ref (thus, moved). Please explain how this implementation works.
Most traits/concepts automatically add && to the types of "source" arguments (things that are passed to functions, as in std::is_invocable, or constructed from, as in std::is_constructible). I.e. constructible_from<A, B> is equivalent to constructible_from<A, B &&> (&& is automatically added to the second argument, but not to the first), and convertible_to<A, B> is equivalent to convertible_to<A &&, B>. Note that if a type already includes &, adding && to it has no effect. So, while T and T && are equivalent here, T & is not. This can be inferred from those traits/concepts being defined in terms of std::declval<T>(), which returns T &&. For the reason why std::declval<T &>() returns T &, see reference collapsing.
70,061,769
70,062,378
How to declare a template function with a std::ratio template parameter
I'm trying to define three functions with C++14 as below: template <typename D = std::chrono::seconds> typename D::rep test() { // somethinig } template <std::intmax_t N, std::intmax_t D = 1, typename V = uint64_t> V test() { // something } The two functions work as expected. I can call them like test<std::chrono::minutes>() and test<60>. Now, I want to define the third function, which accepts a std::ratio as a template parameter. template <template<std::intmax_t, std::intmax_t> class R, std::intmax_t N, std::intmax_t D, typename V = uint64_t> V test() { // R<N, D> should be std::ratio<N, D> // something } But in this case I would get a compile-time error while calling test<std::milli>(). I think it's because the compiler mixed up the first function and the third function. How could I define the third one?
Define some traits to detect whether the type T is a specialization of duration or ratio: #include <chrono> #include <ratio> template<class> struct is_duration : std::false_type { }; template<class Rep, class Period> struct is_duration<std::chrono::duration<Rep, Period>> : std::true_type { }; template<class> struct is_ratio : std::false_type { }; template<std::intmax_t Num, std::intmax_t Denom> struct is_ratio<std::ratio<Num, Denom>> : std::true_type { }; Then use enable_if to enable the corresponding function according to the type of T: template<typename D = std::chrono::seconds, std::enable_if_t<is_duration<D>::value>* = nullptr> typename D::rep test() { // somethinig } template<typename R, typename V = uint64_t, std::enable_if_t<is_ratio<R>::value>* = nullptr> V test() { // R<N, D> should be std::ratio<N, D> // something } Demo.
70,061,779
70,061,854
Weird behaviour when using the modulo operator between a negative int and std::size_t
This code snippet: #include <iostream> #include <cstddef> int main() { int a{-4}; std::size_t b{3}; std::cout << a % b; return 0; } prints 0 while this code snippet: #include <iostream> int main() { int a{-4}; int b{3}; std::cout << a % b; return 0; } prints -1 So, why does the first code snippet returns 0? Why does changing b from std::size_t to int print the right result?
Oh, it's because a implicitly converted into std::size_t becuase b is std::size_t, which is 4294967292(on my machine), and 4294967292 % 3 == 0
70,062,212
70,062,576
Creating a pointer to a class in a function belonging to a different class
I'm trying to populate a vector of type pointer to class B, which I'll be using later. When I try to read the vector's element, the value I'm getting is different from what I've given. Can someone please help me here, what mistake I'm making and how to correct it? Thanks #include <iostream> #include <vector> class B { public: int b; B (int n) { b = n; } }; std::vector<B*> v; class A { public: int a; void func(int n); }; void A::func(int n) { B obj_b(n); B* ptr = &obj_b; v.push_back(ptr); } int main() { A obj_a; obj_a.a = 5; obj_a.func(4); std::cout<<obj_a.a<<std::endl; for (auto it:v) { std::cout<<it->b<<std::endl; } } The output I'm getting is: 5, 32765 Whereas the expected output is: 5, 4
Using value instead of pointer, as per the comments above: #include <iostream> #include <vector> class B { public: int b; B (int n) { b = n; } }; std::vector<B> v; class A { public: int a; void func(int n); }; void A::func(int n) { v.emplace_back(n); } int main() { A obj_a; obj_a.a = 5; obj_a.func(4); std::cout<<obj_a.a<<std::endl; for (auto& e:v) { std::cout<<e.b<<std::endl; } }
70,062,653
70,062,831
SUMMARY: UndefinedBehaviorSanitizer
Trying to solve Odd Even Linked List question. Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. My try: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; int n = 1; ListNode* l = nullptr; ListNode *u = l; ListNode* r = r; ListNode* ru = nullptr; while(head){ ListNode* c = new ListNode(head->val); if(n%2){ if(r == nullptr){ r = c; } else{ r->next = c; r = r->next; } } else{ if(l == nullptr){ l = c; } else{ l->next = c; l = l->next; } } n++; head=head->next; } l->next = ru; return u; } }; But getting the below error: Line 27: Char 24: runtime error: member access within misaligned address 0x9ddfea08eb382d69 for type 'ListNode', which requires 8 byte alignment (solution.cpp) 0x9ddfea08eb382d69: note: pointer points here SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:36:24 What does the error mean and to solve it. Link: https://leetcode.com/problems/odd-even-linked-list/
The problem is (once we fix the typo): ListNode *l = nullptr; ListNode *u = l; ... return u; u is always nullptr. One quick hack would be: ListNode *l = nullptr; ListNode **u = &l; ListNode *r = nullptr; ListNode **ru = &r; ... l->next = *ru; return *u; Or you could try: if(r == nullptr){ r = c; ru = r; // Add this } ... if(l == nullptr){ l = c; u = l; // Add this }
70,062,766
70,128,634
Set XMM register via address location for X86-64
I have a float value at some address in memory, and I want to set an XMM register to that value by using the address. I'm using asmjit. This code works for a 32 bit build and sets the XMM register v to the correct value *f: using namespace asmjit; using namespace x86; void setXmmVarViaAddressLocation(X86Compiler& cc, X86Xmm& v, const float* f) { cc.movq(v, X86Mem(reinterpret_cast<std::uintptr_t>(f))); } When I compile in 64 bits, though, I get a segfault when trying to use the register. Why is that? (And yes, I am not very strong in assembly... Be kind... I've been on this for a day now...)
The simplest solution is to avoid the absolute address in ptr(). The reason is that x86/x86_64 requires a 32-bit displacement, which is not always possible for arbitrary user addresses - the displacement is calculated by using the current instruction pointer and the target address - if the difference is outside a signed 32-bit integer the instruction is not encodable (this is an architecture constraint). Example code: using namespace asmjit; void setXmmVarViaAddressLocation(x86::Compiler& cc, x86::Xmm& v, const float* f) { x86::Gp tmpPtr = cc.newIntPtr("tmpPtr"); cc.mov(tmpPtr, reinterpret_cast<std::uintptr_t>(f); cc.movq(v, x86::ptr(tmpPtr)); } If you want to optimize this code for 32-bit mode, which doesn't have the problem, you would have to check the target architecture first, something like: using namespace asmjit; void setXmmVarViaAddressLocation(x86::Compiler& cc, x86::Xmm& v, const float* f) { // Ideally, abstract this out so the code doesn't repeat. x86::Mem m; if (cc.is32Bit() || reinterpret_cast<std::uintptr_t>(f) <= 0xFFFFFFFFu) { m = x86::ptr(reinterpret_cast<std::uintptr_t>(f)); } else { x86::Gp tmpPtr = cc.newIntPtr("tmpPtr"); cc.mov(tmpPtr, reinterpret_cast<std::uintptr_t>(f); m = x86::ptr(tmpPtr); } // Do the move, now the content of `m` depends on target arch. cc.movq(v, x86::ptr(tmpPtr)); } This way you would save one register in 32-bit mode, which is always precious.
70,063,812
70,063,933
Why shared_ptr object works well without lock in such case?
One reader thread & multi writer threads concurrently access shared_ptr object and it works well, code as below (BUT, if i modify the write line code from "=" to "reset", it will coredump while reading) : shared_ptr.reset means coredump and "operator =" means works well ? ( I tried more than 100 times) bool start = false; std::mutex mtx; std::condition_variable cond; std::shared_ptr<std::string> string_ptr(new std::string("hello")); int main() { auto read = []() { { std::cout << "readddd" << std::endl; std::unique_lock<std::mutex> lck(mtx); while (!start) { cond.wait(lck); } } for (int i = 0; i < 100000; ++i) { std::cout << *string_ptr.get() << std::endl; } }; auto write = []() { { std::unique_lock<std::mutex> lck(mtx); while (!start) { cond.wait(lck); } } for (int i = 0; i < 100000; ++i) { string_ptr = std::make_shared<std::string>(std::to_string(i)); // string_ptr.reset(new std::string(std::to_string(i))); // will coredump } }; std::thread w(write); std::thread rthreads[20]; for (int i = 0; i < 20; ++i) { rthreads[i] = std::thread(read); } { std::unique_lock<std::mutex> lck(mtx); start = true; cond.notify_all(); } w.join(); for (auto& t : rthreads) { t.join(); } return 0; } coredumpe stack will be : #0 0x00007fee5fca3113 in std::basic_ostream<char, std::char_traits >& std::operator<< <char, std::char_traits, std::allocator >(std::basic_ostream<char, std::char_traits >&, std::basic_string<char, std::char_traits, std::allocator > const&) () from /lib64/libstdc++.so.6 #1 0x00000000004039f0 in <lambda()>::operator()(void) const (__closure=0xa54f98) at test_cast.cpp:395 line "std::cout << *string_ptr.get() << std::endl;"
Both versions suffer from a race condition. std::shared_ptr is not magically thread-safe. If you want to share it between threads, you have to protect it with a mutex. Just that you tried it a few times is no proof: It could be that it's just very unlikely to cause errors or even that the error is impossible on your compiler/OS/CPU combination, but that is not a guarantee. If you want to see it break more often, insert switches to the thread context into the code. The simplest way is to sleep for some time, at which point the OS schedules a different thread: for (int i = 0; i < 100000; ++i) { std::string* tmp = string_ptr.get(); std::this_thread::yield(); std::cout << *tmp << std::endl; } Note that this code enforces the context switch, but the same switch could happen at the same point spontaneously when the thread's timeslice is exceeded. As for the why one is more likely to fail than the other, step through the instructions executed by shared_ptr's assignment operator and reset() memberfunction. Their implementation may have larger or smaller critical section, which controls how often the error shows itself.
70,063,981
70,064,357
How to do press any key to continue prompt?
I am writing a program where the code reads off the text from a .txt file in where anything more than 24 lines must be continued with the enter key, but unsure how to put in the prompt asking for the enter key that doesn't mess up the formatting as it must show the first 24 lines instantly. #include <iostream> #include <fstream> #include <string> using namespace std; .... { cout << "Please enter the name of the file: "; string fileName; getline(cin, fileName); ifstream file(fileName.c_str(), ios::in); string input; ifstream fin(fileName); int count = 0; while (getline(fin, input)) { cout << count << ". " << input << '\n' ; count++; if (count % 25 == 0) cin.get(); } cin.get(); system("read"); return 0; } The part of the code that does the function and if I insert the prompt into here if (count % 25 == 0) cout << "Press ENTER to continue..."; cin.get(); it just has it where you must press enter for each line. Putting the prompt anywhere just messes it up in other ways.
Just place braces {} for the appropriate if (as pointed out in the comments) and your program will work. Note also that there is no need to use ifstream twice as you did in your program. #include <fstream> #include <string> #include <iostream> int main() { std::string fileName; std::cout<<"Enter filename"<<std::endl; std::getline(std::cin, fileName); std::ifstream file(fileName); std::string line; int count = 1; if(file) { while (std::getline(file, line)) { std::cout << count << ". " << line << '\n' ; if (count % 25 == 0) { std::cout<<"Press enter to continue"<<std::endl; std::cin.get(); } count++; } } else { std::cout<<"file cannot be opened"<<std::endl; } return 0; }
70,064,017
70,064,857
crypto++ Sending IV to another Function but i get an error: StreamTransformationFilter: invalid PKCS #7 block padding found
Test Program to Encrypt using crypto++, then it sends the iv and message as IV::EncryptedMessage. I am able to encrypt but get a padding error #7 when decrypting, I've searched for hours but can't find anyway to pass a std::string IV to crypto++. I believe my error is in the decc function, where I use hexdecode? string encc(string plain) { using namespace CryptoPP; AutoSeededRandomPool prng; SecByteBlock iv(AES::BLOCKSIZE); std::string sKey = "UltraSecretKeyPhrase"; SecByteBlock key((const unsigned char*)(sKey.data()), sKey.size()); prng.GenerateBlock(iv, iv.size()); std::string cipher, recovered; try { CBC_Mode< AES >::Encryption e; e.SetKeyWithIV(key, key.size(), iv); StringSource s(plain, true, new StreamTransformationFilter(e, new StringSink(cipher) ) ); } catch (const Exception& e) { exit(1); } string ciphertxt, ivString; HexEncoder encoder(new FileSink(std::cout)); encoder.Detach(new StringSink(ivString)); encoder.Put(iv, iv.size()); encoder.MessageEnd(); encoder.Detach(new StringSink(ciphertxt)); encoder.Put((const byte*)&cipher[0], cipher.size()); encoder.MessageEnd(); string toSend = ivString + "::" + ciphertxt; return toSend; } string decc(string toDec) { using namespace CryptoPP; std::string sKey = "UltraSecretKeyPhrase"; SecByteBlock key((const unsigned char*)(sKey.data()), sKey.size()); std::string recovered; string str1 = "::"; size_t found = toDec.find(str1); if (found != string::npos) { std::string sIv = toDec.substr(0, found); std::string encMessage = toDec.substr(found + 2, toDec.length()); cout << endl << "IV: " << sIv << endl << "Encoded Msg: " << encMessage << endl; string iv; HexDecoder decoder; decoder.Attach(new StringSink(iv)); decoder.Put((byte*)sIv.data(), sIv.size()); decoder.MessageEnd(); try { CBC_Mode< AES >::Decryption d; d.SetKeyWithIV(key.data(), key.size(), (byte *)iv.data(), AES::BLOCKSIZE); StringSource s(encMessage, true, new StreamTransformationFilter(d, new StringSink(recovered) ) ); return recovered; } catch (const Exception& e) { std::cerr << e.what() << std::endl; exit(1); } } else return NULL; } int main(){ string hh = encc("this is encoded"); cout << hh << endl; string gg = decc(hh); cout << gg << endl; return 0; } Just can't seem to use the right words for google :)
I Decoded the hex of the IV but never the actual encrypted message. Of course I seen it after I posted smh... This is a functional example of crypto++ encode and decode functions for anyone looking for it. string encc(string plain) { using namespace CryptoPP; AutoSeededRandomPool prng; SecByteBlock iv(AES::BLOCKSIZE); std::string sKey = "UltraSecretKeyPhrase"; SecByteBlock key((const unsigned char*)(sKey.data()), sKey.size()); prng.GenerateBlock(iv, iv.size()); std::string cipher, recovered; try { CBC_Mode< AES >::Encryption e; e.SetKeyWithIV(key, key.size(), iv); StringSource s(plain, true, new StreamTransformationFilter(e, new StringSink(cipher) ) ); } catch (const Exception& e) { exit(1); } string ciphertxt, ivString; HexEncoder encoder(new FileSink(std::cout)); encoder.Detach(new StringSink(ivString)); encoder.Put(iv, iv.size()); encoder.MessageEnd(); encoder.Detach(new StringSink(ciphertxt)); encoder.Put((const byte*)&cipher[0], cipher.size()); encoder.MessageEnd(); string toSend = ivString + "::" + ciphertxt; return toSend; } string decc(string toDec) { using namespace CryptoPP; std::string sKey = "UltraSecretKeyPhrase"; SecByteBlock key((const unsigned char*)(sKey.data()), sKey.size()); std::string recovered; string str1 = "::"; size_t found = toDec.find(str1); if (found != string::npos) { std::string sIv = toDec.substr(0, found); std::string encMessageHex = toDec.substr(found + 2); cout << endl << "IV: " << sIv << endl << "Encoded Msg: " << encMessageHex << endl; string iv, encMessage; HexDecoder decoder, msgDecoder; decoder.Attach(new StringSink(iv)); decoder.Put((byte*)sIv.data(), sIv.size()); decoder.MessageEnd(); // Forgot to decode encrypted message hex. added here decoder.Attach(new StringSink(encMessage)); decoder.Put((byte*)encMessageHex.data(), encMessageHex.size()); decoder.MessageEnd(); try { CBC_Mode< AES >::Decryption d; d.SetKeyWithIV(key.data(), key.size(), (byte *)iv.data(), AES::BLOCKSIZE); StringSource s(encMessage, true, new StreamTransformationFilter(d, new StringSink(recovered) ) ); return recovered; } catch (const Exception& e) { std::cerr << e.what() << std::endl; exit(1); } } else return NULL; } int main(){ string hh = encc("this is encoded"); cout << hh << endl; string gg = decc(hh); cout << gg << endl; return 0; }
70,064,144
70,064,339
Find if allocation is trivially resizable?
realloc may simply update bookkeeping info here and there to increase your allocation size, or it may actually malloc a new one and memcpy the previous allocation (or may fail). I want to be able to query the memory manager if an allocation is trivially resizable (either because it reserved more than I mallocd or because it was able coalesce adjacent blocks , etc...) and if yes, then I'll ask it to go ahead and do so, else I'd want to malloc and memcpy an arbitrary subset of the original allocation in an arbitrary order myself. Other StackOverflow answers seem to do one of these four : Suggest realloc anyways. This can be quite inefficient for large quantities of data, where the double-copy can have serious effect. Usually, it is the fastest portable route. Suggest manual malloc + memcpy + free. This is worse, because now instead of some double copying when allocation may not be resized, everything is double copied every time the allocation fills up. Performs terribly. Suggest a platform specific extension. This is not practical, as my code, like a lot of C code, requires portability. Suggest it's impossible. C already assumes the presence of a memory manager with ability to either resize allocations in place or create a new one. So, why can't I have one more level of control on it? We can have aligned malloc; why not this ? NOTE : This question is posted under both C and C++ tags because solutions from either language are acceptable and relevant. EDIT 1: In the words of FB vector : But wait, there's more. Many memory allocators do not support in- place reallocation, although most of them could. This comes from the now notorious design of realloc() to opaquely perform either in-place reallocation or an allocate-memcpy-deallocate cycle. Such lack of control subsequently forced all clib-based allocator designs to avoid in-place reallocation, and that includes C++'s new and std::allocator. This is a major loss of efficiency because an in-place reallocation, being very cheap, may mean a much less aggressive growth strategy. In turn that means less slack memory and faster reallocations. See this.
Suggest realloc anyways. This can be quite inefficient for large quantities of data, where the double-copy can have serious effect. Due to reasons why realloc can sometimes avoid copying and allocation, this is an irrelevant point because in practical implementations, that condition doesn't exist with large quantities of data. If you know that the allocation is large, then it's fairly safe to assume that realloc will have to copy and allocate. Hence, you can make the choice without having to make the "impossible" check. If reallocation is optional and you cannot afford the copy, then unconditionally choose the option to not reallocate. If reallocation isn't optional, then whether realloc would copy and allocate or not doesn't have an effect on what you have to do. Suggest a platform specific extension. This is not practical, as my code, like a lot of C code, requires portability. This is the only way to achieve what you're asking for because there is no standard way to query whether realloc will copy and allocate. However, keep in mind that it is possible to port such code by conditionally disabling this feature using pre-defined macros. Suggest it's impossible. This is true if you choose to rely on standard C++. is there a way to do this that I have not come across in my search ? No, the list is exhaustive.
70,064,702
70,065,134
Display words that do not contain the specified letter
#include <string> #include <windows.h> #include <stdlib.h> #include <sstream> using namespace std; int main() { string s = "We study C++ programming language first semester.", word; cout << s << endl; s.pop_back(); stringstream in (s); while (in >> word) { if (word.find('e') == std::string::npos) cout << word << endl; } system("pause"); return 0; } Hello everyone! Given the line "We study C ++ programming language first semester." And it is necessary to deduce words from it that do not contain the letter 'e'. There is such a version of the program, but I need something simpler without stl. Using canned loops, etc and preferably using char I will be very grateful to everyone for their help!
If you really want to go with only std::string and loops, I guess maybe this? But it's a lot longer than just using stringstream and such, #include <iostream> #include <string> int main() { std::string s = "We study C++ programming language first semester."; s += ' '; //safeguard; std::string word = ""; for (char c : s) { if (c == ' ') //break of word { if (word != "") //word not empty { bool incE = false; for (char c2 : word) //check for e { if (c2 == 'e') {incE = true; break;} } if (!incE) { std::cout << word << " "; } word = ""; } } else {word = word + c;} } } Output: study C++ programming first
70,065,317
70,065,556
"const std::string &getStr" vs "std::string getStr"
Can someone explain in simple words why a developer did the following const std::string &getStr() const { return m_Str; } instead of std::string getStr() const { return m_Str; }
That's two separate things. The second example returns a copy of the member variable m_Str, the first one a constant reference to the same variable. The difference is quite noticeable, if you take a look at the caller of this method. Imagine another method setStr that changes the member variable. Now take a look at the following code: instance.setStr("Foo"); const std::string& str = instance.getStr(); instance.setStr("Bar"); std::cout << str << std::endl; // Prints "Bar". Whereas if you return a copy, the output will be different: instance.setStr("Foo"); std::string str = instance.getStr(); instance.setStr("Bar"); std::cout << str << std::endl; // Prints "Foo".
70,065,971
70,099,839
UDP livestream (GoPro Hero4) opens using OpenCV in python but not in C++
i want to do image processing on a GoPro Hero4 Black livestream using OpenCV in C++. The firmware version is 5.0. With python it successfully works. When i implement it the same (!) way in C++ status 31 and 32 switch to 1 when opening the VideoCapture, so the livestream is started and the client is connected. However, a following cap.isOpen() returns false. I need to add that the cap.open(...) command lets the program stop for some seconds which is unplausible. The code in python import cv2 import numpy as np from time import time import socket from goprocam import GoProCamera from goprocam import constants import requests sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) t=time() url = "http://10.5.5.9/gp/gpControl/execute?p1=gpStream&a1=proto_v2&c1=restart" payload = { } headers = {} res = requests.post(url, data=payload, headers=headers) cap = cv2.VideoCapture("udp://10.5.5.9:8554") while (cap.isOpened()): nmat, frame = cap.read() if nmat == True: cv2.imshow("GoPro OpenCV", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break if time() - t >= 2.5: sock.sendto("_GPHD_:0:0:2:0.000000\n".encode(), ("10.5.5.9", 8554)) t=time() # When everything is done, release the capture cap.release() cv2.destroyAllWindows() The code in C++ #define CURL_STATICLIB #include <curl\curl.h> #include <boost/exception/exception.hpp> #include <boost/thread.hpp> #include <boost/chrono.hpp> #include <boost/asio.hpp> #include <iostream> #include "opencv2/opencv.hpp" #include "opencv2/highgui.hpp" using namespace cv; int main() { CURL* curl; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://10.5.5.9/gp/gpControl/execute?p1=gpStream&c1=start"); curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_URL, "http://10.5.5.9/gp/gpControl/execute?p1=gpStream&c1=restart"); curl_easy_perform(curl); } boost::asio::io_service ioService; boost::asio::ip::udp::resolver resolver(ioService); boost::asio::ip::udp::endpoint dest(boost::asio::ip::address::from_string("10.5.5.9"), 8554); boost::asio::ip::udp::socket sock(ioService, boost::asio::ip::udp::v4()); boost::this_thread::sleep_for(boost::chrono::milliseconds(2000)); sock.send_to(boost::asio::buffer("_GPHD_:0:0:2:0.000000\n", 22), dest); VideoCapture cap; cap.open("udp://10.5.5.9:8554"); while (cap.isOpened() ) { std::cout << "is open" << std::endl; } return 0; } Does anyone have an idea how to solve the issue? I also tried different API references for VideoCapture cap.open("udp://10.5.5.9:8554", CAP_ANY); cap.open("udp://10.5.5.9:8554", CAP_FFMPEG); I also tried using the @ prefix cap.open("udp://@10.5.5.9:8554", CAP_ANY); UPDATE: I can't test the correct execution of the VideoCapture backend since it seems like the laptop webcam cant be opened with CAP_FFMPEG in python. However, when i let the laptop webcam run by declaring index 0 and using the CAP_FFMPEG backend i get the same behaviour as when i declare the gopro udp livestream. cap.open(0, CAP_FFMPEG);
The solution was to deactivate the windows firewall for private networks. Cant be more trivial but in case someone struggles at that point...here is the hint :)
70,066,137
70,066,267
nLohmann lib in C++ from raw http data
I have raw http data char text[] = R"({\"ID\": 123,\"Name\": \ "Afzaal Ahmad Zeeshan\",\"Gender\": true, \"DateOfBirth\": \"1995-08-29T00:00:00\"})"; I am using Json nlohmann lib , it gives me the parse error and if i tried the following then it parse R"({"happy": true, "pi": 3.141})" Is the nlohmann does not parse http raw data ?
You are using a raw string literal so drop the backslashes: char text[] = R"({ "ID": 123, "Name": "Afzaal Ahmad Zeeshan", "Gender": true, "DateOfBirth": "1995-08-29T00:00:00" })"; Full example: #include <nlohmann/json.hpp> #include <iomanip> #include <iostream> using json = nlohmann::json; int main() { char text[] = R"({ "ID": 123, "Name": "Afzaal Ahmad Zeeshan", "Gender": true, "DateOfBirth": "1995-08-29T00:00:00" })"; char text2[] = R"({"happy": true, "pi": 3.141})"; json obj1, obj2; try { obj1 = json::parse(text); obj2 = json::parse(text2); // print the json objects: std::cout << std::setw(2) << obj1 << '\n' << obj2 << '\n'; } catch(const json::parse_error& ex) { std::cerr << "parse error at byte " << ex.byte << std::endl; } } Possible output: { "DateOfBirth": "1995-08-29T00:00:00", "Gender": true, "ID": 123, "Name": "Afzaal Ahmad Zeeshan" } {"happy":true,"pi":3.141} Demo
70,066,434
70,066,528
Why is temporary object living after end of the expression
Why if string getString(){ return string("string"); } int main(){ const string& a = getString(); cout << a; } Will give an UB This: class vector{ void push_back(const T& value){ //... new(arr + sz) T (value); ++sz; } } main(){ vector v; v.push_back(string("abc")); } will be OK? I guess that in first case temporary object expires right after end of the expression const string& a = getString(); Whereas in second case temporary object's life will be prolonged until finish of the function. Is it the only one case of prolonging of temporary object's life behind of an expression.
Case I: I guess that in first case temporary object expires right after end of the expression const string& a = getString(); Note that, const references are allowed to bind to temporaries. Also, const references extend the lifetime of those temporaries. For example, const int &myRef = 5; Here the reference myRef extend the lifetime of the temporary int that was materialized using the prvalue expression 5 due to temporary materialization. Similarly in your first code snippet, the function getString() returns a std::string by value. The lifetime of the temporary that is materialised in this case will also be extended. So your first code snippet has no UB. You asked Is it the only one case of prolonging of temporary object's life behind of an expression. No there are other examples like the one i have given(const int &myRef = 5;).
70,066,544
70,066,646
Problem with structure and organization in big c++ project
I started my first big c++ project, in which I divided the functionality of the program into different files. I ran in a situation where library include each other and there was some declaration problem. sometingh like this: in apha.h #pagma once #include "betha.h" struct alpha { int data; betha bb; }; int fun1(apha a); in betha.h #pagma once #include "alpha.h" struct betha { double data; double moreData; }; int fun2(alpha a, betha b); I found a solution in transferring all the struct in a separate file struct.h and it works fine. but I was wondering if there was a way to have the struct in their respective libraries because it would make more sense and be easier to work with.
For starters it seems there are two typos in the header name apha.h that should be alpha.h and in this declaration int fun1(apha a); It seems you mean int fun1(alpha a); After including the header apha.h in a compilation unit you in fact have struct betha { double data; double moreData; }; int fun2(alpha a, betha b); struct alpha { int data; betha bb; }; int fun1(apha a); As you can see the function func2 refers to the name alpha int fun2(alpha a, betha b); that was not yet declared. You could use either the forward declaration struct betha { double data; double moreData; }; struct alpha; int fun2(alpha a, betha b); or the elaborated type specifier in the function declaration struct betha { double data; double moreData; }; int fun2( struct alpha a, betha b);
70,066,685
70,067,022
Unhandled exception when trying to retrieve the value from the JSON ptree using Boost C++
I am getting the below error when reading the value from the JSON ptree using Boost C++ Unhandled exception at 0x7682B502 in JSONSampleApp.exe: Microsoft C++ exception : boost::wrapexcept<boost::property_tree::ptree_bad_path> at memory location 0x00DFEB38. Below is the program, Could someone please help me what i am missing here. #include <string> #include <iostream> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/foreach.hpp> using namespace std; using boost::property_tree::ptree; int main() { const char* f_strSetting = "{\"Student\": {\"Name\":\"John\",\"Course\":\"C++\"}}"; boost::property_tree::ptree pt1; std::istringstream l_issJson(f_strSetting); boost::property_tree::read_json(l_issJson, pt1); BOOST_FOREACH(boost::property_tree::ptree::value_type & v, pt1.get_child("Student")) { std::string l_strColor; std::string l_strPattern; l_strColor = v.second.get <std::string>("Name"); l_strPattern = v.second.get <std::string>("Course"); } return 0; }
There is a shape mismatch between your code and your data: The data is a plain nested dictionary: Student.name is "John". The code expects to see an array under the Student key, so it tries to fetch Student.0.name, Student.1.name, ... for every subitem of Student. Either fix the code: // Drop the BOOST_FOREACH auto & l_Student = pt1.get_child("Student"); l_strColor = l_Student.get<std::string>("Name"); or fix the data: // Note the extra [] const char * f_strSetting = R"({"Student": [{"Name":"John","Course":"C++"}]})";
70,066,919
70,066,969
expected primary expression before } in C++
Why a label can not be placed immediately before }while(/*exp*/); in a do-while loop, instead of expecting a primary expression. int main() { int x = 5; do{ if(x==2) goto label; printf("%d", x); label: ; // if not error: expected primary-expression before ‘}’ token }while(--x); return 0; }
Labels may be placed before statements. The symbol '}' does not denote a statement. So you need to include a null statement after the label and before the closing brace. label: ; }while(--x); Pay attention to that it is better to rewrite the do while statement without the goto statement like do{ if ( x != 2 ) printf("%d", x); }while(--x); Also bear in mind that opposite to C in C++ declarations are also statements. So you may place a label before a declaration.
70,067,946
70,068,460
How can I get qjsonvalue to string?
What should i do to get output for example: Bid value is 2248.48? Here is code: QNetworkRequest request = QNetworkRequest(QUrl("https://api.30.bossa.pl/API/GPW/v2/Q/C/_cat_name/WIG20?_t=1637005413888")); QNetworkReply* reply = m_manager.get(request); QObject::connect(reply, &QNetworkReply::finished, [reply]() { QByteArray rawData = reply->readAll(); QString textData(rawData); // qDebug() << textData; QJsonDocument doc = QJsonDocument::fromJson(textData.toUtf8()); auto rootObj = doc.object(); auto _d = rootObj.value("_d").toArray(); auto _t = _d[0].toObject().value("_t").toArray(); auto _quote = _t[0].toObject().value(QString("_quote")); qDebug() << _quote; eply->deleteLater(); Now i get QJsonValue (string, "2248.48) when i tried this: QJsonObject root = _t[0].toObject().value(QString("_quote")); qDebug() << root; QJsonValue value = obj.value(QString("_quote")); qDebug() << "Bid value is" << value.toString();; https://api.30.bossa.pl/API/GPW/v2/Q/C/_cat_name/WIG20?_t=1637005413888 {"message":"OK","_quote_date":null,"_type":"C","_symbol":["WIG20"],"_d":[{"_h":"Własne - 22 listopada 2021 16:42","_hs":"Własne","_max_quote_dtm":"22 listopada 2021","_max_quote_dtm_lc":"22 listopada, 16:42","_ret_quote_dtm":"2021-11-22","_t":[{"_symbol":"WIG20","_symbol_short":"WIG20","_group":"X1","_isin":"PL9999999987","_quote_date":"2021.11.22","_quote_time":"16:42","_time":"16:42","_phase":"Sesja","_quote_max":"2262.74","_quote_min":"2237.64","_quote_open":"2251.08","_quote_ref":"2248.18","_quote_imp":"2254.37","_bid_size":null,"_bid_volume":null,"_bid_orders_nr":null,"_ask_size":null,"_ask_volume":null,"_ask_orders_nr":null,"_volume":null,"_open_positions":null,"_quote_volume":null,"_transactions_nr":null,"_turnover_value":841977698,"_quote":"2254.10","_step":"2","_type_of_instrument":"0","_settlement_price":null,"_change_proc":0.26,"_change_pnts":5.9200,"_30d_change_max":2449.6400,"_30d_change_min":2221.6800,"_change_type":"_change_proc","_quote_type":"_quote","_debut":"0","_live":"1","_sw_symbol_short":0,"_is_indice":"1","_change":"+0.26","_change_suffix":"%","_change_max_min":"+1.12","_change_close_open":"+0.13","_change_settl_ref":null}]}],"_i":[null],"_count":1,"_d_fx":{"_h":null,"_hs":null,"_max_quote_dtm":null,"_max_quote_dtm_lc":null,"_t":[]}} I got erros "QJsonValue to non-scalar type QJsonObject requested"
You either want _quote.toString() (first listing) or root.toString() (second listing)
70,068,085
70,068,463
Why can an object with deleted copy- and move-constructor still be passed to a function accepting an r-value reference?
I have the following code, which apparently compiles in MSVC and GCC: #include <iostream> class Test { public: Test() = default; Test(Test const& other) = delete; Test(Test&& other) noexcept = delete; Test& operator=(Test const& other) = delete; Test& operator=(Test&& other) = delete; auto getX() -> int { return x; }; auto setX(int xz) -> void { x = xz; }; private: int x = 42; }; void something(Test&& thing) { thing.setX(44); std::cout << thing.getX() << std::endl; } int main() { Test a; a.setX(3); std::cout << "Before call: " << a.getX() << std::endl; something(std::move(a)); std::cout << "After call: " << a.getX() << std::endl; } Now, I would have expected this to not compile. Both the move and the copy constructor of Test are deleted. The function something only accepts r-value references. However, it does compile, and this is the output of the program: Before call: 3 44 After call: 44 The only way that I could think of how it should be possible to pass an object of type Test to a function is by using an l-value reference or const ref. But the way something is defined, it should only accept rvalues, shouldn't it? Here is the code on compiler explorer: https://godbolt.org/z/rGKdGbsM5
rvalue references are just references just like lvalue references. The difference between them is the kind of expression that can be used to initialize them. std::move casts an lvalue reference to an rvalue reference. It doesn't require the type to be movable. If you try to actually move thing in something then you will get errors.
70,068,251
70,068,756
How to quickly search a large vector many times?
I have a std::vector<std::string> that has 43,000 dictionary words. I have about 315,000 maybe-words and for each one I need to determine if it's a valid word or not. This takes a few seconds and I need to complete the task as fast as possible. Any ideas on the best way to complete this? Currently I iterate through on each attempt: for (std::string word : words) { if (!(std::find(dictionary.begin(), dictionary.end(), word) != dictionary.end())) { // The word is not the dictionary return false; } } return true; Is there a better way to iterate multiple times? I have a few hypothesis, such as Create a cache of invalid words, since the 315,000 list probably has 25% duplicates Only compare with words of the same length Is there a better way to do this? I'm interested in an algorithm or idea.
Is there a better way to iterate multiple times? Yes. Convert the vector to another data structure that supports faster lookups. The standard library comes with std::set and std::unordered_set which are both likely to be faster than repeated linear search. Other data structures may be even more efficient. If your goal is to create a range of words or non-words in the maybe set, then another efficient approach would be to sort both vectors, and use std::(ranges::)set_intersection or std::(ranges::)set_difference.
70,068,327
70,068,422
Updating a variable in a struct
So I just created a struct that makes a rectangle. the struct itself look likes this struct _rect { //bottom left vertex int x = 0; int y = 0; // width and height int width = 0; int height = 0; //top right vertex int y2 = y + height; int x2 = x + width; }; //init rect _rect rect01; rect01.x = rect01.y = 50; rect01.width = rect01.height = 200; in the main cpp when I want to create an instance of it I just want to enter bottom left x and y, plus width and height and I want it to calculate top right vertex by itself, is there a way to assign x2 and y2 their values without manuly doing so ?
You should create a specific class: class Rect { public: Rect(int x, int y, unsigned int width, unsigned int height) : m_x(x), m_y(y), m_width(width), m_height(height) {} int x() { return m_x; } int y() { return m_y; } int top() { return m_y + m_height; } int right() { return m_x + m_width; } private: int m_x; int m_y; unsigned int m_width; unsigned int m_height; }; That give you the possibility to do the computation you need in the class methods. You can also create setters and more getters if you want.
70,068,998
70,070,145
Is the pointer from casting to base gurenteed to be a pointer into the memory region of the derived object
Given this code: #include <cassert> #include <cstring> struct base{ virtual ~base() = default; }; class derived: public base{ public: int x; }; using byte = unsigned char; int main() { byte data[sizeof(derived)]; derived d; memcpy(data, &d, sizeof(derived)); base* p = static_cast<base*>(reinterpret_cast<derived*>(data)); const auto offset = (long)data - (long)p; assert(offset < sizeof(derived)); // <-- Is this defined? } As my comment asks, is this defined behavior by the standard? i.e does casting to base guarantee a pointer to the region occupied by the derived being cast? From my testing it works on gcc and clang, but I am wondering if it works cross platform too (obviously this version assumes 64bit pointers)
potentially wrong alignment your data array is a char array, so its alignment will be 1 byte. your class however contains an int member, so its alignment will be at least 4 bytes. So you data array is not sufficiently aligned to even contain a derived object. You can easily fix this by providing an alignment of your data array that is at least that of derived or greater, e.g.: alignas(alignof(derived)) byte data[sizeof(derived)]; (godbolt demonstrating the problem) you can also use std::aligned_storage for this if you want. using memcpy on classes is not always safe Using memcpy on classes will only work if they're trivially copyable (so a byte-wise copy would be identical to calling the copy constructor). Your class isn't trivially copyable due to the virtual destructor, so memcpy isn't allowed to copy the class. You can easily check this with std::is_trivially_copyable_v: std::cout << std::is_trivially_copyable_v<derived> << std::endl; You can fix this easily by calling the copy-constructor instead of using memcpy: alignas(alignof(derived)) char data[sizeof(derived)]; derived d; derived* derivedInData = new (data) derived(d); virtual inheritance, multiple inheritance and other shenanigans How classes will be layed out in memory is implementation-defined, so you basically have no guarantees how the compiler will lay out your class hierarchy. However there are a few things you can count on: sizeof(cls) will always return the size cls needs, including all it's base classes, even when it uses virtual and / or multiple inheritance. (sizeof) When applied to a class type, the result is the number of bytes occupied by a complete object of that class, including any additional padding required to place such object in an array. placement new will construct an object and return a pointer to it that is within the given buffer. static_cast<> to baseclass is always defined the actual answer Yes, the base class pointer must always point to somewhere within your buffer, since it's a part of the derived class. However where exactly it'll be in the buffer is implementation-defined, so you should not rely on it. The same thing is true about the pointer returned from placement new - it might be to the beginning of the array or somewhere else (e.g. array allocation), but it'll always be within the data array. So as long as you stick to one of those patterns: struct base { int i; } struct derived : base { int j; }; alignas(alignof(derived)) char data[sizeof(derived)]; derived d; memcpy(data, &d, sizeof(derived)); // trivially copyable derived* ptrD = reinterpret_cast<derived*>(data); base* ptrB = static_cast<base*>(ptrD); / struct base { int i; virtual ~base() = default; } struct derived : base { int j; }; alignas(alignof(derived)) char data[sizeof(derived)]; derived d; derived* ptrD = new(data) derived(d); // not trivially copyable base* ptrB = static_cast<base*>(ptrD); ptrD->~derived(); // remember to call destructor your assertions should hold and the code should be portable.
70,069,151
70,070,935
Prevent fmt from printing function pointers
I have a following buggy program. Logic is nonsense, it is just a toy example. #include <ranges> #include <iostream> #include <fmt/format.h> #include <fmt/ranges.h> template<typename T> constexpr bool size_is_4(){ return sizeof(T)==4; } int main() { std::cout << fmt::format("float size is 4 bytes : {}\n", size_is_4<float>); std::cout << fmt::format("double size is 4 bytes : {}\n", size_is_4<double>); } output is float size is 4 bytes : true double size is 4 bytes : true The problem is that I pass a function pointer to fmt::format and it prints it out as a boolean. Fix is easy, just invoke the function, but I wonder if there is a way to catch bugs like this. Since function returns bool it actually looks reasonable as output.
This is a bug caused by function pointers not caught by the pointer detection logic. I opened a GitHub issue: https://github.com/fmtlib/fmt/issues/2609. Update: the issue has been fixed.
70,069,205
70,069,247
error: ‘leftHeight’ was not declared in this scope
I have the following function to computer height of a node in a binary tree (and its descendants): void computeHeight(Node *n) { // Implement computeHeight() here. if (n->left) { computeHeight(n->left); int leftHeight = n->left->height; } else { int leftHeight = -1; } if (n->right) { computeHeight(n->right); int rightHeight = n->right->height; } else { int rightHeight = -1; } n->height = std::max(leftHeight, rightHeight) + 1; } When I run the code I have error: ‘leftHeight’ was not declared in this scope, it happens at line n->height = std::max(leftHeight, rightHeight) + 1;. The error happens during compilation. I don't understand why it happens because I defined leftHeight above. Other code: In main.cpp: #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <queue> #include "main.h" void computeHeight(Node *n) {} int main() { Node *n = new Node(); n->left = new Node(); n->right = new Node(); n->right->left = new Node(); n->right->right = new Node(); n->right->right->right = new Node(); computeHeight(n); std::cout << std::endl << std::endl; delete n; n = nullptr; return 0; } In main.h: class Node { public: int height; // to be set by computeHeight() Node *left, *right; Node() { height = -1; left = right = nullptr; } ~Node() { delete left; left = nullptr; delete right; right = nullptr; } };
The problem is that you have defined leftHeight inside if else block and therefore they are not visible outside of those blocks. Similarly the variable rightHeight is also visible only inside the blocks in which it was defined. To solve this just define leftHeight outside(of those blocks) once and then just assign value to them inside if and else blocks which would look like: void computeHeight(Node *n) { int leftHeight = -1;//define and initialize leftHeight int rightHeight = -1;//define and initialize rightHeight // Implement computeHeight() here. if (n->left) { computeHeight(n->left); leftHeight = n->left->height;//note this is assignment } if (n->right) { computeHeight(n->right); rightHeight = n->right->height;//note this is assignment } n->height = std::max(leftHeight, rightHeight) + 1;//this works now }
70,069,540
70,069,596
C++ singleton class by making the constructor private
I tried to use the pattern to make a class practically a singleton by making the constructor non-public. However, when I tested it, the result is not what I expected. If only one instance is created, the value should be the same for the references, but apparently, they are different like below. What is wrong with the code? Code: class SortOfSingleton { public: static SortOfSingleton& getInstance(); int value = 0; private: SortOfSingleton(int value); }; SortOfSingleton::SortOfSingleton(int value) { std::cout << "Creating new instance."<< std::endl; this->value = value; } SortOfSingleton& SortOfSingleton::getInstance() { static SortOfSingleton instance(5); return instance; } void main() { auto instance1 = SortOfSingleton::getInstance(); instance1.value = 100; std::cout << instance1.value << std::endl; auto instance2 = SortOfSingleton::getInstance(); std::cout << instance2.value << std::endl; Real Output: Creating new instance. 100 5 Expected Output: Creating new instance. 100 100
auto type deduction does not include references. Instead each instance variable will be its own copy of the object. You must explicitly use & to define a reference: auto& instance1 = SortOfSingleton::getInstance(); ... auto& instance2 = SortOfSingleton::getInstance(); On that note you need to disallow copying as well, by deleting the copy-constructor and copy-assignment operator. You should also disallow moving the object with the rvalue overloads.
70,069,688
70,069,726
Want to compile only if statement in if-else
I am working on a project which should have to run on both ros melodic (ubuntu 18.04) and ros noetic(ubuntu 20.04). so while doing so I made an if-else statement in my code that, if(distro=="noetic"){ ...do this else ...do this The problem occurs basically, noetic and melodic support different versions of Point cloud Libraries(PCL) which also make them different in their way of initialization. So when I put PCL initialization (the way noetic support) in the if statement and in the else statement I put melodic way of initialization. I want the compiler( catkin_make command I use) to compile only the if statement but it also compiles else statement which gives an error because noetic did not support a melodic way of initialization. What should be the way?
Use preprocessor macros. This needs to be handled before compile time. The preprocessor macros #ifdef and #ifndef will check if a token is present in the symbol table (check the documentation for your OS to see if there is a defined token for it), and skip to the according if/else section. #ifdef NOETIC_DISTRO //Code for noetic distro #endif #ifdef OTHER_DISTRO //Code for other distro #endif
70,069,717
70,070,767
Queries for cyclic proportional assignment of work to hosts
Consider M pieces of work distributed over N hosts in a cyclic way where each host must get the amount of work proportional to its speed. Without proportions, this is implemented as: int64_t AssignWorkToHost(const int64_t i_work) { return i_work % N; } Proportions are weights p[i] that sum up to 1.0, so that i-th host must get more or less p[i]*M pieces of work. M is so large that storing M values doesn't fit in the memory of a single host (but a solution where it fits would be of interest too). N can be as large as 10 000. Ideally each host must store no more than O(M/N) values and the computational complexity of AssignWorkToHost() should be no more than O(N). Preprocessing is fine. The algorithm should be deterministic, meaning that each process within the distributed group must get the same assignment of work to hosts.
I would suggest using a priority queue storing pairs of (estimated processing time, worker) with a custom comparator that compares in that order. In pseudo-code, the body of assign to work looks like this: (estimated_time, i) = queue.pop() queue.push((estimated_time + worker_time[i], i)) return i This is deterministic, requires O(N) memory, and each assignment takes time O(log(N)). Of course you set worker_time[i] = 1.0/worker_speed[i] and now how much worker i gets assigned is proportional to its speed. For a query interface, we can avoid replaying all history by the simple trick of reconstructing a single point in history, then playing it forward. For that, at the time (i_work-1)/total_speed no more than i_work-1 can have been produced. Also, no less than i_work-N can have been produced. (Why? Each worker has failed to produce a fraction < 1 of the theoretical elapsed_time / worker_speed[i] limit. Therefore N workers have produced under N fewer than that theoretical limit. Since it has to be an integer, that puts it at most N-1 behind. And i_work-1 - (N-1) = i_work-N.) At that time, for each worker, we know how many that worker has produced, and we know when it next will produce another unit. This is sufficient to produce the priority queue as of that moment of time. Then we play it forward. In no more than N steps, the k'th will pop out, correctly assigned. Total running time for the query version is O(N log(N)). And as the saying goes, "For all intents and purposes, log(N) is a constant. For Google it is a somewhat larger constant." (At the expense of considerably more complexity, I think you can make the query interface truly O(N).) In pseudo-code that is almost valid Python: total_worker_speed = sum(1/t for t in worker_time) t = (i_work-1) / total_worker_speed total_done = 0 todo = [] for i in 0..count_workers: # At time t, this is how many are left. done = floor(t/worker_time[i]) # This is how long until this worker produces the next unit time_left = (done+1)*worker_time[i] - t todo.push([time_left, i]) total_done += done queue = heapify(todo) # turning array into priority queue is O(N) while total_done < iwork: # Get the next one. (estimated_time, i) = queue.pop() queue.push((estimated_time + worker_time[i], i)) total_done += 1 # i now has the job that produced the iwork job. return i
70,069,809
70,069,810
"Unrecognised emulation mode: ain" when compiling with gcc on Ubuntu
Consider the following code lying in main.cpp: #include <iostream> int main() { std::cout << "Hello World!\n"; } Compilation with g++ main.cpp -o -main fails: /usr/bin/ld: unrecognised emulation mode: ain Supported emulations: elf_x86_64 elf32_x86_64 elf_i386 elf_iamcu elf_l1om elf_k1om i386pep i386pe collect2: error: ld returned 1 exit status I'm on a 64-bit Ubuntu 20.04.3 LTS running in WSL2. GCC's version is g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 How do I make this Hello World compile?
You've accidentally typed a dash before specifying your output file: it should be -o main, not -o -main, so the full command line is g++ main.cpp -o main GCC has a -m key which allows specifying target machine architecture. For some reason, even when -main immediately follows -o, GCC still checks that the architecture (ain in case of -main) exists. For example, if I compile with g++ main.cpp -o -melf_x86_64, I get an executable named -melf_x86_64 (to remove it, use rm ./-melf_x86_64 instead of rm -melf_x86_64). However, if I try g++ main.cpp -o -mi386, I get some compilation errors because I don't have 32-bit C++ standard library installed. Looks like a bug to me: it simultaneously changes target architecture AND changes output file name. I've just opened GCC issue and LLVM issue (clang is affected as well). UPD: actually looks like a bug in LD.
70,069,882
70,069,909
Class constructor doesn't seem to be working?
Hi I'm new to c++ and I would like to know why the following code is not working as expected: #include <iostream> using namespace std; class Person { public: int age; Person(){ int age = 20; } }; int main() { Person p; cout << p.age << endl; } I'm expecting to cout 20, but the program returns 0. I thought that the constructor would change age to 20 after the object is created. I tried searching for answers but the search results don't seem to answer my question.
You are creating a local variable age with value 20 and doing nothing else with it. Your constructor needs to look like this: Person() : age{20} {} Then it will actually initialize the instance field as expected. (Otherwise age = 20; in the constructor body (without the int declaration that hides the field name) would have worked as well. But in general it is good practice to always initialize fields in an initializer list rather than in the constructor body. (The most obvious benefit being that the fields can be const, but there are also other benefits, such as a well-defined and enforced and easy-to-read order of initialization.)) (Also, using namespace std; is an antipattern; please don’t do that.)
70,070,178
70,070,233
Problem with dynamic arrays (I suppose) for numbers from 200
I am writing an algorithm which outputs all prime numbers in range [3; n]. Take a look at my code and I will explain the problem: #include <iostream> using namespace std; int main() { int n; cout << "Enter the value of n:" << endl; cin >> n; int k = (n - 2) / 2 + 1; bool* nums = new bool[k]; for (int i = 0; i < k; i++) nums[i] = true; for (int i = 1; i < k; i++) { int j = i; while (i + j + 2 * i * j <= k) { nums[i + j + 2 * i * j] = false; j++; } } for (int i = 1; i < k; i++) { if (nums[i]) { cout << 2 * i + 1 << endl; } } delete[]nums; nums = NULL; system("pause>0"); } For n < 200 everything works well. But for n >= 200 I get the error: Debug Error! <...> HEAP CORRUPTION DETECTED: after Normal block (#764) at 0x008655A0. CRT detected that the application wrote to memory after end of heap buffer. How to fix it? I am sure that this problem is surrounding dynamic array nums.
This loop while (i + j + 2 * i * j <= k) { nums[i + j + 2 * i * j] = false; j++; } might access nums out of bounds in the last iteration, when i+j+2*i*j == k, because the last valid index is k-1. Out of bounds access is undefined behavior in C++, hence your code might appear to work for n < 200. Also, the index, i+j+2*i*j, increases by 1+2*i in each iteration, hence there are values for n where the out-of-bounds access does not occur (eg when k is prime). To make the condition a little less error prone, you can consider to rewrite the loop like this: for (int m = ... ; m < k; m+= 1+2*i) { nums[m] = false; }
70,070,537
70,070,576
save line from file to char pointer in c++, without pointing to variable
This might be a very basic c/c++ question, but I am really struggeling at it right now. I have a struct that looks something like this: struct connection_details { const char *server, *user, *password, *database, *mysql_port, *ssh_port; }; And I have the data in a seperate text file. So I would like to write a function, that takes a pointer to the struct, to write each line of the text file to the corresponding variable of the struct. void get_config(const std::string &config_path, connection_details *mysql) { ifstream file(config_path); string str; getline(file, str); mysql->user = str.c_str(); getline(file, str); mysql->server = str.c_str(); getline(file, str); mysql->database = str.c_str(); //... file.close(); } But now the char pointer points to a variable that no longer exists, and even if it still existed, every part of the struct would point to the same variabe, not the content it was supposed to be. I know this is a rather basic question, but I came to the point where I don't now what to google anymore, so every help is welcome.
If you want to store string data in a way that is kept around as long as the struct is alive, then std::string does exactly that. So, ideally, you should replace the const char* members of connection_details with std::string: struct connection_details { std::string server, user, password, database, mysql_port, ssh_port; }; Conveniently, this also allows you to just getline() directly into the members: void get_config(const std::string &config_path, connection_details *mysql) { ifstream file(config_path); getline(file, mysql->user); getline(file, mysql->server); getline(file, mysql->database); // ... // No need to .close(), it's implicit. } Then, you can use .c_str() wherever you would have used the const char* // Assuming you can't change this... void some_function(const char* str); int main() { connection_details details; get_config("path/to_config.txt", &details); // before: //some_function(details.server); // after: some_function(details.server.c_str()); } Edit: Now, if you have no control over connection_details, then you can still use std::string, but you just have to add a layer of indirection: struct connection_details { const char* server, user, password, database, mysql_port, ssh_port; }; struct connection_details_data { std::string server, user, password, database, mysql_port, ssh_port; // Make it convertible into connection_details operator connection_details() const { return { server.c_str(), user.c_str(), password.c_str(), database.c_str(), mysql_port.c_str(), ssh_port.c_str() }; } }; void get_config(const std::string &config_path, connection_details *mysql) { // ... } int main() { connection_details_data details_data; get_config("path/to_config.txt", &details_data); // Make sure details_data outlives details! connection_details details = details_data; // ... }
70,071,109
70,072,187
error when declaring an inner class template field
I have an error with the following code, using the inner template class Node. the error is when declaring the root private field: "member root declared as a template". template <typename KeyType, typename ValueType> class TreapBST : public AbstractBST<KeyType, ValueType> { public: ..... private: template <typename K, typename V> struct Node { .... }; template <typename K, typename V> typename TreapBST<K, V>::Node<K, V>* root = nullptr; };
I think you have the basic idea right but are getting the syntax confused. When you write a class template you do not need to keep repeating template <typename K, typename V> for each member unless you want that K and V to be two types that are different from class parameters KeyType and ValueType. If you just need KeyType and ValueType you don't need to redeclare members as templates. For example the following will compile: template <typename KeyType, typename ValueType> class AbstractBST { //... }; template <typename KeyType, typename ValueType> class TreapBST : public AbstractBST<KeyType, ValueType> { public: //... private: struct Node { KeyType key; ValueType val; //... }; Node* root = nullptr; }; int main() { TreapBST<std::string, int> treap; return 0; };
70,071,581
70,071,848
How to split definition and declaration with friend function and inheritance
I need to compile something like this: struct Base { virtual void func1()=0; // ... friend void Derived::func2(Base *base); private: int some_private; } struct Derived : Base { virtual func3()=0; // ... void func2(Base *child) { std::cout << child->some_private; } }; But I keep getting compilation error. I tried swapping structures or declaring them first, but I can't declare Derived first (because of inheritance), and I can't declare Base first (because I need to declare friend function in Derived). What to do?
You have a few basic solutions. The most obvious is to change from private to protected. In C++, protected means subclasses have access. You can add more public (perhaps protected) accessor methods instead. You can forward-reference the entire Derived class and friend the entire class. Personally, I have never felt a need to use friend methods or classes, and I don't know under what circumstances I'd have to be in before I wouldn't depend on other ways to accomplish whatever I'm trying to accomplish. For this particular solution, I'd change the access to protected.
70,071,928
70,072,041
Having different specialization of a class template and the specialization definitions have functions with other specializations in its signature
So I have a class template for example in Template.h template <typename T> class Something { public: static_assert(std::is_floating_point<T>::value, "Floating Point only"); }; and I separated the float and double specialization into different .h files float.h #include "Template.h" template<> class Something<float> { public: std::string Name = "Float"; void DoSomething() { std::cout << "Float Thing\n"; } }; and Double.h #include "Template.h" template<> class Something<float> { public: std::string Name = "Double"; void DoSomething() { std::cout << "Double Thing\n"; } }; I include the three files in order in my .cpp file and it works fine but I need to add another function to the float specialization which takes Something as a parameter void SayDouble(Something<double> _D) { std::cout << _D.Name << '\n'; } and then include Double.h after template.h and it works but when I try to do the same in Double.h and add a function which takes or returns Something<float> and includes float.h after tempalte.h. it gives me a lot of errors about re-instantiation Float.h(17,19): error C2039: 'Name': is not a member of 'Something<double>' 1>Float.h(16): message : see declaration of 'Something<double>' 1>Double.h(7,1): error C2908: explicit specialization; 'Something<double>' has already been instantiated 1>Double.h(19,2): error C2766: explicit specialization; 'Something<double>' has already been defined 1>Float.h(16): message : see previous definition of 'Something<double>' 1>Float.h(19,2): error C2766: explicit specialization; 'Something<float>' has already been defined 1>Float.h(7): message : see previous definition of 'Something<float> I don't really understand the problem what I guessed is that maybe having an specialization of the template in the functions signature instantiates the template then when it tries to instantiate it again in the definition it gives "has already been defined error" But I don't know how to rly solve this as I need to have functions referring to other specializations I am using Visual Studio Community 2019 version 16.11.6
An explicit specialization is a distinct class and does not have to resemble the original template at all. You can change the functions, make completely different ones, or whatever. This is usually the point of partial specialization, so a const T can be a different interface than a plan T etc. Any explicit specializations must be declared before that specialization is used. That's why you get redeclaration errors. Also, you showed <float> twice, I assume that's a paste error? The one in Double.h should be <double> right? You violated that with your circular reference. You can fix that by declaring the one you need (without defining it), similarly to how you do with mutually recursive functions. Here is the correctly-compiling and running code: https://godbolt.org/z/x1TcTE7Me You'll notice that the definition of //template<> // Don't use the `template<>` prefix here!!! inline void Something<float>::SayDouble(Something<double> p_D) { std::cout << p_D.Name << '\n'; } // I'm showing it with `inline` in case you put it in a header. It can go in // some CPP file though, as it's been declared in the class specialization. does not use the template prefix. That's because this is defining a member function (that's not a template) for a class just like a normal class — the explicit (and not partial) specialization is a normal class like any other, not a template. It just says "when I ask for this specialization of that template, use this class instead of generating one". Finally, the parameter name _D is not allowed. "If the programmer uses such identifiers, the behavior is undefined."
70,072,105
70,072,148
"More?" in C++ when taking in console input
I was programming in C++ when I noticed some... odd behavior when taking in console input. Let me explain. #include <iostream> int main(int argc, char *argv[]) { if (argc == 1) { std::cout << "Hello!\n"; } if (argc >= 2) { } } Pretty simple program, right? Now, when I type in "programName ^" I get a cryptic message, saying "More?" on the console window. On pressing enter, it prompts again and on pressing it once more it closes the application. Out of curiosity, I tried doing this on some other console input applications I have made and they all do this. What does "More?" mean? I never coded that in, so why is it there?
I'm able to reproduce the behavior with g++ on Windows. The DOS shell is interpreting "^" as some kind of "continuation character". The ^ symbol (also called caret or circumflex) is an escape character in Batch script. When it is used, the next character is interpreted as an ordinary character. Look here for more details: https://forums.tomshardware.com/threads/when-did-become-special-on-the-command-line.1071200/
70,072,902
70,232,896
c++ vector string problem about case sensitivity
so in c++ 'A' and 'a' are different characters, if we have a vector that contains both upper and lowercase letters, how to write a function that transforms this vector into some vector that is case insensitive, for example, 'ABba' becomes the same as 'abba'. so for example, I want to count the number of different characters within the string, for example, "ABba" in this case output must be 2, because A a are 1 same group, B and b same as well, this string also may contain numbers, for example. ABba1212 --> answer should be 4.
The standard approach for doing case insensitive comparisons is: Decide for either upper or lower case and convert all letters to this case. Then, do your operations. In C++ you have a family of functions for that purpose. std::toupperand std::tolower. Please check in CPP Reference. If you know what character set you have, there are also other possibilities. In western countries very often ASCII characters are uses. In that case, you can even do bit operations for conversions. Or, additions or subtractions. Some examples for converting to lower case with ASCII characters #include <iostream> #include <cctype> int main() { char c = 'A'; c = (char)std::tolower(c); std::cout << "\nWith tolower: " << c << '\n'; c = 'A'; if (c >= 'A' and c <= 'Z') c += ('a' - 'A'); std::cout << "\nWith addition: " << c << '\n'; c = 'A'; if (c >= 'A' and c <= 'Z') c |= 32; std::cout << "\nWith bit operation: " << c << '\n'; } Next, counting different characters. If you want to count the different characters in a string, then you need to iterate over it, and check, if you saw the character or not. There are really many different solutions for that. I will show you a very basic one and then a C++ solution. It is made for 8 bit char values. #include <iostream> #include <cctype> #include <string> int main() { std::string test{"ABba1212"}; // There are 256 different 8 bit char values. Create array and initialize everything to false bool weHaveACharValueForThisASCII[256] = {}; // Iterate over all characters in the source string for (char c : test) // And mark, if we found a certain char weHaveACharValueForThisASCII[std::tolower(c)] = true; // Now we want to count, how many different chars we found int sum = 0; for (bool b : weHaveACharValueForThisASCII) if (b) ++sum; // Show result std::cout << sum; return 0; } In C++ you would use a std::unordered_set for this. It can only contain unique values and uses fast hashing fordata access. Please see here. #include <iostream> #include <cctype> #include <string> #include <unordered_set> int main() { std::string test{"ABba1212"}; // Here we will store the unique characters std::unordered_set<char> unique{}; // Iterate over all characters in the source string for (char c : test) unique.insert((char)std::tolower(c)); // Show result std::cout << unique.size(); }
70,072,926
70,079,715
yaml-cpp : How to read this yaml file content using c++ /Linux (using yaml-cpp version = 0.6.3 )
i am trying to read each Node and its respective content (yaml content is below) I am ending up with belwo error . Error: terminate called after throwing an instance of 'YAML::TypedBadConversion sample code : #include <yaml-cpp/yaml.h> YAML::Node config = YAML::LoadFile('yamlfile'); std::cout << config["Circles"]["x"].as<std::int64_t>(); Also i tried with some other approach but perhaps this yaml formt is complex one . I could read a sample format of yaml but not the one i have mentioned below . Any helping hand ? sample.yaml - Pos: sensor - pos1 Rectangle: - x: -0.2 y: -0.13 z: 3.26 - x: 0.005 y: -0.13 z: 3.2 - x: -0.2 y: 0.10 z: 3.26 - x: 0.00 y: 0.10 z: 3.2
The code in the question does not match the sample.yaml file you've provided but here's an example of how you could extract the floating points you have in the Rectangle in sample.yaml. #include "yaml-cpp/yaml.h" #include <iostream> int main() { try { YAML::Node config = YAML::LoadFile("sample.yaml"); // The outer element is an array for(auto dict : config) { // The array element is a map containing the Pos and Rectangle keys: auto name = dict["Pos"]; std::cout << "Name: " << name << '\n'; auto rect = dict["Rectangle"]; // loop over the positions Rectangle and print them: for(auto pos : rect) { std::cout << pos["x"].as<double>() << ",\t" << pos["y"].as<double>() << ",\t" << pos["z"].as<double>() << '\n'; } } } catch(const YAML::BadFile& e) { std::cerr << e.msg << std::endl; return 1; } catch(const YAML::ParserException& e) { std::cerr << e.msg << std::endl; return 1; } } Output: Name: sensor - pos1 0.2, -0.13, 3.26 0.005, -0.13, 3.2 -0.2, 0.1, 3.26 0, 0.1, 3.2
70,073,211
70,073,342
How do you find a string/char inside another string that's in a vector in C++? [that works for me]
I looked this up on multiple forum pages, not just stack overflow, and have tried many solutions from the 'Check if a string contains a string in C++' post, along with others, and tried almost every single solution posed but none of them seem to work for me? I tried the vector[i].find(std::string2) along with if(strstr(s1.c_str(),s2.c_str())) {cout << " S1 Contains S2";} along with std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"; std::string needle = "pisci"; auto it = std::search(in.begin(), in.end(), std::boyer_moore_searcher( needle.begin(), needle.end())); if(it != in.end()) std::cout << "The string " << needle << " found at offset " << it - in.begin() << '\n'; else std::cout << "The string " << needle << " not found\n"; and more solutions, (adapted to my code), but none have worked. The only one I didn't try was std::string.contain() but that's because visual studios (2019 v.142 -if that helps) [C++ standard language I'm using, Preview - Features from the Latest C++ Working Draft (std:c++latest),] wouldn't recognize the function -because it wouldn't recognize the larger library for some reason. I even tried reversing the two variables in case I was mixing the two up, and was looking for the larger variable in the smaller one. I'm rather new at C++ so I'm not great at problem-solving with stuff like this, so forgive my ignorance if you would. Does the problem arise because what I'm looking for is in a vector? I created a vector <string> names = {"Andrew John", "John Doe",}; with names in it, and am trying to 'peer' into it and find keywords, but again, nothing works. Is there a special function to call when looking for something in a vector? Any help would be very much appreciated!
How do you find a string/char inside another string that's in a vector in C++? If the std::vector<std::string> isn't sorted, I would use std::find_if. Example: #include <algorithm> #include <iostream> #include <string> #include <vector> int main() { // A vector with some strings: std::vector<std::string> vec{ {"Lorem ipsum dolor sit amet, consectetur adipiscing elit," " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"}, {"Foo bar"}}; std::string needle = "pisci"; size_t pos; // find and save position in the found string auto it = std::find_if(vec.begin(), vec.end(), [&needle,&pos](const std::string& str) { return (pos = str.find(needle)) != std::string::npos; }); if(it != vec.end()) { std::cout << "Found needle at position " << pos << " in string\n" << *it << '\n'; } } Demo Let's take a closer look at the lambda expression used in the std::find_if: [&needle,&pos](const std::string& str) { return (pos = str.find(needle)) != std::string::npos; } A lambda is an instance of an anonymous class with an operator() which makes it Callable. You can it compare with a struct like below that has an instance named foo which can be called: struct { void operator()() { std::cout << "foo1\n"; } } foo1; // oldschool auto foo2 = [](){ std::cout << "foo2\n"; }; // lambda version: int main() { foo1(); // calling foo1() - prints foo1 foo2(); // calling foo2() - prints foo2 }} In the lambda used in the find_if there is also [&needle,&pos]. This means that the constructed lamba will contain hold references to those two variables to be able to use them inside the function. Compare with a plain struct std::string s1 = "S1"; std::string s2 = "S2"; struct { // struct capturing a string by reference void operator()() { std::cout << "foo1 " + s + '\n'; } std::string& s; } foo1{s1}; // lamda capturing by reference auto foo2 = [&s2]() { std::cout << "foo2 " + s2 + '\n'; }; foo1(); // prints "foo1 S1" foo2(); // prints "foo2 S2" So, as you can see lambda functions and functional objects like the anonymous structs instances above have a lot in common. The lambda in the answer captures two variables by reference, to "outside" variables, needle and pos and it takes an argument (const std::string& str) whenever it's called. With that str it tries to find needle and assigns the result to pos pos = str.find(needle) pos is then compared with std::string::npos. If it's not std::string::npos the needle was found and the lambda will return true which stops the std::find_if function from looking further and returns an iterator to the found std::string. As a bonus, pos will still be set to latest value it was assigned - which is the position in the string where the needle was found.
70,073,526
70,104,450
Matrix multiplication in c++ armadillo is very slow
I'm doing some basic multiplication using armadillo but for some reason it takes very long to complete. I'm quite new to c++ so I might be doing something wrong, but I can't see it even in this very basic example: #include <armadillo> #include <iostream> using namespace arma; int main(){ arma::vec coefficients = {1.0, 1.09, 1.08}; arma::mat X = arma::mat(100000, 3, fill::randu) * coefficients; cout << X.n_cols; } when I mean very slow, I have run this example for some minutes and it doesn't finish EDIT I run the script with perf stat ./main, but stopped it after some time because it shouldn't take that long. This is the output. ^C./main: Interrupt Performance counter stats for './main': 257,169.20 msec task-clock # 1.003 CPUs utilized 3,342 context-switches # 12.995 /sec 215 cpu-migrations # 0.836 /sec 1,312 page-faults # 5.102 /sec 963,025,520,077 cycles # 3.745 GHz 542,959,361,927 instructions # 0.56 insn per cycle 113,002,342,332 branches # 439.409 M/sec 1,095,168,312 branch-misses # 0.97% of all branches 256.349026907 seconds time elapsed 147.860947000 seconds user 109.317743000 seconds sys
Armadillo is a template-based library that can be used as a header-only library. Just include its header and make sure you link with some BLAS and LAPACK implementation. When used like this, armadillo assumes you have a BLAS and LAPACK implementation available. You will get link errors if you try to use any functionality in armadillo that requires them without linking with them. If you don't have BLAS and/or LAPACK, you can change the armadillo_bits/config.hpp file and comment out some defines there such that armadillo uses its own (slower) implementation of that functionality. Alternatively, armadillo can be compiled as a wrapper library, where in that case you just link with the "armadillo" wrapper library. It's CMake code will try to determine during configure time what you have available and "comment-out the appropriated defines" in case you don't have some requirement available, which in turn will make it use the slower implementation. That "configure" code is wrongly determining that you don't have BLAS available, since BLAS is the one providing fast matrix multiplication. My suggestion is to just make sure you have BLAS and LAPACK installed and use armadillo as a header-only library, making sure to link your program with BLAS and LAPACK. Another option is using the conan package manager to install armadillo. Conan added a recipe to install armadillo recently. It has the advantage that it will install everything that armadillo needs (it installs openblas, which provides both a BLAS and LAPACK implementation) and it is system agnostic (similar to virtual environments in Python). Note In the comments you mentioned that it worked with g++ main.cpp -o main -DARMA_DONT_USE_WRAPPER -larmadillo -llapack. The reason is that even if you installed the wrapper library, if you define ARMA_DONT_USE_WRAPPER you are effectivelly using armadillo as a header-only library. You can replace -larmadillo -llapack with -lblas -llapack.
70,073,540
70,074,272
C++ detect if a type can be called with a template type
I'm working on a program where some data is statically allocated and some is dynamically allocated. Now I want to have another type that can be called with any template of the type as its argument. #include <array> #include <vector> template <int size> class Foo { std::array<int, size> data; public: int& operator[](std::size_t idx) {return data[idx];} }; template <> class Foo<-1> { std::vector<int> data; public: int& operator[](std::size_t idx) {return data[idx];} }; // option 1- polymorphism struct FooCaller { virtual void operator()(Foo data) = 0; // how would I make this work with both forms of Foo? }; // option 2- generic programming template <class T> concept CanCallFoo = requires (const T& t) { t(std::declval<Foo&>()); // how do I ensure that this can call any overload of Foo? }; Both methods would be fine, but I'm not sure how to go about this. Because the full code is more complex, I'd rather not have both Foos inherit from a base.
A callable F could write a restriction that it can be called by Foo<x> such that an arbitrary function of x must be true to be valid. In order for your "can be called with any Foo" test to work, you would have to invert an arbitrary function at compile time. There is no practical way to do this short of examinjng all 2^32 possible values of x. No, really. The problem you have is that the type F is possibly too powerful for you to determine its properties. This is related to Halt and Rice's theorem and the fact that template metaprogramming and C++ overload resolution is Turing complete (only related, because 2^32 is finite). In the other case, you could type erase. Write a type RefAnyFoo/AnyFooValue that can be constructed from any Foo type and "type erases" the operations you want, like how std::function<void(int)> type erases. It could either duck type the Foo or actually restrict to instsnces of types made from the template. Then your interface is one that takes a AnyFooValue/RefAnyFoo (depending if you are talking about copies or references). Now, flipping this over, you can write a concept that accepts F that take RefFooAny. This isn't quite what you asked for, but plausibly you have an X/Y problem; you had a real problem, came up with incomplete solutions, then asked about how to get your solutions working, instead of the original problem. Similarly, it is possible you only care about certain ducktype properties of Foo<?> and not the specific type. Then a concept that checks those ducktypes could be used by your callable; this again deosn't solve your problem, as much as it flips it upside down, because you cannot verify a callable accepts an entire concept from outside the callable.
70,074,226
70,074,280
How compile a c++ complex folder with a simple command?
I have a many c++ files in a folder: > project - a.cpp - a.h - b.cpp - b.h - main.cpp - .editorconfig - .gitignore And use this command to compile my code: g++ *.c* -o main However I need organize my code in > project > src > classes - a.h - b.h > methods - a.cpp - b.cpp - main.cpp - .editorconfig - .gitignore Some questions: 1 - What command can I use to compile my project? 2 - Is it a good folder structure?
I would try to compile it with the following command: g++ src/main.cpp src/methods/*.cpp -I src/classes -o myprogram As long as your compilation times are reasonable, there is not much need to use a build system like Make yet. I don't know if it's a good directory structure, but that's a pretty subjective question. It's more common to see directories named "include" or "header" than "classes", since it's possible to have header files that do not define classes. I usually like to put all of the source files in the same directory unless there are a lot of them, or some are written by different teams.
70,075,005
70,081,226
Issues working with "raw" pointers. How do I remove duplicate values from a custom Linked List?
Right now my code is a little... over-complicated. I feel I must be missing a simpler algorithm for getting this task done. Basically the only rules for this assignment are that we can't use containers or other libraries. I'll include my code below so you might get a better idea what I'm trying to do. The code compiles, but only gives me correct output sometimes. The code has a few steps, it first iterates through a linked list which can have any data type and extracts one element at a time. Then it will compare each element against every other element in the list, if 2 matches are found among all the data in the list then the 2nd matching element is removed and the number of matches is set back to 1. I'm performing a push_back() and pop_front() on every element, but only a pop_front() on data which is repeated (when numMatches = 2). At the end, I reorganize based on the number of deletions done (or the number of extra elements) to put the list back in order. I'm not quite sure where the error is popping up, I feel it must have to do with the method of push_back() and pop_front() but I can't think of another way to iterate through pointers without the option of element access. As an example i/o if {1, 2, 4, 2, 3, 2, 3} was the input, the output would be {1, 2, 4, 3} void unique(){ if (this->size_ <= 0){ throw std::domain_error("unique() : must be 1 or more elements"); } // check each value against every other value // nested for loops? // always push, pop for any matches Node* outerElem = this->head_; int numDeletions; for (unsigned i = 0; i < this->size_; ++i){ int numMatches = 0; auto cmp = outerElem->data; Node* innerElem = this->head_; for(unsigned j = 0; j < this->size_ + 1; ++j) { if (innerElem->data == cmp){ ++numMatches; } if (numMatches <= 1) { // not delete, means we found same element // or non-matching element push_back(innerElem->data); innerElem = innerElem->next; pop_front(); } else if (numMatches == 2) { // means there are at least 2 instances of the same element innerElem = innerElem->next; pop_front(); ++numDeletions; --numMatches; // reset numMatches so it can detect if there's another match } } } for(unsigned k = 0; k < numDeletions; ++k) { // put values in original order push_back(this->head_->data); pop_front(); } } Here is the code for the Node class, which contains the pointers used: struct Node { T data; // Actual value for list element Node* next = nullptr; Node* prev = nullptr; }; Node* head_ = nullptr; Node* tail_ = nullptr; std::size_t size_ = 0; };
I would suggest providing a remove method on your linked list, and then you can just remove any found duplicates in your nested loop: void removeNode(Node* node) { // This method assumes that the provided node is a member of the list if (node == head_) { head_ = head_->next; } else { node->prev->next = node->next; } if (node == tail_) { tail_ = tail_->prev; } else { node->next->prev = node->prev; } size_--; delete node; } void unique() { Node* outerElem = this->head_; while (outerElem != nullptr) { auto cmp = outerElem->data; Node* innerElem = outerElem; while (innerElem->next != nullptr) { if (innerElem->next->data == cmp) { removeNode(innerElem->next); } else { innerElem = innerElem->next; } } outerElem = outerElem->next; } }
70,075,048
70,078,863
Would using placement new make the following code valid?
I am building a buffer that will be used in a class and wanted to know if the following is valid according to the C++ standard: #include <iostream> #include <cstdint> int main() { alignas(std::int32_t) char A[sizeof(std::int32_t)] = { 1, 0, 0, 0 }; std::int32_t* pA = new (&A) std::int32_t; std::cout << *pA << std::endl; return 0; } The buffer has been initialized as a char array of 4 bytes. Would doing a placement new on top of the structure allow me to access the bits underneath as an int32_t? Can I now access the memory space there as 4 chars (through the buffer object) or as 1 int32_t (through pA) without any violation to the standard? If not, is it possible to do some other way? NOTE: Yes, I am aware of endianness, but in this context, endianness doesn't matter. That's a different discussion.
(Assuming int and int32_t are the same type for brevity) In C++20, since A is an array of characters, an object of type int can be implicitly created in A, so only the following is needed: alignas(int) char A[sizeof(int)] = { 1, 0, 0, 0 }; int * pA = reinterpret_cast<int*>(&A[0]); std::cout << *pA << std::endl; The problem with your original new (&A) int is that it ends the lifetime of the original char[sizeof(int)] object that was initialised, so its value cannot be read. You now have a default-initialized int, which is UB to read. Your original code is thus equivalent to: int A; std::cout << A << std::endl; If you can't rely on C++ 20 implicit object creation, you can use type punning methods, which create objects of a different type with the same "bit pattern" (value representation). std::bit_cast (or a version implemented with std::memcpy) can be used: char A[sizeof(int)] = { 1, 0, 0, 0 }; int B = std::bit_cast<int>(A); std::cout << B << std::endl; Or std::memcpy to directly copy the value representation: char A[sizeof(int)] = { 1, 0, 0, 0 }; int B; std::memcpy(&B, A, sizeof(int)); std::cout << B << std::endl; You can use placement new to change the effective type of A from char[sizeof(int)] to int, like so: alignas(int) char A[sizeof(int)] = { 1, 0, 0, 0 }; // `A` has effective type `char[sizeof(int)]`; cannot be accessed through `int*` int * pA = new (&A) int(std::bit_cast<int>(A)); // `A` now has effective type `int`. This line should be optimised to do nothing to `A` at runtime. std::cout << *pA << std::endl; // Or using `A` directly std::cout << *std::launder(reinterpret_cast<int*>(A)) << std::endl;
70,075,288
70,075,358
Can a concept satisfaction of an expression, contains both type and the reference?
Is there a way to make the following code not so bloated? I mean join both type and a reference somehow (|| does not work). template<typename T> concept IntegralVector = std::integral<typename T::value_type> && requires(T t) { { t.size() } -> std::convertible_to<std::size_t>; } && (requires(T t) { { t[0] } -> std::same_as<typename T::value_type&>; } || requires(T t) { { t[0] } -> std::same_as<typename T::value_type>; }); A working trick can be: { 0 + t[0] } -> std::integral; But I want to stick with typename T::value_type
You probably want something like this: template <typename T, typename U> concept decays_to = std::same_as<std::decay_t<T>, U>; To use as: template<typename T> concept IntegralVector = std::integral<typename T::value_type> && requires (T t) { { t.size() } -> std::convertible_to<std::size_t>; { t[0] } -> decays_to<typename T::value_type>; }; This also catches value_type const& as an option, which I'm not sure was intentionally omitted.
70,075,346
70,075,583
Issues reading text from a file. Getting double reads
Hello friends at stackoverflow! I have written a program that saves 3 strings to a textfile. The code to write is: void my_class::save_file(const char* text) { for(auto ad: ad_list) { std::ofstream outputFile; outputFile.open(text, std::ios::app); if (outputFile.is_open()) { outputFile << ad.string1 << "|" << ad.string2 << "|" << ad.string3 << "|" << std::endl; outputFile.close(); } } } This gives me the file with the content: string1|string2|string3| <- //extra line here When i read from this file I do it with the following function: void my_class::read_file(const char* text) { // read file to stringsteam std::stringstream ss; std::ifstream fp (text); if (fp.is_open()) { ss << fp.rdbuf(); } fp.close(); string file_contents = ss.str(); // split to lines auto lines = splitString(file_contents, "\n"); // split to parts for (auto ad_text: lines) { // <-- this is the possibly the issue auto ad_parts = splitString(ad_text, "|"); string string1 = ad_parts[0]; string string2 = ad_parts[1]; string string3 = ad_parts[2]; auto new_class = MyClass(string1, string2, string3); //Adds (push_back) the class to its vector add_class(new_class); } } vector<string> my_class::splitString(string text, string delimiter) { vector<string> parts; size_t start = 0; size_t end = 0; while((end = text.find(delimiter, start)) != std::string::npos) { size_t length = end - start; parts.push_back(text.substr(start, length)); start = end + delimiter.length(); } start = end + delimiter.length(); size_t length = text.length() - start; parts.push_back(text.substr(start, length)); return parts; } Result: string1|string2|string3| string1|string2|string3| I'm pretty sure this copy is a result of the new line left behind by the write function. The read function splits the text into lines, and that would be 2 lines. I am currently splitting the lines in this loop "for (auto ad_text: lines)", and what I want to do is basically ( lines - 1 ). I do not understand how I can do that with the way I am interating through the for loop. Thanks in advance!
You can simplify your splitString function to look like below. Note the second parameter to splitString is a char now and not a std::string. //note the second parameter is a char and not a string now vector<string> splitString(string text, char delimiter) { vector<string> parts; std::string words; std::istringstream ss(text); while(std::getline(ss, words,delimiter )) { parts.push_back(words); } return parts; } For the above modification to work you have to make 2 additional changes: Change 1: Replace auto lines = splitString(file_contents, "\n"); to: auto lines = splitString(file_contents, '\n'); Change 2: Replace auto ad_parts = splitString(ad_text, "|"); to: auto ad_parts = splitString(ad_text, '|');
70,075,933
70,075,956
c++ sort() function is not sorting my vector
This is my code - Problem: The sorting comparator function which I have written is not doing anything. the code gets executed, comparator function also runs, but it does not modify my vector. And I don't understand why. Logic(which I have written): I have used region index as an index of my vector. For each region I have maintained a vector of (points, surname). Then, for each region, I have sorted my vector according to their points. then, I checked if there is no reputation in points on first position and second position, vis-a-vis for second and third position, that means we have clear winner, record them. Print the recorded winners. #include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; int main() { int participants, regions; cin >> participants >> regions; vector<vector<pair<int, string>>> cands(regions); string surname; int region, points; for (int i{0}; i<participants; i++) { cin >> surname >> region >> points; cands[region-1].push_back({points, surname}); } for (auto vec : cands) { sort(vec.rbegin(), vec.rend(), [](pair<int, string>& x, pair<int, string>& y) { return x.first > y.first; }); } // for (auto vec : cands) { // for (auto ele : vec) cout << ele.first << " " << ele.second << endl; // cout << endl; // } vector<pair<string, string>> teams; for (auto vec : cands) { if (vec[0].first == vec[1].first) teams.push_back({"?", ""}); else { if (vec.size() > 2) { if (vec[1].first == vec[2].first) teams.push_back({"?", ""}); else teams.push_back({vec[0].second, vec[1].second}); } else teams.push_back({vec[0].second, vec[1].second}); } } for (auto ele : teams) cout << ele.first << " " << ele.second << endl; return 0; }
for (auto vec : cands) { This create a copy of the elements in cands, not the actual element of cands itself. Change your code to: for (auto &vec : cands) {
70,076,273
70,076,531
What does ch!=?.? mean in c++
This is used here do {....} while(ch!=?.?); what does ch!=?.? mean here can anybody please help with it.
It's a syntax error with both clang and gcc. @JonathanLeffler is usually right and I think he nailed the root cause. I used to see this when text was being copied from Microsoft Word to the web (lack of transcode from a Windows code page to ascii/utf8?).
70,076,659
70,077,070
In C++, how do I fix a pointer class's variable becoming a nullptr when I call it?
I want to use a class: class2, within a class: class1. From what I read, to prevent a circular dependency, one must forward declare class2 in class1.h and have it be a pointer. After calling a function from class2 in my class1.cpp file. I'm unable to call the variables within class2 without getting "Unable to read memory" or a nullptr. Here's my code, thank you for the help: //main.cpp #include "Login.h" #include <iostream> using namespace std; int main() { Login login; login.StartMenu(); cout << "ENDING" << endl; system("pause"); return 0; } //Login.h (Class1) #pragma once #include <iostream> using namespace std; class GameManager; class Login { public: void StartMenu(); private: GameManager* manager; }; //Login.cpp #include "Login.h" #include "GameManager.h" void Login::StartMenu() { manager->GameStart(); } //GameManager.h (Class2) #pragma once class GameManager { public: void GameStart(); private: int level = 1; }; //GameManager.cpp #include "Login.h" #include "GameManager.h" void GameManager::GameStart() { cout << level; }
Generally, it is a good idea to keep dependencies between headers to a minimum, and using pointers for classes that are only forward-declared is an established way to do that. This is good practice even if there are no circular dependencies because it can greatly reduce recompilation times in large projects. Regarding your specific question: Essentially, the Login class, and especially the Login::StartMenu function, needs to know which GameManager instance to use. A pointer to that instance will be stored in manager. Ideally you can tell that at construction time of a Login instance via a GameManager * constructor argument: #ifndef LOGIN_H #define LOGIN_H class GameManager; /// This class handles the login procedure for a specific /// game manager which must be provided to the constructor. /// It cannot be copied (so it cannot be /// in arrays) or default-constructed. class Login { public: /// The constructor does nothing except initializing manager. /// @param gmPtr is a pointer to the game manager /// this instance is using. void Login(GameManager *gmPtr) : manager(gmPtr) { /* empty */ } void StartMenu(); private: GameManager* manager; }; #endif // LOGIN_H For completeness, here is how you would use it: #include "Login.h" #include "GameManager.h" #include <iostream> using namespace std; int main() { GameManager gm; Login login(&gm); // <-- provide game manager to login login.StartMenu(); cout << "ENDING" << endl; system("pause"); return 0; } If that is not possible because the GameManager instance does not exist yet or is otherwise unknown during construction of a Login instance (for example, if you have an array of Login instances, whose elements must be default-constructed) you can provide the argument to the Login::StartMenu method. But the constructor argument is much preferred because you can then be sure that the class is functional in the rest of the code — this kind of "invariants" are the main reason why constructors exist. It is certainly possible that you don't need to hold a pointer at all, if all functions get that pointer argument. Whether the Login class has a one-to-one relationship with a GameManager (in which case it simply holds a pointer to it) or not (in which case every function is told each time) is a design decision.
70,076,843
70,897,891
The matplotlibcpp show an error when I use subplot() in cpp
I tried to use matplotlibcpp.h for plotting graph in c++ code. Normal graphs are plotted well. However, when I write plt::subplot(); the program throw runtime error with "Call to subplot() failed". How can solve this problem? Below is my source code. #include <iostream> #include <vector> #include <map> #include <string> #include <matplotlib.h> namespace plt = matplotlibcpp; using std::cout; using std::map; using std::string; using std::vector; int main() { vector<int> x1(10); vector<int> x2(10); vector<int> y1(10); vector<int> y2(10); for(int i = 0; i <10; ++i) { x1[i] = i; y1[i] = i; x2[i] = i; y2[i] = i*2; } plt::subplot(1,2,1); // <- error raised point plt::plot(x1,y1); plt::title("y=x"); plt::subplot(1,2,2); plt::plot(x2,y2,"k-"); plt::title("y=2x"); plt::show(); } The full error message is terminate called after throwing an instance of 'std::runtime_error' what(): Call to subplot() failed. Aborted And, my compile option is g++ matplotlib_test.cpp -I/usr/include/python3.8 -lpython3.8 -o matplotlib_test My running environment is wsl2(windows-subsystem-linux) and ubuntu-20.04-LTS Lastly, could you recommend what is the best way for plotting graph with c++ code?
I had this problem too. But I finally found that if you use root user to run it or "sudo ./your_program", it would be alright enter image description here
70,076,998
70,077,024
all multiples of 3 from 1 to 100 by a for loop in c++
for (int x = 3; x <= 100; x%3 == 0; x++ ) { printf("%d\n", x); } I'm using the book "how to program C" by Deitel and there is this exercise, for this for loop, and they want me to fix it and get the output of all multiples of 3. I've solved this with an if statement. But im curious if there is another way to fix it within the loop. what i did was this : for (int x = 3; x <= 100; x++ ) { if(x%3 == 0){ printf("%d\n", x); } }
You can add 3 instead of 1 after each iteration, so that it will guarantee to be a mutiple of 3 Something like this: for (int x = 3; x <= 100; x += 3) { printf("%d\n", x); }
70,077,013
70,077,248
memory leak in c++ and how to fix it
I am getting this error with memory leak, I know i have to deallocate the memory but how to do it I am getting this error with memory leak, I know i have to deallocate the memory but how to do it please guide SongCollection::SongCollection(char* filename) { try { std::ifstream file("songs.txt"); if (file) { while (file) { std::string temp, t_artist, t_title, t_album, t_price, t_year, t_length; std::getline(file, temp, '\n'); if (!(temp.length() < 25)) { t_title = temp.substr(0, 25); t_artist = temp.substr(25, 25); t_album = temp.substr(50, 25); t_year = temp.substr(75, 5); t_length = temp.substr(80, 5); t_price = temp.substr(85, 5); auto strip = [&](std::string& str) { str = str.substr(str.find_first_not_of(" "), str.find_last_not_of(" ") + 1); str = str.substr(0, str.find_last_not_of(" ") + 1); }; strip(t_title); strip(t_artist); strip(t_album); m_storage = new Song; m_storage->m_title = t_title; m_storage->m_artist = t_artist; m_storage->m_album = t_album; try { m_storage->m_year = std::stoi(t_year); } catch (...) { m_storage->m_year = 0; } m_storage->m_length = std::stoi(t_length); m_storage->m_price = std::stod(t_price); collection.push_back(m_storage); } } } else { throw 1; } } catch (int& err) { std::cerr << "ERROR: Cannot open file [" << filename << "].\n"; exit(err); } } SongCollection::~SongCollection() { if (m_storage) { delete m_storage; m_storage = nullptr; } collection.clear(); } And I got this memory leak report ==141379== 2,345 (2,128 direct, 217 indirect) bytes in 19 blocks are definitely lost in loss record 3 of 3 ==141379== at 0x4C2A593: operator new(unsigned long) (vg_replace_malloc.c:344) ==141379== by 0x403991: sdds::SongCollection::SongCollection(char*) (SongCollection.cpp:34) ==141379== by 0x402856: main (w7_p2_prof.cpp:29)
The "best"™ solution is to not use pointers at all, as then there's no dynamic allocation that you can forget to delete. For your case it includes a few rather minor changes to make it work. First of all I recommend you create a Song constructor taking all needed values as arguments, then it becomes easier to create Song objects: Song::Song(std::string const& title, std::string const& artist, std::string const& album, unsigned year) : m_title(title), m_artist(artist), m_album(album), m_year(year) { } Then inside your SongCollection class use a vector of Song objects instead of pointers: std::vector<Song> collection; Then add songs to the vector while creating the objects all in one go: try { t_year = std::stoi(t_year); } catch (...) { t_year = 0; } collection.emplace_back(t_title, t_artist, t_album, t_year); And finally remove the SongCollection destructor. No pointers, no (explicit) dynamic allocation, no memory leaks. And no breaking the rules of three/five, by following the rule of zero.
70,077,570
70,089,910
Make a event for a mouse button even if application is minimized
I want to make an application that responds to a mouse button so I done this: case WM_LBUTTONDOWN: MessageBox( NULL, (LPCWSTR)L"HALLOOOO", (LPCWSTR)L"Worked", MB_ICONASTERISK | MB_OK | MB_DEFBUTTON2 ); break; but the problem is that this only works if the user clicks on the window and I want it to work even with the window minimized this work even if the application is minimized GetKeyState(VK_LBUTTON); but if I put this in a loop if I press it once it will detect 1 million times because it will just check if the key is down and if I add delay using Sleep(250) it may work but sometimes it will not detect anything even if the user pressed the key I want my app to be able to detect if a key is pressed even if it's minimized how can I do this?
Since you already have a window, call SetWindowsHookEx with WH_MOUSE_LL. The API is documented here and the parameters are explained. HHOOK SetWindowsHookExW( [in] int idHook, [in] HOOKPROC lpfn, [in] HINSTANCE hmod, [in] DWORD dwThreadId ); The lpfn hook procedure can be defined as follows: HWND hmain_window; HHOOK hhook; LRESULT CALLBACK mouse_proc(int code, WPARAM wparam, LPARAM lparam) { if (code == HC_ACTION && lparam) { if (wparam == WM_LBUTTONDOWN) { //MOUSEHOOKSTRUCT* mstruct = (MOUSEHOOKSTRUCT*)lparam; static int i = 0; std::wstring str = L"mouse down " + std::to_wstring(i++); SetWindowText(hmain_window, str.c_str()); } } return CallNextHookEx(hhook, code, wparam, lparam); } int APIENTRY wWinMain(HINSTANCE hinst, HINSTANCE, LPWSTR, int) { ... RegisterClassEx(...); hmain_window = CreateWindow(...); hhook = SetWindowsHookEx(WH_MOUSE_LL, mouse_proc, hinst, 0); MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } UnhookWindowsHookEx(hhook); return 0; }
70,077,576
70,077,787
How to properly read data from CSV file in C++
My input file userinfo.csv contains username and password in this format username,password shown below. frierodablerbyo,Rey4gLmhM pinkyandluluxo,7$J@XKu[ lifeincolorft,cmps9ufe spirginti8z,95tcvbku I want to store all the usernames and passwords in vector<string> usernames; vector<string> passwords; I've never used C++ for file handling, only python EDIT1 #include <bits/stdc++.h> using namespace std; int main() { fstream myfile; myfile.open("small.csv"); vector<string> data; vector<string> usernames, passwords; while(myfile.good()){ string word; getline(myfile, word, ','); data.push_back(word); } for(int i=0; i<8; i=i+2){ usernames.push_back(data[i]); } for(int i=1; i<8; i=i+2){ passwords.push_back(data[i]); } } I know above code is bad, how can I improve it because my actual csv file contains 20000 rows.
You can try something like this std::vector <std::pair<std::string, std::string>> vec_credentials; std::ifstream is("credentials.csv"); if(is.is_open()) { std::string line; while(getline(is, line)) { std::stringstream ss(line); std::string token; std::vector <std::string> temp; // this is good if in the future you will have more than 2 columns while(getline(ss, token, ',')) { temp.push_back(token); } vec_credentials.push_back(std::make_pair(temp[0], temp[1])); } is.close(); }
70,078,468
70,079,348
Are move semantics guaranteed by the standard?
I think I understand the gist of move-semantics in general but am wondering, whether the C++ standard actually guarantees move-semantics for std-types like std::vector. For instance is the following snippet guaranteed to produce check = true (if the used compiler/std-lib is standard-compliant)? std::vector<int> myVec; int *myPtr = myVec.data(); std::vector<int> otherVec = std::move(myVec); int *otherPtr = otherVec.data(); bool check = myPtr == otherPtr; In other words: When moving a a std::vector, does the standard guarantee that I will actually perform a move and not a copy after all (e.g. because the used std-lib hasn't implemented a move-constructor for std::vector)?
I believe this is guaranteed for allocator-aware containers by the following requirement from [tab.container.alloc.req]: X(rv) X u(rv); Postconditions: u has the same elements as rv had before this construction;... Note the words "same elements", not "elements with the same content". For instance, after std::vector<int> otherVec = std::move(myVec); first element of otherVec must therefore be the very same element/object that was the first element of myVec before this move-construction.
70,079,733
70,090,828
Opengl Camera rotation around X
Working on an opengl project in visual studio.Im trying to rotate the camera around the X and Y axis. Thats the math i should use Im having trouble because im using glm::lookAt for camera position and it takes glm::vec3 as arguments. Can someone explain how can i implement this in opengl? PS:i cant use quaternions
The lookAt function should take three inputs: vec3 cameraPosition vec3 cameraLookAt vec3 cameraUp For my past experience, if you want to move the camera, first find the transform matrix of the movement, then apply the matrix onto these three vectors, and the result will be three new vec3, which are your new input into the lookAt function. vec3 newCameraPosition = movementMat4 * cameraPosition //Same for other two Another approach could be finding the inverse movement of the one you want the camera to do and applying it to the whole scene. Since moving the camera is kind of equals to move the object onto inverse movement while keep the camera not move :)
70,079,824
70,079,908
Error when passing arguments to pthread_create()
I am trying to create a Thread-Pool-like structure for pthreads to do identical jobs for network programming, which is very similar to this question. However, a problem occurred as I tried to pass the arguments of the init() method to pthread_create(). Code class ThreadPool{ public: BlockingQueue socket_bq; pthread_mutex_t* threads[THREAD_NUM]; // store the pointer of threads ThreadPool(); void init(pthread_attr_t* attr, void*start_routine(void*), void* arg); }; void ThreadPool::init(pthread_attr_t* attr, void*start_routine(void*), void* arg){ // create threads for(int i = 0; i < THREAD_NUM; i++){ if(pthread_create(threads[i], attr, start_routine, arg)!=0){ fprintf(stderr, "Thread Pool Init: falied when creatng threads"); exit(1); } } } Error message error: no matching function for call to 'pthread_create' if(pthread_create(threads[i], attr, start_routine, arg)!=0){ ^~~~~~~~~~~~~~ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/pthread.h:329:5: note: candidate function not viable: no known conversion from 'pthread_mutex_t *' (aka '_opaque_pthread_mutex_t *') to 'pthread_t _Nullable * _Nonnull' (aka '_opaque_pthread_t **') for 1st argument int pthread_create(pthread_t _Nullable * _Nonnull __restrict, ^ 1 error generated.
The definition of threads is incorrect. It should be: pthread_t* threads[THREAD_NUM];
70,080,102
70,082,595
How do i "filter" output from vector<Parent*>
Here is the problem. I have vector<D2*>, where D2 is a Parent. I add there childs: D3 and D4. void readFromInput(std::vector<D2*>& vec) { std::cout << "\nSecond class input"; int x = 0, y = 0, z = 0; std::cout << "\nEnter x: "; std::cin >> x; std::cout << "Enter y: "; std::cin >> y; std::cout << "Enter z: "; std::cin >> z; vec.push_back(new D3(x, y, z)); } void readFromInput(std::vector<D2*>& vec) { std::cout << "\nSecond class input"; int x = 0, y = 0, z = 0; std::cout << "\nEnter x: "; std::cin >> x; std::cout << "Enter y: "; std::cin >> y; std::cout << "Enter z: "; std::cin >> z; vec.push_back(new D4(x, y, z)); } And here is how i output it. void output(std::vector<D2*>& vec) { for (const auto& item : vec) { item->display(); std::cout << " | "; } } display() is a virtual function, btw. So, when i use "output" i see every single element in this vector, of course. Is there any method to ignore, for example, elements from D3 or D4? I mean when vec.push_back(new D3(1, 1, 1)), vec.push_back(new D4(2, 2, 2)) My ouput will be 1 1 1 | 2 2 2 Can it be 1 1 1| or 2 2 2| , using the same function?
For your particular case you can use dynamic_cast<T>(expression). See some other stack overflow answers dynamic_cast and static_cast in C++ When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? You can do something like this void output(std::vector<D2*>& vec) { for (const auto& item : vec) { auto ptr = dynamic_cast<D3*>(item) if(ptr != nullptr){ ptr->display(); }else{/*Do nonthing*/} std::cout << " | "; } } Please note that this is a bad practice! If you want this kind of functionality you should re-think that design of your program.
70,080,132
70,080,179
winforms identifiers are not visible
I have a button click event handler that draws a graph. System::Void Practform::MyForm::draw_Click(System::Object^ sender, System::EventArgs^ e) { . . . } then I decided to put the drawing of the graph into a separate function, since I would have to call it for the timer.and I got the following.many indentifiers turned out to be undefined: I tried to follow the VS prompts but it didn't help either at the same time, I have defined at the beginning of the cpp file: using namespace System; using namespace System::Windows::Forms; tell me, what should I do to make them visible again?What should I write?
You are missing a reference to the System::Drawing assembly. Add using namespace System::Drawing; at the top of your program. System::Windows::Forms contains classes related to, well, forms and controls. System::Drawing contains class related to, well, drawing.
70,080,192
70,080,336
Can we replace `if (!x) x=true` with `x=true` directly?
I am doing some refactoring work and came across such a piece of code: bool x = false; ...// maybe some logical work would change the value of x. if (!x) { x = true; } So, I am curious whether I can do such a replacement: x = true; As you can see, I assign x to true directly, which may reduce the number of instructions in the CPU, but I am not sure if there are any hidden dangers. Any suggestions?
x = true; is clearer than if (!x) { x = true; }. From performance point of view, former avoids branching, whereas the later doesn't touch to "cacheline" (in one case). And compiler might change one to another with as-is rule anyway.
70,080,350
70,080,961
QCandlestickSet is undefined C++ Qt5.15
I'm using Visual Studio 2019 Community x64, Qt version 5.15.2. I have the 'Charts' module installed and selected in Project -> Properties -> Qt Project Settings -> Qt Modules My code: #include <QCandlestickSet> struct Bar { double open, close, high, low; qint64 timestamp; Bar() : open(0.0), close(0.0), high(0.0), low(0.0), timestamp(0) { } QCandlestickSet * toCandle(void) { return new QCandlestickSet(this->open, this->high, this->low, this->close, this->timestamp); } }; I am getting the error: Severity Code Description Project File Line Suppression State Error (active) E0020 identifier "QCandlestickSet" is undefined ProjectName ..\Bar.h 27 Any help would be appreciated. Thank you in advance.
As mentioned in the comments by G.M., everything QtChart related is held within a namespace called QtCharts. Doing any of the following will fix this issue: using QtCharts::QCandlestickSet; OR using namespace QtCharts; OR QtCharts::QCandlestickSet * toCandle(void) { return new QtCharts::QCandlestickSet(this->open, this->high, this->low, this->close, this->timestamp); } Although the namespace is not mentioned in the page relating to QCandlestickSet, it is mentioned on the QtCharts page
70,080,367
70,080,722
How to read Ctrl+C as input
(in Linux) The methods I found all use signal . Is there no other way? Is there anything I can do to make the terminal put it into the input buffer?
In order to "read CTL+C as input" instead of having it generate a SIGINT it is necessary to use tcsetattr() to either clear cc_c[VINTR] or clear the ISIG flag as described in the manual page that I linked to, here. You will need to use tcgetattr, first, to read the current terminal settings, adjust them accordingly, then tcsetattr to set them. You should make sure that the terminal settings get reset to their original defaults when your program terminates, it is not a given that the shell will reset them to default, for you.
70,081,393
70,102,704
Clang Tidy config format
At the moment I am using the Clang Format utility in my project. In order to share its settings in my team, I put the .clang-format configuration file in the root of the project folder, and now IDE automatically loads it when working with the project. In the same way, I want to use the Clang Tidy utility. However, unlike Clang Format, I cannot find a description of the configuration file format or a utility to create it. I need IDE to also automatically load these settings and take them into account in autoformatting, so it's not possible for me to run the utility using a script that will pass it the necessary parameters. Is there a way to achieve what I need?
.clang-tidy file format is actually specified in the command-line help, see the documentation. --config=<string> - Specifies a configuration in YAML/JSON format: -config="{Checks: '*', CheckOptions: [{key: x, value: y}]}" When the value is empty, clang-tidy will attempt to find a file named .clang-tidy for each source file in its parent directories. --config-file=<string> - Specify the path of .clang-tidy or custom config file: e.g. --config-file=/some/path/myTidyConfigFile This option internally works exactly the same way as --config option after reading specified config file. Use either --config-file or --config, not both. All you need to do is to put the config string in a file and you're good to go. If you don't specify the --config-file option it will automatically search for a .clang-tidy file in the directory where the checked code is. An example .clang-tidy file: Checks: '-*,bugprone-*' CheckOptions: - key: bugprone-argument-comment.StrictMode value: 1 - key: bugprone-exception-escape.FunctionsThatShouldNotThrow value: WinMain,SDL_main FormatStyle: 'file' This would run all bugprone checks and set options for two of them.
70,081,432
70,082,530
How to explicitly instantiate a func template with no parameter?
I have a member func template as following: using ArgValue_t = std::variant<bool, double, int, std::string>; struct Argument_t { enum Type_e { Bool, Double, Int, String, VALUES_COUNT }; template<typename T> as( const Argument_t& def ) const; std::string name; ArgValue_t valu; ArgValue_t maxv; ArgValue_t minv; Type_e type = Int; int prec = 0; }; // specializing for bool template<> bool Argument_t::as<bool>( const Argument_t& def ) const { if( static_cast<Type_e>( valu.index() ) != Bool ) return get<bool>( def.valu ); return get<bool>( valu ); }; // specializing for double template<> double Argument_t::as<double>( const Argument_t& def ) const { if( static_cast<Type_e>( valu.index() ) != Double ) return get<double>( def.valu ); return min<double>( get<double>( def.maxv ), max<double>( get<double>( def.minv ), get<double>( valu ) ) ); }; // specializing for string template<> string Argument_t::as<string>( const Argument_t& def ) const { if( static_cast<Type_e>( valu.index() ) != String ) return get<string>( def.valu ); return get<string>( valu ); }; // default version for all of integral types template<typename T> T Argument_t::as( const Argument_t& def ) const { if( static_cast<Type_e>( valu.index() ) != Int ) return get<T>( def.valu ); return min<T>( get<T>( def.maxv ), max<T>( get<T>( def.minv ), get<T>( valu ) ) ); }; When I compiling it, I get link error, so I add a few of explicit instantiation of them. // there is no problem with these three template string Argument_t::as<string>( const Argument_t& ) const; template bool Argument_t::as<bool>( const Argument_t& ) const; template double Argument_t::as<double>( const Argument_t& ) const; // but these six can **NOT** be compiled template int8_t Argument_t::as<int8_t>( const Argument_t& ) const; template uint8_t Argument_t::as<uint8_t>( const Argument_t& ) const; template int16_t Argument_t::as<int16_t>( const Argument_t& ) const; template uint16_t Argument_t::as<uint16_t>( const Argument_t& ) const; template int32_t Argument_t::as<int32_t>( const Argument_t& ) const; template uint32_t Argument_t::as<uint32_t>( const Argument_t& ) const; Compiler error message: /usr/include/c++/9/variant: In instantiation of ‘constexpr const _Tp& std::get(const std::variant<_Types ...>&) [with _Tp = signed char; _Types = {bool, double, int, std::__cxx11::basic_string<char, std::char_traits, std::allocator >}]’: Argument.cpp:57:16: required from ‘T octopus::Argument_t::as(const octopus::Argument_t&) const [with T = signed char]’ Argument.cpp:67:53: required from here /usr/include/c++/9/variant:1078:42: error: static assertion failed: T should occur for exactly once in alternatives Why did I get this? How to resolve it?
I think I found the answer: The type ArgValue_t is a instance of the template std::variant with arguments: bool/double/int/std::string, but NOT with int8_t/uint8_t/int16_t/uint16_t/... as arguments, therefore in the invokations of get(), it only can accept bool/double/int/std::string as template arg. May I complain the message of gcc? At least it may warn me the template-arg of get() is incorrect?
70,081,830
70,083,194
Getting an exception when reading values using BOOST_FOREACH from the JSON array in C++
I am getting the below error when reading the values using BOOST_FOREACH: Unhandled exception at 0x76FCB502 in JSONSampleApp.exe: Microsoft C++ exception: boost::wrapexcept<boost::property_tree::ptree_bad_path> at memory location 0x00CFEB18. Could someone help me how to read values from the array with the below JSON format? #include <string> #include <iostream> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> using namespace std; using boost::property_tree::ptree; int main() { const char* f_strSetting = R"({"Class": [{"Student": {"Name":"John","Course":"C++"}}]})"; boost::property_tree::ptree pt1; std::istringstream l_issJson(f_strSetting); boost::property_tree::read_json(l_issJson, pt1); BOOST_FOREACH(boost::property_tree::ptree::value_type & v, pt1.get_child("Class.Student")) { std::string l_strName; std::string l_strCourse; l_strName = v.second.get <std::string>("Name"); l_strCourse = v.second.get <std::string>("Course"); cout << l_strName << "\n"; cout << l_strCourse << "\n"; } return 0; }
You asked a very similar question yesterday. We told you not to abuse a property tree library to parse JSON. I even anticipated: For more serious code you might want to use type-mapping Here's how you'd expand from that answer to parse the entire array into a vector at once: Live On Coliru #include <boost/json.hpp> #include <boost/json/src.hpp> // for header-only #include <iostream> #include <string> namespace json = boost::json; struct Student { std::string name, course; friend Student tag_invoke(json::value_to_tag<Student>, json::value const& v) { std::cerr << "DEBUG: " << v << "\n"; auto const& s = v.at("Student"); return { value_to<std::string>(s.at("Name")), value_to<std::string>(s.at("Course")), }; } }; using Class = std::vector<Student>; int main() { auto doc = json::parse(R"({ "Class": [ { "Student": { "Name": "John", "Course": "C++" } }, { "Student": { "Name": "Carla", "Course": "Cobol" } } ] })"); auto c = value_to<Class>(doc.at("Class")); for (Student const& s : c) std::cout << "Name: " << s.name << ", Course: " << s.course << "\n"; } Printing Name: John, Course: C++ Name: Carla, Course: Cobol I even threw in a handy debug line in case you need to help figuring out exactly what you get at some point: DEBUG: {"Student":{"Name":"John","Course":"C++"}} DEBUG: {"Student":{"Name":"Carla","Course":"Cobol"}}
70,082,108
70,082,365
How to make a template specialization for integral, floating and char* types without if constexpr?
I need a function void foo(T &t) that will have one implementation for char*, another for std::is_integral_v and yet another for std::is_floating_point types. I don't want to make a constexpr approach because it would create a gigantic function with a lot of branches that are difficult to navigate and understand and scale. I've tried SFINAE but i can't fully understand how it works The code i've written before template<typename T> void foo(T *t); template<> void foo<char *>(char **t) { /* does some logic */ } template<> void foo<int>(int *t) { /* does some logic */ } template<> void foo<float>(float *t) { /* does some logic */ } i want to make an int specialization to also accept all int#_t, uint#_t and other integral types the same i want for my float also accept double types without copy-pasting implementation with different cast i need a single scalable solution with SFINAE or any other technology UPD Given answers looks close to what I want but they are still having issues in my case. Generally speaking, i want to make a generic template function without implementation so that could raise an error during compilation and the other i want to map onto my C-style api. Different types of called function should map in different ways (different implementation). I was happy with full-specialization for each type until I had need to reuse the same implementations for a group of related values like float and double use the same implementations, int8_t, int16_t, int32_t, int64_t, and their unsigned counterparts should use their own implemetation but the same for each one. The main requirements are: not using if-constexpr not having a single place where i need to make changes after adding a new type with its own implementation and i want to make use of explicit template parameters (possibly without deducing because i don't trust it well enough) The api i have is like that: void createString(const char *); void createInt(int); void createFloat(float); void createSomeCustomStuff(CustomStruct); and i want to templatify that on the C++ side with ability to pass const char * as a string literal, uint32_t into createInt, etc like so create<const char *>("hello"); create("world"); create(0ull); create(double(100));
This does the job: // For integral types only: template<typename T> std::enable_if_t<std::is_integral_v<T>> foo(T *t) { cout << "integer" << endl; } // For floating point types only: template<typename T> std::enable_if_t<std::is_floating_point_v<T>> foo(T *t) { cout << "floating point" << endl; } template <typename T> std::enable_if_t<std::is_pointer_v<T>> foo(T *t) { cout << "pointer" << endl; } int main() { long a; double b; foo(&a); foo(&b); const char *c = "test"; foo(&c); return 0; } https://godbolt.org/z/b5fT9PGbv
70,082,344
70,157,161
Initializing an array of trivially_copyable but not default_constructible objects from bytes. Confusion in [intro.object]
We are initializing (large) arrays of trivially_copiable objects from secondary storage, and questions such as this or this leaves us with little confidence in our implemented approach. Below is a minimal example to try to illustrate the "worrying" parts in the code. Please also find it on Godbolt. Example Let's have a trivially_copyable but not default_constructible user type: struct Foo { Foo(double a, double b) : alpha{a}, beta{b} {} double alpha; double beta; }; Trusting cppreference: Objects of trivially-copyable types that are not potentially-overlapping subobjects are the only C++ objects that may be safely copied with std::memcpy or serialized to/from binary files with std::ofstream::write()/std::ifstream::read(). Now, we want to read a binary file into an dynamic array of Foo. Since Foo is not default constructible, we cannot simply: std::unique_ptr<Foo[]> invalid{new Foo[dynamicSize]}; // Error, no default ctor Alternative (A) Using uninitialized unsigned char array as storage. std::unique_ptr<unsigned char[]> storage{ new unsigned char[dynamicSize * sizeof(Foo)] }; input.read(reinterpret_cast<char *>(storage.get()), dynamicSize * sizeof(Foo)); std::cout << reinterpret_cast<Foo *>(storage.get())[index].alpha << "\n"; Is there an UB because object of actual type Foo are never explicitly created in storage? Alternative (B) The storage is explicitly typed as an array of Foo. std::unique_ptr<Foo[]> storage{ static_cast<Foo *>(::operator new[](dynamicSize * sizeof(Foo))) }; input.read(reinterpret_cast<char *>(storage.get()), dynamicSize * sizeof(Foo)); std::cout << storage[index].alpha << "\n"; This alternative was inspired by this post. Yet, is it better defined? It seems there are still no explicit creation of object of type Foo. It is notably getting rid of the reinterpret_cast when accessing the Foo data member (this cast might have violated the Type Aliasing rule). Overall Questions Are any of these alternatives defined by the standard? Are they actually different? If not, is there a correct way to implement this (without first initializing all Foo instances to values that will be discarded immediately after) Is there any difference in undefined behaviours between versions of the C++ standard? (In particular, please see this comment with regard to C++20)
What you're trying to do ultimately is create an array of some type T by memcpying bytes from elsewhere without default constructing the Ts in the array first. Pre-C++20 cannot do this without provoking UB at some point. The problem ultimately comes down to [intro.object]/1, which defines the ways objects get created: An object is created by a definition, by a new-expression, when implicitly changing the active member of a union, or when a temporary object is created ([conv.rval], [class.temporary]). If you have a pointer of type T*, but no T object has been created in that address, you can't just pretend that the pointer points to an actual T. You have to cause that T to come into being, and that requires doing one of the above operations. And the only available one for your purposes is the new-expression, which requires that the T is default constructible. If you want to memcpy into such objects, they must exist first. So you have to create them. And for arrays of such objects, that means they need to be default constructible. So if it is at all possible, you need a (likely defaulted) default constructor. In C++20, certain operations can implicitly create objects (provoking "implicit object creation" or IOC). IOC only works on implicit lifetime types, which for classes: A class S is an implicit-lifetime class if it is an aggregate or has at least one trivial eligible constructor and a trivial, non-deleted destructor. Your class qualifies, as it has a trivial copy constructor (which is "eligible") and a trivial destructor. If you create an array of byte-wise types (unsigned char, std::byte, or char), this is said to "implicitly create objects" in that storage. This property also applies to the memory returned by malloc and operator new. This means that if you do certain kinds of undefined behavior to pointers to that storage, the system will automatically create objects (at the point where the array was created) that would make that behavior well-defined. So if you allocate such storage, cast a pointer to it to a T*, and then start using it as though it pointed to a T, the system will automatically create Ts in that storage, so long as it was appropriately aligned. Therefore, your alternative A works just fine: When you apply [index] to your casted pointer, C++ will retroactively create an array of Foo in that storage. That is, because you used the memory like an array of Foo exists there, C++20 will make an array of Foo exist there, exactly as if you had created it back at the new unsigned char statement. However, alternative B will not work as is. You did not use new[] Foo to create the array, so you cannot use delete[] Foo to delete it. You can still use unique_ptr, but you'll have to create a deleter that explicitly calls operator delete on the pointer: struct mem_delete { template<typename T> void operator(T *ptr) { ::operator delete[](ptr); } }; std::unique_ptr<Foo[], mem_delete> storage{ static_cast<Foo *>(::operator new[](dynamicSize * sizeof(Foo))) }; input.read(reinterpret_cast<char *>(storage.get()), dynamicSize * sizeof(Foo)); std::cout << storage[index].alpha << "\n"; Again, storage[index] creates an array of T as if it were created at the time the memory was allocated.
70,082,906
70,082,950
Why do so many libraries define their own fixed width integers?
Since at least C++11 we got lovely fixed width integers for example in C++'s <cstdint> or in C's <stdint.h> out of the box, (for example std::uint32_t, std::int8_t), so with or without the std:: in front of them and even as macros for minimum widths (INT16_C, UINT32_C and so on). Yet we have do deal with libraries every day, that define their own fixed width integers and you might have seen for example sf::Int32, quint32, boost::uint32_t, Ogre::uint32, ImS32, ... I can go on and on if you want me to. You too know a couple more probably. Sometimes these typedefs (also often macro definitions) may lead to conflicts for example when you want to pass a std fixed width integer to a function from a library expecting a fixed width integer with exactly the same width, but defined differently. The point of fixed width integers is them having a fixed size, which is what we need in many situations as you know. So why would all these libraries go about and typedef exactly the same integers we already have in the C++ standard? Those extra defines are sometimes confusing, redundant and may invade your codebase, which are very bad things. And if they don't have the width and signedness they promise to have, they at least sin against the principle of least astonishment, so what's their point I hereby ask you?
Why do so many libraries define their own fixed width integers? Probably for some of the reasons below: they started before C++11 or C11 (examples: GTK, Qt, libraries internal to GCC, Boost, FLTK, GTKmm, Jsoncpp, Eigen, Dlib, OpenCV, Wt) they want to have readable code, within their own namespace or class (having their own namespace, like Qt does, may improve readability of well written code). they are build-time configurable (e.g. with GNU autoconf). they want to be compilable with old C++ compilers (e.g. some C++03 one) they want to be cross-compilable to cheap embedded microcontrollers whose compiler is not a full C++11 compiler. they may have generic code (or template-s, e.g. in Eigen or Dlib) to perhaps support arbitrary-precision arithmetic (or bignums) perhaps using GMPlib. they want to be somehow provable with Frama-C or DO-178C certified (for embedded critical software systems) they are processor specific (e.g. asmjit which generates machine code at runtime on a few architectures) they might interface to specific hardware or programming languages (Tensorflow, OpenCL, Cuda). they want to be usable from Python or GNU guile. they could be operating-system specific. they add some additional runtime checks, e.g. against division by 0 (or other undefined behavior) or overflow (that the C++ standard cannot require, for performance or historical reasons) they are intended to be easily usable from machine-generated C++ code (e.g. RefPerSys, ANTLR, ...) they are designed to be callable from C code (e.g. libgccjit). etc... Finding other good reasons is left as an exercise to the reader.
70,083,091
70,196,247
How to safely compare std::complex<double> with Zero with some precision Epsilon?
I need to safely check is my complex number a zero (or very similar to it). How can I do it for floating point numbers? Can I use something like: std::complex<double> a; if(std::abs(std::real(a)) <= std::numerical_limits<double>::epsilon() && std::abs(std::imag(a)) <= std::numerical_limits<double>::epsilon()) { //... } I will divide values by a and don't want to get the INF as result.
Have you tried std::fpclassify from <cmath>? if (std::fpclassify(a.real()) == FP_ZERO) {} To check if both the real and imaginary part of a complex are 0: if (a == 0.0) {} As mentioned by @eerorika a long time before I did. An answer you rejected. Floating point precision, rounding, flag raising, subnormal is all implementation-defined (See: [basic.fundamental], [support.limits.general], and ISO C 5.2.4.2.2).
70,083,167
70,084,355
no matching function for call to 'LiquidCrystal::write(String&)'
void printOnLcd(String s){ for (int i =0; i<2; i++){ if( i % 2 == 0){ for(int a=0; a<16; a++){ lcd.setCursor(a,i); lcd.write(s); delay(200); lcd.setCursor(a,i); lcd.write(" "); } } else { for(int a = 0; a<16; a++){ lcd.setCursor(a,i); lcd.write(s); delay(200); lcd.setCursor(a,i); lcd.write(" "); } } } Arduino gives me the problem: no matching function for call to 'LiquidCrystal::write(String&)' Can't I put a string on the screen? what's the problem? I encountered this problem a few days ago and now I don't have a chance to look for a possible solution.
now I don't have a chance to look for a possible solution. Open a webbrowser, enter www.google.com, enter "Arduino LiquidCrystal", click the first hit: https://www.arduino.cc/en/Reference/LiquidCrystal < the Arduino manual btw. Read it! You're trying to use LiquidCrystal.write, so click write and read. Syntax lcd.write(data) data: the character to write to the display So obviously you can only use this function to print a single character. Now check wether there is another function that allows you to write a string. The next function in the list is print Sounds good, let's click that and read. Syntax lcd.print(data) data: the data to print (char, byte, int, long, or string) Hey this allows us to display a string! Try it out lcd.print(s); Alternatively click any of the many examples. Most of them use print.
70,083,616
70,083,687
Create std::string from int8_t array
In some code int8_t[] type is used instead of char[]. int8_t title[256] = {'a', 'e', 'w', 's'}; std::string s(title); // compile error: no corresponding constructor How to properly and safely create a std::string from it? When I will do cout << s; I want that it print aews, as if char[] type was passed to the constructor.
Here you are int8_t title[256] = { 'a', 'e', 'w', 's' }; std::string s( reinterpret_cast<char *>( title ) ); std::cout << s << '\n'; Or you may use also std::string s( reinterpret_cast<char *>( title ), 4 );
70,083,648
70,083,739
Updating an array (passed as parameter) inside a C++ function
I have the following declaration and function call: unsigned int myArray[5] = {0, 0, 0, 0, 0}; ModifyArray(&myArray[0]); The above code cannot be modified, it is given as is. I need to write the implementation for ModifyArray to update myArray to contain 1, 2, 3, 4, 5. I have written it as: void ModifyArray(unsigned int * out_buffer) { unsigned int updatedValues[5] = {0, 0, 0, 0, 0}; updatedValues[0] = 1; updatedValues[1] = 2; updatedValues[2] = 3; updatedValues[3] = 4; updatedValues[4] = 5; *out_buffer = &updatedValues; } This doesn't really seem to work. I have a feeling that I'm not doing the assignment correctly on the last line of code, however I have tried multiple variations, and it still doesn't seem to update just element 0 of the array. What am I doing wrong? Thanks! P.S.: Please note that the scenario is more complex than presented here. I have simplified for readability purposes, but the code should look very similar to this, just the last assignment should be updated to a correct one if possible.
*out_buffer is an unsigned int. &updatedValues is an unsigned int(*)[5] - a pointer to an array of five elements - which you can't assign to an int. You should not assign any arrays (it's impossible), you should modify the contents of the given array: void ModifyArray(unsigned int *out_buffer) { out_buffer[0] = 1; out_buffer[1] = 2; out_buffer[2] = 3; out_buffer[3] = 4; out_buffer[4] = 5; } which you can simplify to void ModifyArray(unsigned int *out_buffer) { for (int i = 0; i < 5; i++) { out_buffer[i] = i+1; } }
70,083,774
70,083,926
Metaprogramming - power-like function
I want to define template which would behave similar to power function a^n a^n = -1 where a < 0 or n < 0 a^0 = 0 (so not exactly as std::pow) otherwise std::pow I have a problem defining the condition for point 1 - I assume this will be a combination of enable_if and some defined constexpr checking whether integer is negative. What I wrote for the 1. point (commented out below) probably does not make sense as it do not compile. I am only starting with metaprogramming, to be honest I do not quite understand it. I would much appreciate if you could provide explanation and/or some resources you found helpful while getting into the topic. #include <iostream> #include <cmath> // std::pow template <int a, int n> struct hc { enum { v = a * hc<a, n - 1>::v }; }; // to break recursion from getting to a^0=0 template <int a> struct hc<a, 1> { enum { v = a }; }; // a^0 = 0 template <int a> struct hc<a, 0> { enum { v = 0 }; }; // a^n=-1 for negative a or n /* template <int i> constexpr bool is_negative = i < 0; // a ^ n = -1, where a < 0 or n < 0 template <int a, int n, typename std::enable_if<is_negative<a> || is_negative<n>>::type> struct hc { enum { v = -1 }; }; */ int main() { // a^0=0 std::cout << hc<0, 0>::v << " -> 0^0=0\n"; std::cout << hc<3, 0>::v << " -> 3^0=0\n"; // a^n=std::pow std::cout << hc<1, 1>::v << " -> 1^1=" << std::pow(1, 1) << '\n'; std::cout << hc<2, 2>::v << " -> 2^2=" << std::pow(2, 2) << '\n'; std::cout << hc<0, 2>::v << " -> 0^2=" << std::pow(0, 2) << '\n'; std::cout << hc<3, 2>::v << " -> 3^2=" << std::pow(3, 2) << '\n'; std::cout << hc<3, 7>::v << " -> 3^7=" << std::pow(3, 7) << '\n'; // a^n=-1 for negative a or n std::cout << hc<-3, 7>::v << " -> -3^7=-1\n"; std::cout << hc<3, -7>::v << " -> 3^-7=-1\n"; std::cout << hc<0, -7>::v << " -> 0^7=-1\n"; std::cout << hc<-3, 0>::v << " -> -3^0=-1\n"; }
There are several ways Simpler IMO, would be constexpr function constexpr int hc_impl(int a, int n) { if (a < 0 || n < 0) return -1; if (n == 0) return 0; int res = 1; for (int i = 0; i != n; ++n) { res *= a; } return res; }; template <int a, int n> struct hc { constexpr int v = hc_impl(a, n); }; The old way with struct, you might add an extra parameter for dispatch, something like: template <int a, int n, bool b = (a < 0 || n < 0)> struct hc; template <int a, int n> struct hc<a, n, true> { enum { v = -1 }; }; template <int a> struct hc<a, 1, true> { enum { v = -1 }; }; template <int a> struct hc<a, 0, true> { enum { v = -1 }; }; template <int a, int n> struct hc<a, n, false> { enum { v = a * hc<a, n - 1>::v }; }; // to break recursion from getting to a^0=0 template <int a> struct hc<a, 1, false> { enum { v = a }; }; // a^0 = 0 template <int a> struct hc<a, 0, false> { enum { v = 0 }; };
70,083,996
70,084,044
Variable is not declared in the scope error in c++?
I'm new bee in c++! I'm to iterate over integers using the for loop, but getting the error error: ‘frame’ was not declared in this scope auto position_array = (*frame)[i][j]; But as you can see in the code below it is declared auto ds = data_file.open_dataset(argv[1]); // auto frame = data_file.read_frame(ds, 0); // inside the loop for (int i = 0; i < 3; ++i) auto frame = data_file.read_frame(ds, i); for (size_t i = 0; i < nsamples; ++i) { for (size_t j = 0; j <= 2; ++j) { // j<=2 assign all columns auto position_array = (*frame)[i][j]; } corr.sample(frame); } corr.finalise(); It works fine if I use the commented second line. But now I want to iterate over the second variable of data_file.read_frame(ds, i) and the error comes up! What am I doing wrong? Do I need to declare int frame = 0; before the for loop? For the brevity I just post the code with the error, incase some one need to see the whole code you're welcome!!
Sounds like you need a nested for loop. Using for (int i = 0; i < 3; ++i) { auto frame = data_file.read_frame(ds, i); for (size_t j = 0; j < nsamples; ++j) { for (size_t k = 0; k <= 2; ++k) { // j<=2 assign all columns auto position_array = (*frame)[i][j]; } corr.sample(frame); } } Lets you get each frame, and then process each element of each frame.
70,086,124
70,086,373
Copying parent nodes
I'm trying to write a copy-constructor that is only allowed to copy from a parent node. Since I'm constrained to using C++17, I would like to accomplish this by imitating concepts/require clauses with the use of the std::enable_if type trait (if there is a better way to accomplish this, please let me know). #include <functional> #include <iostream> template<int N> struct node { node() { std::cout << "def-ctor N=" << N << "\n"; } node(node const&) { std::cout << "cpy-ctor N=" << N << "\n"; } template<int O // , typename = std::enable_if_t<(N > O)> > node(node<O> const&) { std::cout << "cpy-ctor N=" << N << " O=" << O << " "; // static_assert(N > O); // fails due to 3 > 4 if constexpr (N > O) std::cout << "N > O\n"; if constexpr (N == O) std::cout << "N == O\n"; if constexpr (N < O) std::cout << "N < O\n"; } }; node<3> n3; auto n4 = node<4>{n3}; // template<int N> using f = std::function<void(node<N> const&)>; auto f3 = f<3>{[](auto const&){}}; auto f4 = f<4>{f3}; // auto main() -> int {} The code above prints the expected output: cpy-ctor N=4 O=3 N > O But (to my surprise) when uncommenting the static-assert, the compilation fails stating that 3 sure can't be greater than 4. Which I can't really argue with, I guess. I'm suspecting that some sort of copy-elision shenanigans is taking place here. Why under the hood a copy of the reversal is required, is beyond me. So my question is: What is going on here? Why can't I constrain this copy-constructor to only accepts parent nodes? And how do I remedy this? Live example.
Your code and SFINAE usage for node(node<O> const&) (currently commented) look OK to me. If I uncomment the static_assert, my local g++ 11.2.0 by msys2 yields the following error: a.cpp: In instantiation of 'node<N>::node(const node<O>&) [with int O = 4; int N = 3]': C:/tools/msys64/mingw64/include/c++/11.2.0/bits/invoke.h:61:36: required from 'constexpr _Res std::__invoke_impl(std::__invoke_other, _Fn&&, _Args&& ...) [with _Res = void; _Fn = std::function<void(const node<3>&)>&; _Args = {const node<4>&}]' C:/tools/msys64/mingw64/include/c++/11.2.0/bits/invoke.h:111:28: required from 'constexpr std::enable_if_t<is_invocable_r_v<_Res, _Callable, _Args ...>, _Res> std::__invoke_r(_Callable&&, _Args&& ...) [with _Res = void; _Callable = std::function<void(const node<3>&)>&; _Args = {const node<4>&}; std::enable_if_t<is_invocable_r_v<_Res, _Callable, _Args ...>, _Res> = void]' C:/tools/msys64/mingw64/include/c++/11.2.0/bits/std_function.h:291:30: required from 'static _Res std::_Function_handler<_Res(_ArgTypes ...), _Functor>::_M_invoke(const std::_Any_data&, _ArgTypes&& ...) [with _Res = void; _Functor = std::function<void(const node<3>&)>; _ArgTypes = {const node<4>&}]' C:/tools/msys64/mingw64/include/c++/11.2.0/bits/std_function.h:422:21: required from 'std::function<_Res(_ArgTypes ...)>::function(_Functor) [with _Functor = std::function<void(const node<3>&)>; <template-parameter-2-2> = void; <template-parameter-2-3> = void; _Res = void; _ArgTypes = {const node<4>&}]' a.cpp:35:18: required from here a.cpp:19:25: error: static assertion failed 19 | static_assert(N > O); // fails due to 3 > 4 | ~~^~~ a.cpp:19:25: note: '(3 > 4)' evaluates to false Let's unpack. It clearly wants to construct a node<3> from an existing node<4> somewhere. This somewhere is required by the line auto f4 = f<4>{f3}; This line constructs a std::function<void(node<4> const&)> from an existing std::function<void(node<3> const&)> The error happens in a helper function called __invoke_impl How does one convert a function taking node<3> to a function taking node<4>? The only reasonable way is: void f4(node<4> const &arg) { return f3(arg); // f3(node<3> const &) } Actually, that's more or less what __invoke_impl does. Note that implicit conversion from node<4> to node<3> is required here. Hence, the program has to construct a node<3> object from a node<4> object. But static_assert prohibits that. You can double-check this by replacing static_assert with either debug output or debugger breakpoint and seeing when it's actually called.
70,086,144
70,086,244
Template type inference using std::views
I am coming somewhat belatedly to Functional Programming, and getting my head around ranges/views. I'm using MSVC19 and compiling for C++ 20. I'm using std::views::transform and the compiler doesn't seem to be inferring type as I might naively hope. Here's a small example, which simply takes a vector of strings and computes their length: #include <vector> #include <iostream> #include <ranges> template<typename E> auto length(const E& s) { std::cout << "Templated length()\n"; return static_cast<int>(s.length()); } template<typename E> auto getLengths(const std::vector<E>& v) { return v | std::views::transform(length<E>); } int main() { std::vector<std::string> vec = { "Larry","Curly","Moe" }; for (int i : getLengths(vec)) { std::cout << i << "\n"; } return 0; } with the output: Templated length() 5 Templated length() 5 Templated length() 3 My question is why does changing the code in this line (dropping the <E>): return v | std::views::transform(length); give me an armful of errors, starting with: Error C2672 'operator __surrogate_func': no matching overloaded function found ? Why doesn't the compiler infer that the type is std::string? If I replace the templates with a non-templated function: auto length(const std::string& s) -> int { std::cout << "Specialized length()\n"; return static_cast<int>(s.length()); } The code compiles and runs, so clearly without the template, the compiler finds a match for the particular type I am using.
This has nothing to do with views. You can reduce the problem to: template <typename T> int length(T const& x) { return x.length(); } template <typename F> void do_something(F&& f) { // in theory use f to call something } void stuff() { do_something(length); // error } C++ doesn't really do type inference. When you have do_something(length), we need to pick which length we're talking about right there. And we can't do that, so it's an error. There's no way for do_something to say "I want the instantiation of the function template that will be called with a std::string - it's entirely up to the caller to give do_something the right thing. The same is true in the original example. length<E> is a concrete function. length is not something that you can just pass in. The typical approach is to delay instantiation by wrapping your function template in a lambda: void stuff() { do_something([](auto const& e) { return length(e); }); // ok } Now, this works - because a lambda is an expression that has a type that can be deduced by do_something, while just length is not. And we don't have to manually provide the template parameter, which is error prone. We can generalize this with a macro: #define FWD(arg) static_cast<decltype(arg)&&>(arg) #define LIFT(name) [&](auto&&... args) -> decltype(name(FWD(args)...)) { return name(FWD(args)...); } void stuff() { do_something(LIFT(length)); } Which avoids some extra typing and probably makes the intent a little clearer.
70,086,227
70,086,336
C++ ofstream Binary Mode - Written file still looks like plain text
I have an assignment that wants plain text data to be read in from a file, and then outputted to a separate binary file. With that being said, I expect to see that the contents of the binary file not to be intelligible for human reading. However, when I open the binary file the contents are still appearing as plain text. I am setting the mode like this _file.open(OUTFILE, std::ios::binary). I can't seem to figure out what I'm missing. I've followed other examples with different methods of implementation, but there's obviously something I'm missing. For the purpose of posting, I created a slimmed down test case to demonstrate what I'm attempting. Thanks in advance, help is greatly appreciated! Input File: test.txt Hello World main.cpp #include <iostream> #include <fstream> using namespace std; #define INFILE "test.txt" #define OUTFILE "binary-output.dat" int main(int argc, char* argv[]) { char* text = nullptr; int nbytes = 0; // open text file fstream input(INFILE, std::ios::in); if (!input) { throw "\n***Failed to open file " + string(INFILE) + " ***\n"; } // copy from file into memory input.seekg(0, std::ios::end); nbytes = (int)input.tellg() + 1; text = new char[nbytes]; input.seekg(ios::beg); int i = 0; input >> noskipws; while (input.good()) { input >> text[i++]; } text[nbytes - 1] = '\0'; cout << "\n" << nbytes - 1 << " bytes copied from file " << INFILE << " into memory (null byte added)\n"; if (!text) { throw "\n***No data stored***\n"; } else { // open binary file for writing ofstream _file; _file.open(OUTFILE, std::ios::binary); if (!_file.is_open()) { throw "\n***Failed to open file***\n"; } else { // write data into the binary file and close the file for (size_t i = 0U; i <= strlen(text); ++i) { _file << text[i]; } _file.close(); } } }
As stated here, std::ios::binary isn't actually going to write binary for you. Basically, it's the same as std::ios::out except things like \n aren't converted to line breaks. You can convert text to binary by using <bitset>, like this: #include <iostream> #include <vector> #include <bitset> int main() { std::string str = "String in plain text"; std::vector<std::bitset<8>> binary; // A vector of binaries for (unsigned long i = 0; i < str.length(); ++i) { std::bitset<8> bs4(str[i]); binary.push_back(bs4); } return 0; } And then write to your file.
70,086,350
70,087,313
Unexpected output in c++ classes and copying objects to another object
I have a robot class that has a pointer vector of ints (to store work done history), however when I copy an object of one robot to another and the first robot goes out of scope, and then I print the history of the robot it gives me a massive list of random numbers. I ve tried making my own copy constructor and setting _history to new objects _history value by value, but gives same response. ROBOT.h # pragma once #include <iostream> #include <vector> class Robot{ private: int workUnit = 0; std::vector<int>* _history; // pointer to vector of ints (NOT a vector of int pointers) public: Robot() : name("DEFAULT") {_history = new std::vector<int>();}; Robot(const std::string& name) : name(name){_history = new std::vector<int>();}; ~Robot(){std::cout << name << ": Goodbye!" << std::endl; delete _history;}; std::string whoAmI() const {return name;}; void setName(const std::string& name){this->name = name;}; void work(); void printWork() const; std::vector<int>* getHistory() const { return _history; }; protected: std::string name; }; ROBOT.cpp # include "Robot.h" void Robot::work(){ workUnit++; _history -> push_back(workUnit); std::cout << name << " is working. > " << workUnit <<"\n"; } void Robot::printWork() const { std::cout << "Robot " << name << " has done the following work: "; for(const int& record : *_history){ std::cout << record << " "; } std::cout << std::endl; } MAIN #include <iostream> #include "Robot.h" int main(){ Robot r2("Task5 Robo"); { Robot r1("r1"); r1.whoAmI(); r1.work(); r1.work(); r1.printWork(); std::cout << "assign r1 to r2..." << std::endl; r2 = r1; r2.setName("r2"); r2.whoAmI(); r2.printWork(); } r2.whoAmI(); r2.printWork(); std::cout << "end of example code..." << std::endl; return 0; } OUTPUT iam getting : r1 is working. > 1 r1 is working. > 2 Robot r1 has done the following work: 1 2 assign r1 to r2... Robot r2 has done the following work: 1 2 r1: Goodbye! Robot r2 has done the following work: 7087248 0 6975376 0 0 0 -1124073283 19523 7087248 0 6975408 0 7087248 0 6947152 0 0 -1 -1174404934 19523 7087248 0 6947152 0 1701603654 1917803635 1701602145 1986087516 1634360417 (and lots more random numbers)
Here's one example of how to implement the five special member functions in the rule of 5. First, your default constructor and the constructor taking a string could be combined so that the default constructor delegates to the one taking a string: Robot(const std::string& name) : _history(new std::vector<int>()), name(name) {}; Robot() : Robot("DEFAULT") {} // Delegate Here's the rule of five: // --- rule of five --- Robot(const Robot& rhs) : // copy constructor workUnit(rhs.workUnit), _history(new std::vector<int>(*rhs._history)), name(rhs.name) {} Robot(Robot& rhs) noexcept : // move constructor workUnit(rhs.workUnit), // use exchange to steal pointer and replace with nullptr: _history(std::exchange(rhs._history, nullptr)), name(std::move(rhs.name)) {} Robot& operator=(const Robot& rhs) { // copy assignment operator workUnit = rhs.workUnit; *_history = *rhs._history; // use vector's copy assignment operator name = rhs.name; return *this; } Robot& operator=(Robot&& rhs) noexcept { // move assignment operator workUnit = rhs.workUnit; // swap pointers, let rhs destroy *this old pointer: std::swap(_history, rhs._history); name = std::move(rhs.name); return *this; } ~Robot() { // destructor std::cout << name << ": Goodbye!\n"; delete _history; }; // --- rule of five end --- When you are dealing with raw owning pointers, you could use a std::unique_ptr to get some of this for free though. Instead of std::vector<int>* _history; you make it: std::unique_ptr<std::vector<int>> _history; So the class becomes: Robot(const std::string& name) : _history(std::make_unique<std::vector<int>>()), name(name) {}; Robot() : Robot("DEFAULT") {} // Delegate And the rule of five becomes a little simpler: // --- rule of five --- Robot(const Robot& rhs) : // copy constructor workUnit(rhs.workUnit), _history(std::make_unique<std::vector<int>>(*rhs._history)), name(rhs.name) {} // move constructor handled by unique_ptr, just default it: Robot(Robot& rhs) noexcept = default; Robot& operator=(const Robot& rhs) { // copy assignment operator workUnit = rhs.workUnit; *_history = *rhs._history; name = rhs.name; return *this; } // move assignment operator handled by unique_ptr, just default it: Robot& operator=(Robot&& rhs) noexcept = default; ~Robot() { // destructor std::cout << name << ": Goodbye!\n"; // delete _history; // no delete needed, unique_ptr does it }; // --- rule of five end --- You may also want to return your _history by reference from getHistory(). The below works for both the raw pointer and the unique_ptr version and gives a nicer interface to your class: const std::vector<int>& getHistory() const { return *_history; }; std::vector<int>& getHistory() { return *_history; };
70,086,762
70,087,190
byte-wise operation on multibyte native types idomatically
In C I would, without hesitation, write the following: uint32_t value = 0xDEADBEEF; uint8_t *pValue = &value; for (size_t i = 0; i < sizeof(value); i++) { pValue[i] ^= 0xAA; } But in C++17 I'm faced with two constraints from my code scanner Use "std::byte" for byte-oriented memory access. Replace "reinterpret_cast" with a safer cast. The latter coming into effect when my C lizard brain inevitably tries to force a typecast. So how exactly do I idiomatically accomplish what I'm trying to do? In my googling I ran past memcpy in and out of the data of a vector but that feels goofy.
As noted at https://en.cppreference.com/w/cpp/language/ Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true: ... AliasedType is std::byte (since C++17), char, or unsigned char: this permits examination of the object representation of any object as an array of bytes. So, reinterpret_cast is an eldritch abomination but won't give you any error no matter what type pointer you give it, except that these 3 ways of naming bytes is allowed. So a "safer" cast would be a function that specifically only gives you an array-of-bytes view of an arbitrary object, rather than exposing the reinterpret_cast and making the reviewer check that the type used is allowed and it's used in the idiomatic way. Meanwhile, you need to write an old-fashioned counting for loop and index the pointer to get to each element. You can have the "safer" (more specific, more targeted) feature take care of that too, by providing a result that is a proper range of bytes, not just a pointer to the beginning. The easiest way is to use std::span. Just off the top of my head: template <typename T> auto raw_byte_view (T& original) { constexpr auto sz = sizeof(T); auto& arr = reinterpret_cast<std::byte(&)[sz]>(&original); return std::span<std::byte,sz>(arr); } I've not tried that, but it appears that to get the compile-time size version of the span, you have to give in an array reference, not separate pointer,length arguments. You can cast to reference to an array, and it includes the size as part of the type. discussion Returning span as a wrapper around the array reference is nicer than trying to deal with the array reference itself, because it's too easy to mishandle the array reference as it has to be kept as a reference. You could accomplish the same thing with a pointer to a std::array which unlike the C array works like any normal type. But we want reference semantics — the returned thing is a reference into an existing object, not a thing to be copied. So it's better to use a type that represents this indirection rather than stacking another pointer on top of a value-based type. end discussion   Now you can write: for (auto& x : raw_byte_view(value)) { x ^= std::byte{0xAA}; }
70,087,104
70,087,160
In C++, how to express the largest possible value of a type via its variable name?
Assuming there is a declaration in a header file you don't control that states something like: static const uint16 MaxValue = 0xffff; // the type could be anything, static or not Inside a file that includes the above you have code like this: int some_function(uint16 n) { if (n > MaxValue) { n = MaxValue; } do_something(n); ... } The compiler will warn that the if statement is always false because n cannot be larger than 0xffff. One way might be to remove the code. But then if later someone wants to change the value of MaxValue to something lower you have just introduced a bug. Two questions: Is there any C++ templates or techniques that can be used to make sure the code is removed when not needed (because MaxValue is 0xfff) and included (when MaxValue is not 0xffff)? Assuming you want to explicitly write an extra check to see if MaxValue is equal to the limit the type can hold, is there a portable technique to use to identify the maximum value for the type of MaxValue that would work if later the code of MaxValue is changed? Meaning: how can I infer the maximum value of type via its variable name? I would prefer not using the limits.h or <limit> constants like USHRT_MAX, or event not using std::numeric_limits<uint16> explicitly. Can something like std:numeric_limits<MaxValue> be used?
typeid results in a type_info const & rather than the type of variable, use std::numeric_limits<decltype(variable)>::max() instead.
70,087,348
70,087,968
How to create if statement from curl command output (c++)
I am trying to get the output of the curl command to work inside of an if statement I am new to C++ and don't know how I could do this. int curlreq; curlreq = system("curl localhost/file.txt"); string curlreqstring = to_string(curlreq); if ((krxcrlstr.find("hello") != string::npos) ) { cout << "hello\n"; } else if (curlreqstring.find("hello2") != string::npos) { cout << "hello2\n"; } I am doing this on Windows. The project is a console app C++ 20 All the above code is doing, is printing what the curl response is, but I need that as a variable to then determine what the program should do. As you see I am getting the contents of a file from localhost, the file itself has a singular line.
std::system returns an int with an implementation-defined value. On many platforms, 0 means success and anything else means some sort of failure. I'm making this assumption in the below example. My advice is to use libcurl which is what the curl command is using internally. With a little setup you can make your program perform curl actions and receive what you get back into your program. If you do not have access to libcurl or find it a bit hard to get started with, you could wrap your system command in a function which performs the curl command but directs the output to a temporary file which you read after curl is done. Example: #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <iterator> #include <string> // a simple class to remove the temporary file after use struct file_to_remove { // remove "filename" when the object is destroyed ~file_to_remove() { std::remove(filename.c_str()); } const std::string& str() const { return filename; } const std::string filename; }; // A function to "curl": std::string Curl(std::string options_plus_url) { // An instance to remove the temporary file after use. // Place it where you have permission to create files: file_to_remove tempfile{"tmpfile"}; // build the command line // -s to make curl silent // -o to save to a file options_plus_url = "curl -so " + tempfile.str() + " " + options_plus_url; // perfom the system() command: int rv = std::system(options_plus_url.c_str()); // not 0 is a common return value to indicate problems: if(rv != 0) throw std::runtime_error("bad curl"); // open the file for reading std::ifstream ifs(tempfile.str()); // throw if it didn't open ok: if(!ifs) throw std::runtime_error(std::strerror(errno)); // put the whole file in the returned string: return {std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>{}}; } // tmpfile is removed when file_to_remove goes out of scope With the above Curl function you can perform curl commands and get the response as a std::string which you can then use in your if statements etc. Example: int main(int argc, char* argv[]) { if(argc < 2) return 1; // must get an URL as argument try { std::string response = Curl(argv[1]); std::cout << response << '\n'; } catch(const std::exception& ex) { std::cout << "Exception: " << ex.what() << '\n'; } }