question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,402,542
69,402,573
Using #define for text replacement in the code
Apparently, I can set #define LIMIT 50 to say that LIMIT, wherever it occurs in the code, is replaced by 50. Is it possible to use #define ui "unsigned int" to define my variables in such a way? ui foo = 42 ui bar = 99
Using the preprocessor for replacement is not recommended and can lead to unexpected problems. For your use-case there is the typedef or using statement: Use: using ui = unsigned int; Or: typedef unsigned int ui;
69,403,464
69,403,797
C++ Qt : push_back doesn't work correctly
I'm trying to write a code which reads .stl files, and gathers the informations in an std::vector<Triangle*>triangles. When I'm using push_back, it erases all the previous values in triangles and replaces all of them by the last value I'm trying to push_back. Here is my code : Mesh.h: struct Triangle { Node* nodes[3]; double normal[3]; }; struct Node { double coo[3]; }; public: std::vector<Triangle*> triangles; Mesh.cpp void dm::Mesh::loadSTL(const QString p_file) //----------------------------------------------------------------------------- { //Open the STL file QFile file(p_file); //READ FILE file.open(QIODevice::ReadOnly | QIODevice::Text); Node *vn = new Node; Node *vertex1 = new Node; Node *vertex2 = new Node; Node *vertex3 = new Node; Triangle *triangle = new Triangle; *triangle->nodes = new Node; QString line; QTextStream in(&file); line = in.readLine(); // solid while(true) { line = in.readLine().trimmed(); //facet or endsolid if(line.trimmed().startsWith("endsolid")) { break; } *vn = getCoordinateFromString(line); line = in.readLine(); //outer loop line = in.readLine().trimmed(); //vertex 1 *vertex1 = getCoordinateFromString(line); line = in.readLine().trimmed(); //vertex 2 *vertex2 = getCoordinateFromString(line); line = in.readLine().trimmed(); //vertex 3 *vertex3 = getCoordinateFromString(line); line = in.readLine(); //endloop line = in.readLine(); //endfacet triangle->nodes[0] = vertex1; triangle->nodes[1] = vertex2; triangle->nodes[2] = vertex3; for(int i = 0; i<3 ; i++){ triangle->normal[i] = vn->coo[i]; } triangles.push_back(triangle); } file.close(); }
The problem is that you create the triangle once and keep pushing the pointer to that triangle into the vector. Meaning any change to the pointer will affect all items in the vector (because they all point to the same instance). You should move the construction of the triangle in the while loop (Triangle *triangle = new Triangle;) This makes sure you create a new pointer every time.
69,403,564
69,406,769
Unable to create image bitmap c++
My goal is to analyse image by pixels (to determine color). I want to create bitmap in C++ from image path: string path = currImg.path; cout << path << " " << endl; Then I do some type changes which needed because Bitmap constructor does not accept simple string type: wstring path_wstr = wstring(path.begin(), path.end()); const wchar_t* path_wchar_t = path_wstr.c_str(); And finally construct Bitmap: Bitmap* img = new Bitmap(path_wchar_t); In debugging mode I see that Bitmap is just null: How can I consstruct Bitmap to scan photo by pixel to know each pixel's color?
Either Gdiplus::GdiplusStartup is not called, and the function fails. Or filename doesn't exist and the function fails. Either way img is NULL. Wrong filename is likely in above code, because of the wrong UTF16 conversion. Raw string to wstring copy can work only if the source is ASCII. This is very likely to fail on non-English systems (it can easily fail even on English systems). Use MultiByteToWideChar instead. Ideally, use UTF16 to start with (though it's a bit difficult in a console program) int main() { Gdiplus::GdiplusStartupInput tmp; ULONG_PTR token; Gdiplus::GdiplusStartup(&token, &tmp, NULL); test_gdi(); Gdiplus::GdiplusShutdown(token); return 0; } Test to make sure the function succeeded before going further. void test_gdi() { std::string str = "c:\\path\\filename.bmp"; int size = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, 0, 0); std::wstring u16(size, 0); MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &u16[0], size); Gdiplus::Bitmap* bmp = new Gdiplus::Bitmap(u16.c_str()); if (!bmp) return; //print error int w = bmp->GetWidth(); int h = bmp->GetHeight(); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { Gdiplus::Color clr; bmp->GetPixel(x, y, &clr); auto red = clr.GetR(); auto grn = clr.GetG(); auto blu = clr.GetB(); } delete bmp; }
69,403,575
69,403,889
Why can't we use square brackets in the code below?
vector<int> mergeKSortedArrays(vector<vector<int>*> input) { vector<int> ans; //min priority queue priority_queue<int, vector<int>, greater<int>> pq; for(int i = 0; i < input.size(); i++){ for(int j = 0; j < input[i] -> size(); j++){ pq.push(input[i][j]); //THIS LINE } } while(!pq.empty()){ ans.push_back(pq.top()); pq.pop(); } return ans; } The main function that calls this function mergeKSortedArrays int main() { int k; cin >> k; vector<vector<int> *> input; for (int j = 1; j <= k; j++) { int size; cin >> size; vector<int> *current = new vector<int>; for (int i = 0; i < size; i++) { int a; cin >> a; current->push_back(a); } input.push_back(current); } vector<int> output = mergeKSortedArrays(input); for (int i = 0; i < output.size(); i++) { cout << output[i] << " "; } return 0; } Can anyone tell why using input[i][j] inside the first loop giving an error? What i know of how square brackets work is that it just goes to the address and dereferences. So I don't see why using square brackets will be a problem. Input[i] takes me to the vector pointer and then Input[i][j] takes me to the address of that vector and dereference. Like input[i][j] =*(address of the vector + j). One more thing guys, i'm able to do input[i] -> at(j). It compiles without a problem. But isn't isn't input[i][j] same as input[i] -> at(j) unless i'm doing an illegal access of the memory.
With this declaration: vector<vector<int>*> input; input is not a vector of int vectors but it's a vector of pointers to int vectors. Therefore you need this: (*input[i])[j] input[i] is a pointer to vector<int> *input[i] is a vector<int> (*input[i])[j] is an int This being said, you should not use pointers in the first place but simply use a vector<vector<int>> (vector of int vectors). Then you can use input[i][j]. Complete code: #include <iostream> #include <vector> #include <queue> using namespace std; vector<int> mergeKSortedArrays(vector<vector<int>> input) { vector<int> ans; //min priority queue priority_queue<int, vector<int>, greater<int>> pq; for (int i = 0; i < input.size(); i++) { for (int j = 0; j < input[i].size(); j++) { pq.push(input[i][j]); //THIS LINE } } while (!pq.empty()) { ans.push_back(pq.top()); pq.pop(); } return ans; } int main() { int k; cin >> k; vector<vector<int>> input; for (int j = 1; j <= k; j++) { int size; cin >> size; vector<int> current; for (int i = 0; i < size; i++) { int a; cin >> a; current.push_back(a); } input.push_back(current); } vector<int> output = mergeKSortedArrays(input); for (int i = 0; i < output.size(); i++) { cout << output[i] << " "; } return 0; } NB: This code compiles, but I didn't check if it actually works as intended by you. Bonus: The signature of mergeKSortedArrays should be vector<int> mergeKSortedArrays(const vector<vector<int>> & input)` this will avoid an unnecessary copy of the vector upon calling mergeKSortedArrays.
69,403,853
69,448,204
Using C++14 with AVR-GCC (Arduino Uno)
I'm trying try get my Arduino code to compile with -std=c++14 instead of the default -std=gnu++11. To this end, I added to my platformio.ini: build_flags = -std=c++14 build_unflags = -std=gnu++11 However, when I then try to compile, I get the following linker errors: <artificial>:(.text+0x20a4): undefined reference to `operator delete(void*, unsigned int)' (multiple times) I seems that the delete operator is missing. I found some threads about adding it manually, which appears to be used to be necessary in the past with Arduino. However, this shouldn't be the case anymore, and with the default gnu++11 I do not have this issue. Why is this missing with c++14 (and later standards and their GNU extensions) and not with the default gnu++11? I only have this problem with avr-gcc (for Arduino Uno), with arm-none-eabi-g++ (for Teensy), this problem does not occur.
After some searching around it turns out that C++ from C++14 on defines two additional delete operators: void operator delete ( void* ptr, std::size_t sz ) noexcept; (5) (since C++14) void operator delete[]( void* ptr, std::size_t sz ) noexcept; (6) (since C++14) 5-6) Called instead of (1-2) if a user-defined replacement is provided, except that it's unspecified whether (1-2) or (5-6) is called when deleting objects of incomplete type and arrays of non-class and trivially-destructible class types. A memory allocator can use the given size to be more efficient. The standard library implementations are identical to (1-2). (from https://en.cppreference.com/w/cpp/memory/new/operator_delete) Looking at ArduinoCore-avr's source, these are actually present, and defined as follows: #if __cplusplus >= 201402L void operator delete(void* ptr, std::size_t size) noexcept { operator delete(ptr); } void operator delete[](void * ptr, std::size_t size) noexcept { operator delete[](ptr); } #endif // __cplusplus >= 201402L However, it seems like there hasn't been a new release of ArduinoCore-avr in a while, and the last release predates this (relatively recent) code. After adding the above definition to my code myself, it compiles :)
69,403,895
69,403,930
Calling template function inside function C++
I have similar case but more complex. I am trying to call a template function inside a normal function but I can't compile... #include <iostream> using namespace std; template<class T> void ioo(T& x) { std::cout << x << "\n"; } template<class T, class ReadFunc> void f(T&& param, ReadFunc func) { func(param); } int main() { int x = 1; std::string y = "something"; f(x, &::ioo); }
ioo is a function template, not a function, so you can't take its address. This would however work since it instantiates the function void ioo<int>(int&): f(x, &ioo<decltype(x)>); and as noted by Jarod42 in the comments, you could make it into a lambda: f(x, [](auto& arg){ioo(arg);});
69,403,902
69,405,220
Print only at the end of all the input c++
I want to add values to a binary search tree taking input from user until -1 is encountered. It must then continue to read numbers and delete from the tree until I encounter a -1 again. After taking both inputs it should print the pre-order, in-order and post-order traversals after each number was removed. My code below is printing the traversals in between the taking of input of the values which will be removed and not at the end Input: //These values will be added to tree 50 30 35 61 24 58 62 32 -1 //These values will be removed from tree 30 24 32 -1 Expected Output: 50 32 24 35 61 58 62 24 32 35 50 58 61 62 24 35 32 58 62 61 50 50 32 35 61 58 62 32 35 50 58 61 62 35 32 58 62 61 50 50 35 61 58 62 35 50 58 61 62 35 58 62 61 50 My input and output 50 30 35 61 24 58 62 32 -1 30 50 32 24 35 61 58 62 24 32 35 50 58 61 62 24 35 32 58 62 61 50 24 50 32 35 61 58 62 32 35 50 58 61 62 35 32 58 62 61 50 32 50 35 61 58 62 35 50 58 61 62 35 58 62 61 50 -1 int main() { Node *root = NULL; int num; cin >> num; while (num != -1) { root = insert(root, num); cin >> num; } cin >> num; while (num != -1) { root = deleteNode(root, num); // delete from tree preorder(root); // print preorder cout << endl; inorder(root); // print inorder cout << endl; postorder(root); //print postorder cout << endl; cin >> num; } return 0; }
Yes, your code writes the traversals after it reads each number to be deleted. I gather you want the writing to be done after all the reading is done. As commenters say, there's two ways. Either you can buffer the input, or you can buffer the output. The input buffer is a bit simpler, so I'll demonstrate that way. The first thing to note is that you don't know how big the buffer will need to be until you get to the -1. So you could either allocate a "big enough" buffer and hope for the best, or use an expanding buffer. In C++, expanding buffers are easy - they're called vector's. //Get access to C++'s standard vector library #include <vector> int main() { Node *root = NULL; int num; cin >> num; while (num != -1) { root = insert(root, num); cin >> num; } //create the inputBuffer, initially empty. std::vector<int> inputBuffer; cin >> num; while (num != -1) { //Instead of producing the output straight away, just buffer the input num. inputBuffer.push_back(num); cin >> num; } //Now we've buffered all the input, get going on producing the output. for(int i=0; i<inputBuffer.size(); i++) { int num = inputBuffer[i]; root = deleteNode(root, num); // delete from tree preorder(root); // print preorder cout << endl; inorder(root); // print inorder cout << endl; postorder(root); //print postorder cout << endl; } return 0; }
69,404,038
69,404,585
Does .NET initialize struct padding to zero?
When .NET initializes a struct to zero, does it zero out the padding as well? I ask because I'm wondering about the limitations of doing bitwise comparisons on unmanaged structs. Note how CanCompareBits not only checks that the type is unmanaged (!mt->ContainsPointers()), but also that it is tightly packed (!mt=>IsNotTightlyPacked). Mind the double negative on the latter: it requires that the type is tightly packed. // Return true if the valuetype does not contain pointer and is tightly packed FCIMPL1(FC_BOOL_RET, ValueTypeHelper::CanCompareBits, Object* obj) { WRAPPER_CONTRACT; STATIC_CONTRACT_SO_TOLERANT; _ASSERTE(obj != NULL); MethodTable* mt = obj->GetMethodTable(); FC_RETURN_BOOL(!mt->ContainsPointers() && !mt->IsNotTightlyPacked()); } FCIMPLEND This code seems to imply that structs with padding are unsuitable for bitwise comparisons. When is this true, and why? My assumption is that this has to do with padding initialization, but perhaps there is more going on.
Struct padding is explicitly documented as being indeterminant. From https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code: For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of the struct. The contents of the bits used as padding are indeterminate. This matches the documentation for C/C++ structs, which I think is no coincidence. The ISO C99 standard states: When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values." So to answer your questions: "When .NET initializes a struct to zero, does it zero out the padding as well?" - Undefined, so you cannot rely on it. "When is this true?" - Always. "Why" - If that means "why is the padding not initialised", I can only surmise: Probably for performance reasons, and for compatibility with C/C++ for Interop calls.
69,404,394
69,404,524
C++ weird instantiation of struct
I have a struct in a header file as shown here struct GraphNode { Id id {}; std::string name {}; long long int passengerCount {0}; std::vector<std::shared_ptr<GraphEdge>> edges {}; // Find the edge for a specific line route. std::vector< std::shared_ptr<GraphEdge> >::const_iterator FindEdgeForRoute( const std::shared_ptr<RouteInternal>& route ) const; }; I'm not sure about the "find the edge for a specific line route" part of the code. So is FindEdgeForRoute a vector of shared pointers to type GraphEdge, but instead of a normal vector it's an iterator? I'm confused. It's also instantiated in this particular manner: bool TransportNetwork::AddStation( const Station& station ) { // Create a new station node and add it to the map. auto node {std::make_shared<GraphNode>(GraphNode { station.id, station.name, 0, // We start with no passengers. {} // We start with no edges. })}; return true; } Is the above the same as if I do bool TransportNetwork::AddStation( const Station& station ) { GraphNode node; node.id = station.id; node.name = station.name; node.passengerNumber = 0; } And I don't know how I would initialize the FindEdgeForRoute function. Can anyone help clarify this?
is FindEdgeForRoute a vector of shared pointers to type GraphEdge, but instead of a normal vector it's an iterator? What you see in the struct definition is that it declares a const member function called FindEdgeForRoute that takes one parameter (a const std::shared_ptr<RouteInternal>&) and returns a const_iterator into a std::vector<std::shared_ptr<GraphEdge>>. I don't know how I would initialize the FindEdgeForRoute function. You need to call it with a std::shared_ptr<RouteInternal>.
69,405,207
69,405,435
I'm having doubts about how C++ is handling an array
I was messing around just trying to understand how c++ works, when I got "crashed" by the int arrayF[0]; on line 6, and int arrayF[input]; on line 21. In the computer memory the first version of this arrayF shouldn't be overwrote by the one on line 21? I know that int arrayF[input]; is in another scope, but still do what is supposed to do, or not? And I tested another thing(don't know why) removing the int from int arrayF[input]; on line 21 like I was trying to access that address and somehow, the program works as intended. Why? This should arise a error by trying to access a unexistent address. Yes, this a fibonacci program, my intention is not make this exactualy right, I'm just messing with the language. #include <iostream> #include <string> using namespace std; int arrayF[0]; int fiboR(int i, int n) { if(i == n) return arrayF[n]; else arrayF[i + 2] = arrayF[i] + arrayF[i + 1]; return fiboR(i + 1, n); } int main(int argc, char *argv[]) { int input = stoul(argv[argc - 1]); int start = stoul(argv[argc - 2]); int arrayF[input]; arrayF[0] = 0; arrayF[1] = 1; cout << fiboR(start, input) << "\n"; return 0; } The program works by calling it with command-line arguments, the 0 is the first fibonacci's sequence index, a start argument. The next numer is the desired index of the fibonacci's sequence Output with int arrayF[input]; on line 21: $ ./a.out 0 10 0 Output with arrayF[input]; on line 21: $ ./a.out 0 10 55
int arrayF[0]; This program is ill-formed. The size of an array variable must not be zero. if(i == n) return arrayF[n]; Even if we pretend that empty array variables were allowed, then all indices to such array would be outside the bounds of the array. Regardless of what the value of n is, this would read outside the bounds and behaviour of the program will be undefined. int arrayF[input]; The size of an array must be compile time constant. input is not compile time constant. The program is ill-formed. Note that this second array variable is local to the main function. The fiboR function is outside of that scope and it will not see this variable. memory the first version of this arrayF shouldn't be overwrote by the one on line 21? That's not how C++ works. The both arrays exist in different parts of the memory. The name within the nested scope hides the other name within the inner scope - but not outside of its scope. And I tested another thing(don't know why) removing the int from int arrayF[input]; on line 21 like I was trying to access that address and somehow, the program works as intended. Why? This should arise a error by trying to access a unexistent address. The behaviour of accessing outside of bounds is undefined. There is no guarantee that you would get an error even though you may hope to get one. Evidently you weren't lucky this time.
69,405,208
69,411,585
Compiler error c2237 when working with modules
I am trying to change a project to use modules in visual studio. I have changed a simple class to generate a module as follows: #pragma once export module FieldData; namespace Serializer { class FieldData { public: bool nvConverted{ false }; }; } I've also changed the item type to 'c/c++ compiler' This results in the following error however: error C2237: multiple module declaration Unfortunately there seems to be no documentation on what causes c2237 or how to resolve it
I figured it out. The problem was that I hadn't changed the 'Compile as' option in the project properties -> Configuration properties -> C/C++ -> Advanced. The value it needs to be is: 'Compile as C++ Module Code (/interface )'
69,405,241
69,405,441
Why can't we use square brackets in case of dynamic vectors?
#include <iostream> using namespace std; #include <vector> #include <queue> int main(){ vector<int> *v = new vector<int>; v -> push_back(1); //min priority queue priority_queue<int, vector<int>, greater<int>> pq; pq.push(v[0]); //Able to do pq.push(v -> at(0)) } So why is this giving an error? Am i not pushing an integer inside my priority queue?
A std vector already manages its buffer dynamically. In 99.9% of cases, new std::vector is a mistake. vector<int> v; v.push_back(1); //min priority queue priority_queue<int, vector<int>, greater<int>> pq; pq.push(v[0]); this works. If you are really in the 0.1% of cases where new on a vector makes sense, change v[0] to (*v)[0]. What v[0] does is treat the pointer v as a pointer to an array of vectors. It then picks the 0th one. It does not pick the 0th element of the 0th one. v[0][0] would also work (but would be a bad way to do that when v is not actually a pointer to array; confusing to readers usually). So C++ inherits an array pointer duality from C. When you have a pointer, you can use square brackets to treat it as an array as if it was the pointer to the first element of the array. This is actually how array [] works; the array is implicitly converted to a pointer, then [] applies. This is confusing when you have a pointer that isn't pointing at an array. C++ also has objects, and those objects can overload operators like square brackets. The overloading happens on the objects not on pointers to those objects. So vector[] fakes being an array and finds the elements owned by the vector. ptr_to_vector[] insteat treats it as an array of vectors starting at *ptr_to_vector, almost never what you want. C++ is relatively unique in having full fledged objects that can be values. Few languages do. This can be confusing if you are coming from other languages. Embrance value semantics in C++ when you can.
69,405,274
69,405,318
Using copy algorithm to copy from vector to set
As a purely learning experience I want to be able to use the copy algorithm to copy from a vector to a set. This is what I am trying to do: vector<int> myVector = {0, 1, 1, 2, 2, 3, 3, 4, 5, 6}; // set<int> mySet(myVector.begin(), myVector.end()); // This works, no issues set<int> mySet; copy(myVector.begin(), myVector.end(), some_inserter_that_will_work(mySet)); Somewhere on the web it was suggested that the inserter function would work but it is giving me the following compile error: error: no matching function for call to ‘inserter(std::set&)’
You need to use std::inserter in this way, indicating the insertion position as second argument: copy(myVector.begin(), myVector.end(), inserter(mySet, mySet.end()));
69,405,805
69,405,878
Why does a rising integer with no influence crash my program
This is my code and it works as expected. But after adding a rising integer (even though it has no influence on the code) my code doesn't work as expected #include <iostream> int i; int j = 0; int nums[] = {}; int co = 0; void rq1() //rq = request { std::cout << ("How many numbers?"); std::cin >> i; } void rq2 () { int n2 = 0; for (int n = 1; n <= i; n++) { std::cout << n2 + 1 << (". number?"); std::cin >> nums[n2]; n2++; } } void sort () { for (int n4 = 0; n4 < i; n4++) { int k = j + 1; for (int n3 = 1; n3 < i; n3++) { if (nums[j]==nums[k]) { if (j<k) {std::cout << j << "," << k << std::endl; k++;} else {k++; return;} } else {k++;} } j++; } } int main() { rq1(); rq2(); sort(); } Input: 4 numbers (1,2,1,2) Output: (0 , 2) (1 , 3) But after adding co++ the Output is (0,2) but expected Output is (0 , 2) (1 , 3) { for (int n4 = 0; n4 < i; n4++ ) { int k = j + 1; for (int n3 = 1; n3 < i; n3++) { if (nums[j]==nums[k]) { if (j<k) {std::cout << j << "," << k << std::endl; k++; co++;} else {k++; return;} } else {k++;} } j++; } } I don't know why my outputs changes. I mean int co doesn't do anything else
int nums[] = {}; This array variable has no elements. This isn't allowed in C++. The program is ill-formed. std::cin >> nums[n2]; Here you access the empty array outside of its bounds. The behaviour of the program is undefined. I don't know why my outputs changes. It's because the behaviour of the program is undefined.
69,406,084
69,406,401
Is it possible to use a custom allocator to allocate an arbitrary sized area?
I have a container class that manages the underlying memory in different chunks. The number of chunks varies with the number of objects stored in the container. I allocate a new chunk of memory whenever the container is about to exceed the currently available memory. And also, deallocate a chunk whenever it is no longer in use. So, the number chunks are variable during runtime. Therefore, I've to store the chunk pointers in a dynamically growing/shrinking array. /*** Container Class ***/ template<class T, class Allocator = std::allocator<T>> class CustomContainer{ public: // Some member methods here.. private: void createNewChunk() { // Some code goes here ... newChunkAddr = new T*[CHUNK_SIZE]; } void destroyChunk(T* chunkAddr) { // Some code goes here ... delete [] chunkAddr; } private: /*** Members ***/ // Some other members ... std::size_t size = 0; T** chunks = nullptr; Allocator allocator; }; Everything is well as long as the system that uses this container has a heap, thus a properly implemented operator new. The problem occurs when the system doesn't use the operator new and the user assumes that the container will allocate any dynamic resource using the Allocator it provides. Immediately after a quick brainstorm, I thought that I can use the allocate method of the std::allocator_traits class for allocating the space required. Unfortunately, that method can only allocate areas of a size which is an exact multiple of the template value type used in the allocator. Here is the explanation of the corresponding function: Uses the allocator a to allocate n*sizeof(Alloc::value_type) bytes of uninitialized storage. An array of type Alloc::value_type[n] is created in the storage, but none of its elements are constructed. Here is the question, what is the proper way of allocating/deallocating the space for storing the chunk pointers?
what is the proper way of allocating/deallocating the space for storing the chunk pointers? Any correct way of allocating memory is a proper way. Each have their benefits and drawbacks. You should choose based on which benefits and drawbacks are important to your use case. You could use static storage if you wish to avoid dynamic storage, but that would limit your maximum number of chunks. Or if you don't mind dynamic storage, then you can use the global allocator. You could even let the user customise that allocation by providing a separate custom allocator. The way that standard containers do - which is also a proper way, but not the only proper way - is they would create a new allocator of type std::allocator_traits<Allocator>::rebind_alloc<T*>. If you do go the way of using separate custom allocators, this would be a reasonable default for the second allocator. I've to store the chunk pointers in a dynamically growing/shrinking array. There's a container for that purpose in the standard library: std::vector. You could use that within your container. P.S. Your the description of your container is quite similar to std::deque. Consider whether it would be simpler to just use that.
69,406,591
69,407,318
How to edit some parts of text files c++? (Mac OS)
Lets say I have a .txt file that says: Date: 01:10:21 Hi My name is Jack and I want to change My name is Jack to My name is John! but instead of change everything like: file.open("yourname.txt", ios::out); if (file.is_open()) { file << "Date: 01:10:21 \nHi \nMy name is John"; file.close(); } I want to edit only the Jack part to John, Because the date could be changed later that time, so how can I do it? Every help appreciated!
Can't say I know a proper C++ way, but there is a C way using <cstdio>. Here is a snippet how this is achieved, however you need to implement your own logic for the problem, like finding where and how much to replace, ex. use indexes or string buffer to hold your needed data. Here is a minimum snippet: #include <cstdio> #include <cstring> int main() { FILE* fp = fopen("test.txt", "r+"); if (!fp) return -1; int c; char buffer[30] = {0}; while (fgets(buffer, 3 /*hold `is `*/, fp)) { printf("[%s]\r\n", buffer); if (!strcmp(buffer, "is")) { //match `is` for example fgetc(fp); // control the file ptr and move one forward fputs("JOHN", fp); //replace break; } } fclose(fp); return 0; }
69,406,741
69,407,018
Ordering in unordered_map in C++
So I have an array as : arr[] = {5, 2,4,2,3,5,1}; How can I insert them in this order with the number of times they occur in unordered_map? #include<bits/stdc++.h> using namespace std; void three_freq(int arr[], int n){ unordered_map<int, int> m; for(int i=0;i<n;i++){ m[arr[i]]++; } for(auto itr = m.begin(); itr != m.end(); itr++){ cout<<itr->first<<":"<<itr->second<<"\n"; } } int main(){ int arr[] = {5, 2,4,2,3,5,1}; int n = sizeof(arr)/ sizeof(arr[0]); three_freq(arr, n); return 0; } Using the code above I am getting output as : 1:1 3:1 4:1 5:2 2:2 But I want the output to be in same order as the element occur in array. Example: 5:2 2:2 4:1 3:1 1:1
If you don't care about efficiency (that much), then you can just change the for loop which is printing the output. for(int i=0; m.size(); i++) { auto it = m.find(arr[i]); if (it != m.end()) { cout<<arr[i]<<":"<<it->second<<"\n"; m.erase(it); } }
69,406,779
69,407,511
c++ Increase pointer size without return new pointer
My teacher has me complete this(the main is hidden) and i wonder why i got an infinite loop with this solution. Task: Complete this function: void pad_left(char *a, int n) { } // if length of a greater than n, do nothing // else insert '_' util a 's length is n Some case i got an segmentfault I try realloc but it return new ptr My solution #include<iostream> #include<algorithm> #include<cstring> using namespace std; void printChar(char *a) { int i = 0; while(a[i] != '\0') cout << a[i]; cout << endl; } void insert_begin(char *a, int n) { for(int i = n; i > 0; i--) { a[i] = a[i-1]; } a[n+1] = '\0'; } void pad_left(char *a, int n) { int len = n - strlen(a); for(int i = 0; i < len; i++) { insert_begin(a, strlen(a)); } } Here is full code #include<iostream> #include<algorithm> #include<cstring> using namespace std; void printChar(char *a) { int i = 0; while(a[i] != '\0') cout << a[i]; cout << endl; } void insert_begin(char *a, int n) { for(int i = n; i > 0; i--) { a[i] = a[i-1]; } a[n+1] = '\0'; } void pad_left(char *a, int n) { int len = n - strlen(a); for(int i = 0; i < len; i++) { insert_begin(a, strlen(a)); } } int main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); char a[5] = "test"; pad_left(a, 10); printChar(a); return 0; }
Okay, you need some background information. void pad_left(char *a, int n) { } char a[5] = "test"; pad_left(a, 10); This is going to be a significant problem. First, you can't realloc for two reasons. First, char a[5] is a fixed array -- not an allocated array. When you pass it to pad_left, that doesn't change. realloc() does a free of the old pointer, but you can't do that, and it will cause problems. So you cannot use realloc in your solution unless you make sure the strings came from allocated memory. And you can't assume that. So put realloc aside. You can't use that. Next, char a[5] only allocates 5 bytes. If you start writing beyond that range (by passing in 10 to your method), you're going to step on other places. This is absolutely bad. So... Without testing it, the rest of your code seems reasonable. You can probably get a good test if you do this: char a[100] = "test"; pad_left(a, 10); You'll have allocated plenty of space for padding. Try this and see if you get further.
69,407,691
69,440,791
Does substitution failure block special member function generation?
I am trying to understand at a non-superficial level why the following code does not compile: #include <vector> template<typename T> struct wrapper { T wrapped_value; wrapper() {} template<typename... Args> wrapper(Args&&... args) : wrapped_value( std::forward<Args>(args)... ) { } }; struct A { int a; A(int i = 0) : a(i) { } }; int main() { std::vector<wrapper<A>> v1; std::vector<wrapper<A>> v2; v1 = v2; } I can tell from the error message in the std::vector implementation that the above is failing because the perfect forwarding constructor of wrapper<T> matches the copy constructor. The copy constructor created by substitution into the constructor template would be wrapper(wrapper<A>& w) : wrapped_value( w ) { } Because wrapped_value is of type A this is an error since A does not have a constructor accepting a wrapper<A>. But isn't "substitution failure not an error"? So the constructor template fails when the compiler attempts to use it as a copy constructor -- why does this block the automatic generation of a copy constructor? Or does it not and the real problem has something to do with the implementation of std::vector? Also, this is a toy example but what is the best way around this sort of thing in my real code when dealing with classes like this? Use "pass-by-value-then-move" rather than perfect forwarding? Just define the copy constructor as default? Use an std::in_place_t parameter before the variadic parametes in the perfect forwarding constructor? Disable the constructor template in the case of copy construction via enable_if et. al.
Substitution is not failing and special function generation is not being blocked. Template substitution leads to a constructor that is a better match than the compiler-generated copy constructor so it is selected which causes a syntax error. Let's simplify the problem illustrated in the question by getting rid of usage of std::vector. The following will also fail to compile: #include <utility> template<typename T> struct wrapper { T wrapped_value; wrapper() {} template<typename... Args> wrapper(Args&&... args) : wrapped_value(std::forward<Args>(args)...) { } }; struct A { int a; A(int i = 0) : a(i) { } }; int main() { wrapper<A> v1; wrapper<A> v2(v1); } In the above template substitution is not failing as applied to the required the copy constructor. We end up with two overloads of the copy constructor, one generated by the compiler as part of special function generation and one produced by substituting the type of v1 into the constructor template: wrapper(wrapper<A>& rhs); // (1) instantiated from the perfect forwarding template wrapper(const wrapper<A>& rhs); // (2) compiler-generated ctor. by the rules of C++ (1) has to be chosen since v1 in the orginal code is not const. You can actually check this by making it const and the program will no longer fail to compile. As for what to do about this, as @jcai mentions in comments, Scott Meyers' Item 27 in Effective Modern C++ is about how to handle this issue -- basically it comes down to either not using perfect forwarding or using "tag dispatch" -- so I will not go into it here.
69,407,692
69,408,051
What may be the reason for this constructor failing to initialize with the given values?
I have been trying to solve an example question from a book and I encountered this problem while initializing the constructor with the values given below. Normally constructor initializes the variables beforehand. When I run the function from a function like Rational_Caller, the member function file given below gives an error as "DIVISION BY ZERO ERROR". Since I initialize the first object with given values in Rational_Caller function, I couldn't figure out why denominator gets the value 0. this is the header file // Rational Class header file #ifndef _RATIONAL_H_ #define _RATIONAL_H_ class Rational { public: Rational(int = 0, int = 1); // default constructor Rational addition(const Rational&); Rational subtraction(const Rational&); Rational multiplication(const Rational&); Rational division(const Rational&); void printRational(); void printRationalAsdouble(); private: int numerator; int denominator; void reduction(); // function to reduce using great common divisor }; #endif // !_RATIONAL_H_ this is the member function definitions for the file Rational.h #include <iostream> #include "Rational.h" // include definiton of class Rational using namespace std; Rational::Rational(int n, int d) { numerator = n; denominator = d; reduction(); } Rational Rational::addition(const Rational& a) { Rational t; t.numerator = a.numerator * denominator; t.numerator += a.denominator * numerator; t.denominator = a.denominator * denominator; t.reduction(); return t; } Rational Rational::subtraction(const Rational& s) { Rational t; t.numerator = s.numerator * denominator; t.numerator -= denominator * s.numerator; t.denominator = s.denominator * denominator; return t; } Rational Rational::multiplication(const Rational& m) { Rational t; t.numerator = m.numerator * numerator; t.denominator = m.denominator * denominator; t.reduction(); return t; } Rational Rational::division(const Rational& v) { Rational t; t.numerator = numerator * v.denominator; t.denominator = denominator * v.numerator; t.reduction(); return t; } void Rational::printRational() { if (denominator == 0) cout << "\nDIVIDE BY ZERO ERROR!!!" << "\n"; else if (numerator == 0) cout << 0; else cout << numerator << '/' << denominator; } void Rational::printRationalAsdouble() { cout << static_cast<double>(numerator) / denominator; } void Rational::reduction() { int largest; largest = numerator > denominator ? numerator : denominator; int gcd = 0; for (int loop = 2; loop <= largest; loop++) { if (numerator % loop == 0 && denominator % loop == 0) gcd = loop; if (gcd != 0) { numerator /= gcd; denominator /= gcd; } } } this is the file I call the functions #include <iostream> using namespace std; #include "Rational.h" int main() { Rational obj1(8, 14), obj2(5, 7), resobj; obj1.printRational(); cout << " + "; obj2.printRational(); resobj = obj1.addition(obj2); cout << " = "; resobj.printRational(); }
The proble is in void Rational::reduction() function. What happens when if (numerator % loop == 0 && denominator % loop == 0) is false? You should have initlise gcd to 0 for each iteration of for-loop or even batter, do't use gcd variable at all. See it here in action: for (int loop = 2; loop <= largest; loop++) { if (numerator % loop == 0 && denominator % loop == 0) { numerator /= loop; denominator /= loop; } }
69,407,697
69,408,321
Missing return statement after if-else
Some compilers (Intel icc, pgi/nvc++) issue "missing return statement" warning for functions like below, while others (gcc, clang) do not issue warnings even with -Wall -Wextra -pedantic: Is the code below legal according to the standard? This is a minimal reproducible example of my code that gives the warning. Simplifying it to, say, just a single function removes the warning. // test.cpp #include <climits> #include <cstddef> template<class T, std::size_t N> class Test { public: class Inner; private: static constexpr std::size_t NB_ = sizeof(std::size_t) * CHAR_BIT; static constexpr std::size_t NI_ = (N + NB_ - 1) / NB_; }; template<class T, std::size_t N> class Test<T, N>::Inner { public: Inner() : b_{0}, j_{0} {} friend bool operator!= (Inner x, Inner y) { if constexpr(J_ > 0) return x.j_ != y.j_ || x.b_ != y.b_; else return x.b_ != y.b_; } private: static constexpr std::size_t J_ = NI_ - 1; std::size_t b_; std::size_t j_; }; int main() { Test<int, 50>::Inner x, y; int a, b; x.b_ = a; y.b_ = b; x != y; } Compilation: > nvc++ test.cpp -std=c++17 "test.cpp", line 30: warning: missing return statement at end of non-void function "operator!=" } ^ detected during instantiation of class "Test<T, N>::Inner [with T=int, N=50UL]" at line 41
The C++ standard says this, see [stmt.return]/2: Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main results in undefined behavior. Your operator != does exactly that. It never flows off the end of the function since all control paths end with a return. Hence the code is correct, and the compiler's diagnostic is wrong.
69,408,216
69,408,308
How does this line of code negate a std::uint64_t value?
I'm trying to understand what this code does. This is supposed to negate the coefficient coeff of type uint64_t* of a polynomial with coefficients modulus modulus_value of type const uint64_t: std::int64_t non_zero = (*coeff != 0); *coeff = (modulus_value - *coeff) & static_cast<std::uint64_t>(-non_zero); What's up with the & static_cast<std::uint64_t>(-non_zero)? How does this negate anything? The code is from here.
non_zero will be either 1 or 0. -non_zero will turn that into -1 or 0. static_cast<std::uint64_t>(-non_zero) will tell the compiler to treat the signed number as unsigned, which will turn 0 into 0, and -1 into 0xffffffffffffffff. Then the bitwise AND will either clear all bits of (modulus_value - *coeff) (if non_zero is 0) or keep all the bits of (modulus_value - *coeff) as they are (i.e. it's a no-op really). So the result assigned back to *coeff will be either 0 or modulus_value - *coeff. It's equivalent to (modulus_value - *coeff) * non_zero. Or in shorter form (modulus_value - *coeff) * !!*coeff.
69,408,691
69,408,839
Variable with same name as type gives no compilation error when placed in function, struct or class
Given the Code: #include <iostream> typedef int Integer; Integer Integer = 1234; int main() { std::cout << "Integer: " << Integer; } Compiling the code with the gcc 11.2 Compiler will result in compilation errors: error: 'Integer Integer' redeclared as different kind of entity 4 | Integer Integer = 1234; | ^~~~~~~ note: previous declaration 'typedef int Integer' 3 | typedef int Integer; | ^~~~~~~ In function 'int main()': error: expected primary-expression before ';' token 7 | std::cout << "Integer: " << Integer; | ^ However, changing the code to: #include <iostream> typedef int Integer; int main() { Integer Integer = 1234; std::cout << "Integer: " << Integer; } will not result in a compilation error. I tried using the gcc 11.2, clang 12.0.1 and MSVC 19.29 Compiler and all failed at the first version but allowed the second one. Why does the second version work while the first one fails?
The difference is one of scope. In the first example, both Integers are declared in the global scope: typedef int Integer; Integer Integer = 1234; In the second example, one is declared in the global scope, whereas the other is local to main: typedef int Integer; int main() { Integer Integer = 1234; ... } It works because, at the moment the compiler reads the first Integer inside main, there is only one entity with that name, so it must refer to the type in the global scope. But once you've declared a variable with the name Integer inside main, you cannot use that name again to refer to the type instead: typedef int Integer; int main() { Integer Integer = 1234; // OK because only the type is visible. Integer otherInteger = 567; // Error because Integer is a variable here. ::Integer thirdInteger = 89; // OK because :: resolves to the global one. }
69,410,277
69,417,486
"Directory listing failed" when execute "dart pub publish --dry-run"
I'm trying to publish a flutter plugin and I got this error when I perform a dry run. The plugin can be compiled and it works well, source code is here How do I fix it? Thank you. PS F:\Armoury\SourceCode\window_interface> dart pub publish --dry-run Publishing window_interface 0.1.0 to https://pub.dartlang.org: ... Directory listing failed, path = '.\example\windows\flutter\ephemeral\.plugin_symlinks\window_interface\example\windows\flutter\ephemeral\.plugin_symlinks\window_interface\example\windows\flutter\ephemeral\.plugin_symlinks\window_interface\windows\include\*' (OS Error: The system cannot find the path specified. , errno = 3) PS F:\Armoury\SourceCode\window_interface>
I recreated the project and the problem doesn't appear, additional, the project needs to be cleaned before publish
69,410,312
69,410,535
std::forward not allowing lvalues to be accepted
Below is an implementation of the insert() member function of a max heap. I tried to use std::forward as I think it can be alternative to writing an overload of this function that accepts lvalues. However, the code is still not working for lvalues. Any ideas why? Note: values is a private vector<T> in the max_heap class. template <typename T, typename compare_type> void max_heap<T, compare_type>::insert(T&& item){ if(values.empty()){ values.push_back(std::forward<T>(item)); return; } values.push_back(std::forward<T>(item)); size_t child_pos = values.size()-1; size_t parent_pos = (child_pos-1)/2; //stop swapping either when inserted child at root or smaller than parent while(child_pos != 0 && pred(values[parent_pos], values[child_pos])){ std::swap(values[parent_pos], values[child_pos]); child_pos = parent_pos; parent_pos = (child_pos-1)/2; } }
To create a forwarding reference, your argument's type must exist as a template parameter of the same function template. (See (1) of forward references for more information.) In your case, the template parameter T is from the class max_heap and not from the function's template argument list, so item serves as an rvalue reference (which can't bind to lvalues) and not as a forwarding reference. For your case, try something like this: #include <cstddef> #include <utility> #include <vector> // Other header includes go here ... template <typename T, typename compare_type> class max_heap { // Other instance variables go here ... public: template <typename U> // <- Notice how the template parameter 'U' is bound to the 'same function template' void insert(U&& item); // Other member methods go here ... }; // ... template <typename T, typename compare_type> template <typename U> void max_heap<T, compare_type>::insert(U&& item){ if(values.empty()){ values.push_back(std::forward<U>(item)); return; } values.push_back(std::forward<U>(item)); size_t child_pos = values.size()-1; size_t parent_pos = (child_pos-1)/2; //stop swapping either when inserted child at root or smaller than parent while(child_pos != 0 && pred(values[parent_pos], values[child_pos])){ std::swap(values[parent_pos], values[child_pos]); child_pos = parent_pos; parent_pos = (child_pos-1)/2; } } // Other definitions go here ...
69,410,954
69,411,421
Dereferencing struct pointer in pthread
I need to pass a structure to a pthread and be able to change the values of the struct from the function the pthread will execute. This is my code: #include <stdio.h> #include <stdlib.h> #include <vector> #include <pthread.h> void *deal_cards(void* deck); int main() { struct t_data { std::string name; std::string status; std::vector<int> hand; std::vector<int> *ptr_deck; }; std::vector<int> deck = {1,2,3}; std::vector<int> *p_deck = &deck; struct t_data player1_data = {"PLAYER 1", "lose", {}, p_deck}; struct t_data *player1 = &player1_data; pthread_t p1; pthread_create (&p1, NULL, deal_cards, (void *) player1); } void* deal_cards (void* data) { (struct t_data*)->(std::vector<int>*)ptr_deck.push_back(3); } I get the following error when I run this In function 'void* deal_cards (void*) error: expected primary-expression before 'struct' error: expected ')' before 'struct' In case it matters I'm compiling on Linux with g++ main.cpp -o main -lpthreads What am I missing and is that the right way to alter the values inside the structure?
There are numerous mistakes in your code: The t_data structure type is defined local to main(), so deal_cards() can't use it. main() is exiting, destroying its local variables, while the thread is still running. the syntax you are trying to use to access push_back() in deal_cards() is all wrong. You are not referencing the data input parameter at all, that is what you should be type-casting to t_data*. And, you are type-casting ptr_deck to std::vector<int>*, which it is already typed as, so that cast is unnecessary. And, since ptr_deck is a pointer, you need to use the -> operator to access its push_back() method, not the . operator. Also, while not strictly errors, you should also be aware of these: you are using std::string without #include <string> unlike in C, in C++ you don't need to prefix references to a structure type with the struct keyword. Only the declaration of the structure type needs to use the struct keyword. With that said, try this instead: #include <vector> #include <string> #include <pthread.h> void* deal_cards(void* deck); struct t_data { std::string name; std::string status; std::vector<int> hand; std::vector<int> *ptr_deck; }; int main() { std::vector<int> deck = {1,2,3}; t_data player1_data = {"PLAYER 1", "lose", {}, &deck}; pthread_t p1; if (pthread_create (&p1, NULL, deal_cards, &player1_data) == 0) { pthread_join (p1, NULL); // use deck as needed... } } void* deal_cards (void* data) { static_cast<t_data*>(data)->ptr_deck->push_back(3); return NULL; } Though, you really should be using C++'s own std::thread class instead of pthreads directly: #include <vector> #include <string> #include <thread> struct t_data { std::string name; std::string status; std::vector<int> hand; std::vector<int> *ptr_deck; }; void deal_cards(t_data* deck); int main() { std::vector<int> deck = {1,2,3}; t_data player1_data = {"PLAYER 1", "lose", {}, &deck}; std::thread p1(deal_cards, &player1_data); p1.join(); // use deck as needed... } void deal_cards (t_data* data) { data->ptr_deck->push_back(3); }
69,411,620
69,411,700
C++ headers inclusion order, strange behaviour
I'm writing some library and want to have some "optional" class methods (or just functions), declared or not, dependent on other library inclusion. Say, I have a class SomeClass with method int foo(std::string). Sometimes it's very useful to also have similar method(s) which uses classes of another library the project is build upon - for example, sf::String or wxString, for SFML or wxWidgets accordingly. In this case including SFML/System.hpp or even worse, wx/app.hpp or similar is absolutely NOT an option, because I want to have only methods for libraries that are already included. So, my first example must (as I suppose) work fine, but it's not: main.cpp: #include <SFML/System.hpp> // FIRST, I include SFML base lib in the very first line. #include <SFML/System/String.hpp>// to be 100% sure, I include SFML string class, #include "a.h" // and ONLY AFTER that I include my own lib // so inside the "a.h" file, the sf::String class *must* be already declared main() { SomeClass x; x.foo("ABC");// error here: "undefined reference to `SomeClass::foo(sf::String)" } a.h: #ifndef A_H_INCLUDED #define A_H_INCLUDED class SomeClass { public: #ifdef SFML_STRING_HPP int foo(sf::String str);// this method is declared, as expected #endif }; #endif a.cpp: #include "a.h" #ifdef SFML_STRING_HPP int SomeClass::foo(sf::String str) { return 1; } #endif The first question is: WHY? a.cpp includes a.h in the very beginning, and inside a.h the sf::String is declared, so why inside a.cpp after #include "a.h" it is not declared in fact? I've tried to add #error OK right before #endif directive in a.cpp file, and this error is not fired. Do I miss something about #include and .cpp / .h files?.. The second question is: How to fix that or work it around? (And yes, I do a clean rebuild every time to avoid possible compiler bugs about partially changes sources, g++ likes it). P.S: The same kind of "dependent" methods declarations works perfectly well with some template class - I suppose, it's because the implementation is within .h file where everything is OK about conditional compilation.
a.c includes a.h that does not include <SFML/System/String.hpp>, thus SFML_STRING_HPP is not defined. Usually, what to include is set through compiler -D options. For example -DUSE_SFML_STRING main.cpp #include <SFML/System.hpp> // FIRST, I include SFML base lib in the very first line. #include "a.h" // and ONLY AFTER that I include my own lib // so inside the "a.h" file, the sf::String class *must* be already declared main() { SomeClass x; x.foo("ABC");// error here: "undefined reference to `SomeClass::foo(sf::String)" } a.h #ifndef A_H_INCLUDED #define A_H_INCLUDED #ifdef USE_SFML_STRING #include <SFML/System/String.hpp> #endif class SomeClass { public: #ifdef SFML_STRING_HPP int foo(sf::String str);// this method is declared, as expected #endif }; #endif
69,411,635
69,411,835
How do we read from file and store it into different objects in c++?
I am working on a project to store class objects in a dynamically allocated array. Now instead of users setting objects' values, I am trying to read object's values from a text file. There are 10 objects stored in the file and I want to read 8 objects and then insert them in my dynamic array. This is my class: class Person { private: std::string name; double age; public: // Constructor Stock(const std::string& name = "", double age = 0) { this->name = name; this->age = age; } // copy constructor Stock(const Stock& s) { this->name = s.name; this->age = s.age; } // Display function void display() const { std::cout << "Name is " << name << ", " << "Age is " << age << ".\n"; } // get functions std::string getName() const { return name; } double getAge() const { return age; } And my text file looks like this: Tony 25 Cap 30 Loki & Sylvi 20 ... How can I read these lines into 8 separate objects?
It appears you have not actually compiled the code provided, since there are problems with it. There are different ways to serialize/deserialize data. Here is one way, which may be sufficient for your needs. This code allows constructing a Person from an istream&. Another way to provide a static class factory function to construct a Person from an istream&, which is probably more common. Once constructed, the Person can be added to a vector, which is the dynamic array in C++. #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> using std::cout; using std::getline; using std::istream; using std::istringstream; using std::move; using std::ostream; using std::runtime_error; using std::string; using std::vector; namespace { char const* data = R"(Tony 25 Cap 30 Loki & Sylvi 20 Bob 1 20 Bob 2 30 Bob 3 40 Bob 4 50 Bob 5 60 Bob 6 70 Bob 7 80 )"; auto get_string(istream& in) -> string { string result; if (getline(in, result)) return result; throw runtime_error("get_string"); } auto get_double(istream& in) -> double { string line; if (!getline(in, line)) throw runtime_error("get_double"); istringstream ss(line); double result; if (!(ss >> result)) throw runtime_error("get_double"); return result; } class Person final { string _name; double _age; public: Person(string name_ = "", double age_ = 0) : _name{move(name_)}, _age{age_} { } Person(Person const& s) : _name{s._name}, _age{s._age} { } Person(istream& in) : _name{get_string(in)}, _age{get_double(in)} { } void print(ostream& out) const { out << "Name is " << _name << ", " << "Age is " << _age << "."; } auto name() const -> string { return _name; } auto age() const -> double { return _age; } }; auto operator<<(ostream& out, Person const& p) -> ostream& { p.print(out); return out; } auto operator<<(ostream& out, vector<Person> const& v) -> ostream& { for (auto&& p : v) { out << p << "\n"; } return out; } } // anon int main() { istringstream ss(data); auto tony = Person(ss); auto cap = Person(ss); auto loki_sylvi = Person(ss); cout << tony << "\n"; cout << cap << "\n"; cout << loki_sylvi << "\n"; vector<Person> peeps; peeps.emplace_back(ss); peeps.emplace_back(ss); peeps.emplace_back(ss); cout << peeps << "\n"; }
69,411,836
69,411,903
C++ Stack around variable corrupted and issue with the size of an array
I have a program that has been stumping me for the past few weeks. It asks the user to input how many rolls they want from two six sided dice, then runs a function that rolls those numbers and adds them together. The sums go into an array and then from that array, the amount of each sums is counted. Next, the odds of each roll is calculated as well as the error percentage. Finally, the total sums rolled, the odds, and error percentage is tabulated. There are two issues I'm facing at the moment. The first is that I input an amount of times I want the program to roll the dice, but with larger numbers the array doesn't hold all of them. For example I input 100 and it only gives me 5 array values or with 50 it gives only 7. My second issue is that I have a do while loop for after the program takes the input and shows the output, the user is asked if they want to try again (putting in 1 for yes or 0 for no). When I hit zero to close the program, it tells me the "stack around the variable 'countingArray' was corrupted." I tried changing the for loop that fills the array with adding countingArray[]++; but that only told me that the stack around doAgain was now corrupted instead of countingArray. I also tried using vectors since it would be easier with me not knowing the initial size of the array, but I was struggling with that and someone else told me to use arrays instead that it would be "easier". CODE: #include <iostream> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; int dice(int total) { int diceOne, diceTwo; diceOne = rand() % 6 + 1; diceTwo = rand() % 6 + 1; total = diceOne + diceTwo; return total; } //dice end int main() { //seeding srand(time(0)); //variables int input = 0, diceOne, diceTwo, total = 0, doAgain; int two = 0, three = 0, four = 0, five = 0, six = 0, seven = 0, eight = 0, nine = 0, ten = 0, eleven = 0, twelve = 0; do { //input cout << "Please enter the number of rolls you want: "; cin >> input; //array int countingArray[] = { 0 }; int oddsNow[] = { 0 }; int odds[] = { 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 12 }; //odds Array end //filling array for (int rolls = 0; rolls < input; rolls++) { countingArray[rolls] = dice(total); } //for end for (int i = 0; i < input; i++) { cout << "\ncountingArray[" << i << "]: " << countingArray[i]; } //for end //repeat cout << "\nTry Again? (1 == yes || 0 = exit) \n"; cin >> doAgain; }while (doAgain == 1 && doAgain != 0); return 1; } //main end
You're using finitely sized arrays, in particular int countingArray[] = { 0 }; is an array with enough memory for one integer. When you fill the array, you are indexing into whatever memory lies beyond the end of the array! This is totally scribbling over who knows what. for (int rolls = 0; rolls < input; rolls++) { countingArray[rolls] = dice(total); // What if rolls is > 0 ? BOOM! } If you use std::vector<int> instead of an array, you can simply push entries onto the end of it with vector.push_back(). You don't necessarily need to know how large it will grow beforehand, as it will grow as needed. Explicitly: std::vector<int> countingVec; for ( int rolls = 0; rolls < input; ++rolls ) { countingVec.push_back( dice( total ) ); }
69,412,140
69,414,345
Can't sort model by QDateTime with using QSortFilterProxyModel sort by role
I am stuck with simple problem but I can't figure it out why my model is not sorted. I have SimpleModel class that inherits from QAbstractListModel and I want to sort it by DateTime role. This is how I am setting the Proxy in my main.cpp: SimpleModel m; ProxyModel proxyModel; proxyModel.setSourceModel(&m); proxyModel.setSortRole(SimpleModel::SimpleRoles::DateTimeRole); engine.rootContext()->setContextProperty("simpleModel", &proxyModel); My Items in the SimpleModel are objects from SimpleItem class which has only Name and DateTime. This is my SimpleModel data method: QVariant SimpleModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) { return QVariant(); } auto simpleItem = static_cast<SimpleItem*>(index.internalPointer()); if (!simpleItem) { return QVariant(); } if(role == NameRole) { return simpleItem->name(); } //This is used for displaying in QML else if(role == DateRole) { return simpleItem->dateTime().toString("yyyy-MM-dd"); } // This is used for dsiplaying in QML too else if(role == TimeRole) { return simpleItem->dateTime().toString("hh:mm"); } // This Role is only used for sorting else if(role == DateTimeRole) { return simpleItem->dateTime(); } return QVariant(); } And in my ProxyModel that inherits from QSortFilterProxyModel class I have implemented lessThan() methood but it never gets called: bool ProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const { qDebug() << "called lessThan()"; QVariant leftData = sourceModel()->data(source_left); QVariant rightData = sourceModel()->data(source_right); if (leftData.userType() == QMetaType::QDateTime) return leftData.toDateTime() < rightData.toDateTime(); return false; } What I am doing wrong or do you have any idea that I can try? If you need more code I will update. Thanks in advance.
as you say it works after calling proxyModel.sort(0, Qt::DescendingOrder); after setSortRole
69,412,498
69,412,839
Why my assigning an object itself doesn't work properly?
AFAIK, for an operator that doesn't guarantee the order of evaluation of its operand(s), we should not modify the operand more than once. Here I have this snippet that I wrote: I'm compiling it using gcc with the C++20 standard: -std=c++2b. int main(){ std::string s = "hello"; auto beg = s.begin(); *beg = *beg++; std::cout << s << " " << *beg << std::endl; } Why do I get this output? hhllo h This: *beg = (*beg)++; std::cout << s << " " << *beg << '\n'; yields this output: hello h Why is the value 'h' not incremented to 'i'? What happens here? Normally, this assigns the first character in s back to itself then increments the beg iterator. But the iterator is not incremented, but the value changed! I bet that it is because of Undefined Behavior, but if so then can someone explain this to me? Did the C++17 standard add the assignment operator to the 'sequenced' operators? If so, why doesn't it work properly in my example?
All of these results are correct. Your misunderstanding comes from not knowing how postfix increment works. *beg = *beg++; By the rules of C++ operator precedence, postfix operators happen first. So this is *beg = *(beg++). C++17 forced assignment operators to completely evaluate all expressions on the right-hand side, including all side-effects, before evaluating the left-hand side. Postfix iterator increment increments the lvalue, but it returns a copy of the original value. The original value is an iterator pointing at the first character. So after evaluating beg++, beg will have changed its position (therefore pointing at the second character). But the value of the expression is an iterator pointing at the first. Then this iterator is derefenced, thus returning a reference to the first character. After that, the lhs is evaluated. beg as previously noted, points to the second character. So *beg is a reference to the second character, which gets assigned to the value of the first character. *beg = (*beg)++; So this is the other way around. *beg is a reference to the first character, which is then postfix incremented. This means that the object referenced by *beg is incremented, but the value of the expression is a copy of the original value. Namely, the character as it was before being incremented: 'h'. You then assign this character to the first character, therefore overwriting what you just incremented. BTW: if you have to go into this detail to figure out what an expression is doing, you shouldn't write your expression that way. Avoid postfix expressions unless they are absolutely essential in some way.
69,412,552
69,432,240
CGAL: Which headers to include
What is the standard workflow to figure out which headers are needed to make the program compile? Take the following simple example #include <iostream> int main() { std::cout << CGAL::square(0.002) << '\n'; return 0; } The function square is defined in Algebraic_foundations/include/CGAL/number_utils.h. Question 1: Why is it not enough to just #include <CGAL/number_utils.h>? I was made aware that #include <CGAL/basic.h> makes the program compile. I guess one can use a more fine-grained file inclusion and looking in basic.h I found out that #include <CGAL/number_type_basic.h> is enough. Question 2: Does using a finer-grained file inclusion decrease compilation time (less text in compilation unit?) but executable/object files will not differ as compilers remove the excess code from unneeded inclusions? Question 3: Is there another rationale why one would use finer inclusions? Some kind of style guide? Or is it even good practice to include a high-level header to make it safe against changes in low-level code? Question 4: What kind of high-level headers are there in CGAL? Is there one for the whole library? How is the connection regarding all the different packages? Is there one for each package? Question 5: If it is good practice to include middle- to lower-level header files then what is the standard workflow to figure out which headers are needed, e.g. for the square function in the above mentioned example?
Almost all reference manual pages such as this one of the class Triangulation_2 give as very first information which header file to include. All higher level data structures are parameterized with a geometric traits class for which they in most cases pass a kernel, e.g., the Exact_predicates_inexact_constructions_kernel, which again states what header to include. The latter will define number types which include all the infrastructure. Note that CGAL/basic.h is not documented.
69,412,579
69,412,714
Assign value in ternary operator
When using std::weak_ptr, it is best practice to access the corresponding std::shared_ptr with the lock() method, as so: std::weak_ptr<std::string> w; std::shared_ptr<std::string> s = std::make_shared<std::string>("test"); w = s; if (auto p = w.lock()) std::cout << *p << "\n"; else std::cout << "Empty"; If I wanted to use the ternary operator to short hand this, it would seem that this: std::cout << (auto p = w.lock()) ? *p : "Empty"; would be valid code, but this does not compile. Is it possible to use this approach with the ternary operator?
auto p = w.lock() is not an assignment. It's a declaration of a variable. You can declare a variable in the condition of an if statement, but you cannot declare variables within a conditional expression. You can write: auto p = w.lock(); std::cout << ( p ? *p : "Empty" );
69,412,746
69,419,780
Matlab C++ integration, what is libting?
I have written some c++ code that I want to integrate with matlab in the following method https://www.mathworks.com/help/matlab/matlab_external/publish-interface-to-shared-c-library-on-linux.html The first step: Generate Interface on Linux goes well. The second step: Define Missing Constructs is not really necessary, my example is so simple it can do this automatically Build Interface is where I get the problem. Here is my matlab code: clc; clibgen.generateLibraryDefinition(fullfile("testing.h"),... "Libraries", fullfile("testing.so"),... "PackageName", "integrationTest",... "ReturnCArrays",false,... % treat output as MATLAB arrays "Verbose",true) defineintegrationTest; summary(defineintegrationTest) build(defineintegrationTest) The last line, build(defineintegrationTest) is what throws the error. Here is the full output: Using g++ compiler. Generated definition file defineintegrationTest.mlx and data file 'integrationTestData.xml' contain definitions for 1 constructs supported by MATLAB. Build using build(defineintegrationTest). MATLAB Interface to integrationTest Library Functions int32 clib.integrationTest.addingNumbers(int32,int32) Building interface file 'integrationTestInterface.so'. Error using clibgen.internal.buildHelper (line 62) Build failed with error: '/usr/bin/ld: cannot find -lting collect2: error: ld returned 1 exit status '. Error in clibgen.LibraryDefinition/build (line 1297) clibgen.internal.buildHelper(obj, obj.LibraryInterface, '', directBuild); Error in myIntegrationTest (line 11) build(defineintegrationTest) The main part of the error seems to be the cannot find -lting collect2: error: ld returned 1 exit status ' part. I made testing.so using the lines: g++ -o testing.o -O3 testing.cpp g++ -shared -o testing.so testing.o My testing examples here are super simple. Here's the cpp file. #include "testing.h" int addingNumbers(int a, int b){ return a + b; } And here's the header file #ifndef TESTING_ /* Include guard */ #define TESTING_ int addingNumbers(int a, int b); #endif I also tried to use g++ to make a shared library with the -lting flag, and got the same error. g++ -shared -o testing.so testing.o -lting Does anyone know what this library is or where I can install it? I have gotten google results that actually return 0 results while looking for things about -lting or libting or matlab ting.
It turns out that you should make the first three letters of your .so file lib. So I changed testing.so to libtesting.so and reran the same steps and it worked. Thank you for your help Cris Luengo, who answered this question.
69,412,907
69,412,948
Why does the compiler say this macro function needs a closing parenthesis?
The code is below. The compiler says "Expected a )", but I do not get it: ( and ) are matching. What did I do wrong? #define CR_SUCCESS 0 #define EXIT_IF_FAILS(varResult, callString) \ (\ varResult = callString; \ if(varResult != CR_SUCCESS) \ { \ return -1; \ } \ ) int testFunction(int a, int b) { return -1; } int main() { int result; EXIT_IF_FAILS(result, testFunction(1, 2)); }
Expanding, your main looks like int main() { int result; ( result = testFunction(1, 2); if(result != CR_SUCCESS) { return -1; } ) } This is invalid, since you cannot have parentheses around statements. For some things you might do when you want a macro which acts like a statement, see the C++ FAQ "What should be done with macros that have multiple lines?"
69,412,970
69,440,589
arrays of arrays writing to a file using rapidjson
Using below function I am writing vector of vector into a file and getting this: [[[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]]] However I want the output to look like this: [[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]] Code: void resultToJson(std::vector<std::vector<int>> &result, const char *fileName) { rapidjson::Document d; rapidjson::Document::AllocatorType &allocator = d.GetAllocator(); rapidjson::Value globalArray(rapidjson::kArrayType); std::vector<std::vector<int>>::iterator row; for (row = result.begin(); row != result.end(); row++) { std::vector<int>::iterator col; rapidjson::Value myArray(rapidjson::kArrayType); for (col = row->begin(); col != row->end(); col++) { myArray.PushBack(*col, allocator); } globalArray.PushBack(myArray, allocator); } d.SetArray().PushBack(globalArray, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); std::ofstream of(fileName); of << buffer.GetString(); if (!of.good()) throw std::runtime_error("Can't write the JSON string to the file!"); } I couldn't find out a way to do this. Any help would be appreciated.
You have globalArray to which you push a single element. It is not needed. Eliminating it and using d.SetArray().PushBack(myArray, allocator); instead should work just fine, and avoid creation of an extra level in the JSON tree.
69,413,174
69,413,264
How to print in a file and with cout with same function in c++?
I have a simple print function like this: template <class T> void ArrayList<T>::print() const { //store array contents to text file for (int i = 0; i < length; i++) { cout << *(list + i) << endl; } } It prints the value in the array. I want it to work like this: If the ArrayList ‘print’ function is called with no argument then it will write the information to the standard output stream. However, a variable of type ‘ofstream’ is then it should write the information to a file. I changed the function to write in a file but now if I don't pass the argument then it shows an error. Is there a way to make it both write in a file (if the argument passed) and standard print (if no argument)? template <class T> void ArrayList<T>::print(std::ofstream& os) const { //store array contents to text file for (int i = 0; i < length; i++) { os << *(list + i) << endl; } }
What you can do here is take an std::ostream& as your parameter. Then the print function doesn't care where the data is getting output to. static void print( std::ostream& os ) { os << "I don't care where this data is going\n"; } int main( ) { // Pass it std::cout. print( std::cout ); // Or pass it an std::fstream. std::fstream file{ "/Path/To/File/File.txt", std::ios::out }; print( file ); }
69,413,986
69,414,523
Parameter pack extraction
I have a function2, which can be called with or without a second argument == char. If so, I want to modify that char-Argument. Given void function1_caller(int x) { char ws=7; function2_modifyArg(x, ws); } This works: template <typename ... WS> void function2_modifyArg(int x, WS ... ws) { function3_end(x, ws ...); } simply put in parenthesis, doesn't work already: template <typename ... WS> void function2_modifyArg(int x, WS ... ws) { function3_end(x, (ws ... )); } This results in the following error: Syntax error: unexpected token '...', expected declaration In fact here I'd like to modify the argument, but of course I get the same Syntax error: unexpected token '...', expected declaration template <typename ... WS> void function2_modifyArg(int x, WS ... ws) { function3_end(x, (ws ... / 3)); } template <typename ... WS> void function3_end(int x, WS ... ws) {};
You don't need the parenthesis you just need to put the operation you want to do before the pack expansion: template <typename ... WS> void function2_modifyArg(int x, WS ... ws) { function3_end(x, ws / 3 ...); }
69,414,070
69,414,099
Why does size of array differ in main and other function?
I am not new to C++, but today I found that the size of the array is different in the main function and in other functions. Why is that? I suppose it's something related to pointers. #include<bits/stdc++.h> using namespace std; void func(int arr[]){ cout<<"func size: "<<sizeof(arr)<<"\n"; } int main(){ int arr[5]; cout<<sizeof(arr)<<"\n"; func(arr); return 0; } You can test this code to see the difference.
Because the array is decayed to a pointer What is array to pointer decay?. you can pass the array by reference to see the same size, as follows #include <iostream> template <class T, size_t n> void func(T (&arr)[n]) { std::cout << "func size: " << sizeof(arr) << "\n"; } int main() { int arr[5]; std::cout << sizeof(arr) << "\n"; func(arr); } Demo And see Why is "using namespace std;" considered bad practice? and Why should I not #include <bits/stdc++.h>?
69,414,335
69,414,376
How do I act upon a class in C++ from a class method?
In the realm of psuedocode, if I wanted to act upon something in Java, I could go class Dragon { //some code here defining what a Dragon is } class Knight { //some code here defining what a Knight is public void Attack(Dragon dragon) { // <----- specifically this //define an attack } } class Main { public static void main (String[] args) { Knight knight = new Knight; Dragon dragon1 = new Dragon; Dragon dragon2 = new Dragon; knight.Attack(dragon1); // <----- specifically this } } How would I do this in c++? When I try to use the following code, I'm told that error: unknown type name 'Dragon' #include <iostream> #include <list> #include <string> class IObserver { public: virtual ~IObserver(){}; virtual void Update(const std::string &message_from_subject) = 0; }; class ISubject { public: virtual ~ISubject(){}; virtual void Attach(IObserver *observer) = 0; virtual void Notify() = 0; }; class Knight : public ISubject { public: void Attach(IObserver *observer) override { list_observer_.push_back(observer); } void Notify() override { std::list<IObserver *>::iterator iterator = list_observer_.begin(); while (iterator != list_observer_.end()) { (*iterator)->Update(message_); ++iterator; } } void CreateMessage(std::string message = "Empty") { this->message_ = message; Notify(); } void Attack(Dragon dragon) { //<-----------right here this->message_ = "I am attacking"; Notify(); std::cout << "todo\n"; } private: std::list<IObserver *> list_observer_; std::string message_; }; class Dragon : public ISubject { public: void Attach(IObserver *observer) override { list_observer_.push_back(observer); } void Notify() override { std::list<IObserver *>::iterator iterator = list_observer_.begin(); while (iterator != list_observer_.end()) { (*iterator)->Update(message_); ++iterator; } } void CreateMessage(std::string message = "Empty") { this->message_ = message; Notify(); } void CallForHelp() { this->message_ = "I'm under attack"; Notify(); std::cout << "todo\n"; } private: std::list<IObserver *> list_observer_; std::string message_; }; class GameManager : public IObserver { public: GameManager(Knight &subject) : subject_(subject) { this->subject_.Attach(this); std::cout << "GameManager " << ++GameManager::static_number_ << " online\n"; this->number_ = GameManager::static_number_; } void Update(const std::string &message_from_subject) override { message_from_subject_ = message_from_subject; PrintInfo(); } void PrintInfo() { std::cout << "GameManager " << this->number_ << ": a new message is available --> " << this->message_from_subject_ << "\n"; } private: std::string message_from_subject_; Knight &subject_; static int static_number_; int number_; }; int GameManager::static_number_ = 0; void ClientCode() { Knight *knight = new Knight; GameManager *gameManager = new GameManager(*knight); knight->CreateMessage("I exist"); knight->CreateMessage("Going to attack dragon1"); knight->Attack(); } int main() { ClientCode(); return 0; } I must be missing something but I feel like this should work. I'm not super informed on abstract classes or C++ but there should be an equivalent action that's able to be made, right?
In C++, when a class or any other identifier is declared below, as far as the compiler knows it is undeclared. You will need to declare Knight below Dragon. Also notice the distinction between passing a class as an argument by value, reference or pointer. In most cases you will want to pass a class by reference such as Dragon& dragon instead of value such as Dragon dragon. This prevents unnecessary copies.
69,414,350
69,414,403
Why is my string not printing in a function?
Here is the code: #include<iostream> using namespace std; int lengthOfLastWord(string s) { int i,j,n=0; for(i=0;s[i]!=0;i++){ n++; } string s1; for(i=n,j=0;s[i]!=' ';i--,j++){ s1[j]=s[i]; } cout<<s1; }; int main(){ string s; getline(cin,s); lengthOfLastWord(s); } What is the problem with the string s1? If s1 is in the for loop, s1 prints successfully.
First and foremost, your lengthOfLastWord() function doesn't return anything so have its return type be void: void lengthOfLastWord(string const& s) { // ^^^^^^ Preferably use const reference here to avoid making unnecessary copies at each invocation to 'lengthOfLastWord()' /* ... */ } Now, the real problem is that you never initialized s1 before accessing it with s1[j] which leads to Undefined Behavior. So, to fix your problem, just replace this line: string s1; with this: string s1(n, '\0'); Demo Alternatively, you can use std::string::push_back(): // ... string s1; for(i = n; s[i] != ' '; i--) s1.push_back(s[i]); cout << s1; Demo using std::string::push_back
69,414,827
69,415,000
How to terminate my cpp program after 3 attempts of asking for pin?
My program should terminate after 3 wrong attempts but mine would still proceed to the menu even if the attempts were wrong. I've tried using return 0, but I didn't know why it still not worked. Is there any way to fix my program? #include <iostream> #include <string> using namespace std; int main () { string pin; int attemptCount = 0; while ( attemptCount < 3 ) { cout << "Enter pin: " << endl; cin >> pin; if ( pin != "1234") { cout << "Pin is incorrect." << "\n" << endl; attemptCount++; } else if ( attemptCount = 0 ) { cout << "3 pins were unsuccessful."; return 0; } else { cout << "Access granted." << endl; break; } } int a, b, c; char choice; cout<<"\n\n---Area of a polygon---\n[A] Triangle\n[B] Square\n[C] Rectangle\n[D] Exit \n"; cout<<"Enter choice: \n"; cin>>choice; switch(choice){ case 'a': case 'A': int square_area, square_side; float base, height, area1; cout << "\nEnter length of base and height of Triangle: "; cin >> base >> height; area1 = (base * height) / 2; cout << "Area of Triangle: " << area1 << endl; break; case 'b': case 'B': cout<<"\nEnter the side of the square: "; cin >> square_side; square_area = square_side * square_side; cout << "Area of Square: " << square_area << endl; break; case 'c': case 'C': int length, width, area; cout << "\nEnter the Length of Rectangle : "; cin>>length; cout << "\nEnter the Width of Rectangle : "; cin>>width; area = length * width; cout << "\nArea of Rectangle : " << area; break; case 'd': case 'D': break; ; } return 0; } My program should terminate after 3 wrong attempts but mine would still proceed to the menu even if the attempts were wrong. I've tried using return 0, but I didn't know why it still not worked. Is there any way to fix my program?
first you have to do change this like that if ( attemptCount == 2) { cout << "3 pins were unsuccessful."; return 0; } else if ( pin != "1234" ) { cout << "Pin is incorrect." << "\n" << endl; attemptCount++; } what happening here you are checking first pin is correct or not if it goes there it increment the attemptCount and back to loop and you have to write your menu and all the statements in else condition and remove the break from it. Like that else { cout << "Access granted." << endl; int a, b, c; char choice; cout<<"\n\n---Area of a polygon---\n[A] Triangle\n[B] Square\n[C] Rectangle\n[D] Exit \n"; cout<<"Enter choice: \n"; cin>>choice; switch(choice){ case 'a': case 'A': int square_area, square_side; float base, height, area1; cout << "\nEnter length of base and height of Triangle: "; cin >> base >> height; area1 = (base * height) / 2; cout << "Area of Triangle: " << area1 << endl; break; case 'b': case 'B': cout<<"\nEnter the side of the square: "; cin >> square_side; square_area = square_side * square_side; cout << "Area of Square: " << square_area << endl; break; case 'c': case 'C': int length, width, area; cout << "\nEnter the Length of Rectangle : "; cin>>length; cout << "\nEnter the Width of Rectangle : "; cin>>width; area = length * width; cout << "\nArea of Rectangle : " << area; break; case 'd': case 'D': break; } } Now your whole code look like this #include <iostream> #include <string> using namespace std; int main () { string pin; int attemptCount = 0; while ( attemptCount < 3 ) { cout << "Enter pin: " << endl; cin >> pin; if ( attemptCount == 2) { cout << "3 pins were unsuccessful."; return 0; } else if ( pin != "1234" ) { cout << "Pin is incorrect." << "\n" << endl; attemptCount++; } else { cout << "Access granted." << endl; int a, b, c; char choice; cout<<"\n\n---Area of a polygon---\n[A] Triangle\n[B] Square\n[C] Rectangle\n[D] Exit \n"; cout<<"Enter choice: \n"; cin>>choice; switch(choice){ case 'a': case 'A': int square_area, square_side; float base, height, area1; cout << "\nEnter length of base and height of Triangle: "; cin >> base >> height; area1 = (base * height) / 2; cout << "Area of Triangle: " << area1 << endl; break; case 'b': case 'B': cout<<"\nEnter the side of the square: "; cin >> square_side; square_area = square_side * square_side; cout << "Area of Square: " << square_area << endl; break; case 'c': case 'C': int length, width, area; cout << "\nEnter the Length of Rectangle : "; cin>>length; cout << "\nEnter the Width of Rectangle : "; cin>>width; area = length * width; cout << "\nArea of Rectangle : " << area; break; case 'd': case 'D': break; } } } return 0; }
69,414,958
69,415,093
defaulting to using braces enclosing each case in switch statements in Visual Studio Code
In C++ or C#, it's generally a good practice to enclose each case within curly braces (e.g., see C# switch statement with curly braces for each case/default block within the switch statement?). But Visual Studio Code defaults to creating a template that leaves them out. What UI preferences can I change so that they are included by default? Edit: I am not interested in a debate about whether adding curly braces should always be done or not, but rather knowing how to change VS Code's UI for this context.
You should add a snippet by yourself. Select Command palette (F1) -> Preferences: Configure User Snippets -> C++ and add the following code. "switch2": { "prefix": "switch2", "body": "switch (${1:expression}) {\n\tcase ${2:/* constant-expression */}: {\n\t\t${3:/* code */}\n\t\tbreak;\n\t}\n\tdefault: {\n\t\tbreak;\n\t}\n}" }
69,415,046
69,415,600
Clang issues -Wunused-value depending on whether the code is called from a macro
I use a special assertion macros called CHECK. It is implemented like this: #define CHECK(condition) check(condition).ok ? std::cerr : std::cerr The user can choose to provide additional information that is printed if the assertion fails: CHECK(a.ok()); CHECK(a.ok()) << a.to_string(); Notice the ternary operator in macro definition. It ensures that a.to_string() is executed only when the assertion fails. So far so good. I've been using this (and other similar) macros for a long time without any problems. But recently I found that clang issues “expression result unused [-Wunused-value]” warning regarding the second std::cerr if CHECK is used inside another macro: #define DO(code) do { code } while(0) int main() { do { CHECK(2 * 2 == 4); } while(0); // no warning DO( CHECK(2 * 2 == 4); ); // warning } Full example: https://godbolt.org/z/5bfnEGqsn. This makes no sense to me. Why would this diagnostic depend on whether the code was expanded from a macro or not? GCC issues no warnings in either case. Two questions: Is there any reason for such behavior or should I file this as clang bug? How can I suppress this without disabling “-Wunused-value” altogether? I've tried [[maybe_unused]] and __attribute__((unused)) but they don't seem to work on statements.
I don't think that this is a good solution what I suggest here but you could change your code so that you will always use your std::cerr, by changing your check(condition).ok ? std::cerr : std::cerr to check(condition).ok ? std::cerr << "" : std::cerr << "": #include <iostream> struct CheckResult { CheckResult(bool ok_arg) : ok(ok_arg) {} ~CheckResult() { if (!ok) abort(); } bool ok; }; inline CheckResult check(bool ok) { if (!ok) std::cerr << "Assertion failed!\n"; return CheckResult(ok); } #define CHECK(condition) \ check(condition).ok ? std::cerr << "" : std::cerr << "" #define DO(code) \ do { code } while(0) int main() { do { CHECK(2 * 2 == 4); } while(0); DO( CHECK(2 * 2 == 4); ); } Another thing you could do is to use a function that returns that std::cerr: #include <iostream> struct CheckResult { CheckResult(bool ok_arg) : ok(ok_arg) {} ~CheckResult() { if (!ok) abort(); } bool ok; }; inline CheckResult check(bool ok) { if (!ok) std::cerr << "Assertion failed!\n"; return CheckResult(ok); } [[maybe_unused]] inline std::ostream & get_ostream() { return std::cerr; } #define CHECK(condition) \ check(condition).ok ? get_ostream() : get_ostream() #define DO(code) \ do { code } while(0) int main() { do { CHECK(2 * 2 == 4); } while(0); DO( CHECK(2 * 2 == 4); ); } The [[maybe_unused]] here is not about the returned value but about the function in case that you change your code so that it is not used under certain conditions (maybe not needed here). My major concern about your approach is this statement: Notice the ternary operator in macro definition. It ensures that a.to_string() is executed only when the assertion fails. Without reading the documentation and just looking at CHECK(a.ok()) << a.to_string(); on one would assume that a.to_string() will only be executed if the assertion fails. For a standpoint of code review or collaboration, this can be really problematic.
69,415,139
69,415,346
reinterpret_cast between char* and std::byte*
I'm reading type aliasing rules but can't figure out if this code has UB in it: std::vector<std::byte> vec = {std::byte{'a'}, std::byte{'b'}}; auto sv = std::string_view(reinterpret_cast<char*>(vec.data()), vec.size()); std::cout << sv << '\n'; I'm fairly sure it does not, but I often get surprised by C++. Is reinterpret_cast between char*, unsigned char* and std::byte* always allowed? Additionally, is addition of const legal in such cast, e.g: std::array<char, 2> arr = {'a', 'b'}; auto* p = reinterpret_cast<const std::byte*>(arr.data()); Again, I suspect it is legal since it says AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType but I would like to be sure with reinterpret_casting once and for all.
The code is ok. char* and std::byte* are allowed by the standard to alias any pointer type. (Be careful as the reverse is not true). ([basic.types]/2): For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]).43 If the content of that array is copied back into the object, the object shall subsequently hold its original value. ([basic.lval]/8.8): If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: a char, unsigned char, or std​::​byte type. And yes you can add const.
69,415,271
69,415,622
I got 'fatal error: opencv2/core.hpp: No such file or directory' but there is it
I'm trying to use opencv 4.x library on C++. When I run a test code on vscode, the error occured 'fatal error: opencv2/core.hpp: No such file or directory' But there is the file in the directory. I checked vscode's json file and I set the include path correctly. I don't know why. Can you tell me anything i missed? { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:\\minGW+opencv\\opencv\\build\\include" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.18362.0", "compilerPath": "C:/minGW+opencv/minGW/bin/g++.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-gcc-x64" } ], "version": 4 } I have that header file in the right path.
C:\\minGW+opencv\\opencv\\build\\include is the wrong include path for your project. (it only contains cmake scripts, no actual headers) assuming you did a proper mingw32-make install before (well, did you ??), it should be: C:\\minGW+opencv\\opencv\\build\\install\\include
69,415,361
69,415,571
Can requires-expression in C++20 be of type implicitly convertible to bool?
In the following example the requires-expression of second f-function overload has the type std::integral_constant<bool,true>, which is implicitly convertible to bool: #include <type_traits> struct S { static constexpr bool valid = true; }; template<typename T> int f() { return 1; } template<typename T> int f() requires( std::bool_constant< T::valid >() ) { return 2; } int main() { return f<S>(); } One can observe that GCC rejects the program due to the type is not precisely bool, but Clang accepts, but selects the other overload int f() { return 1; }. Demo: https://gcc.godbolt.org/z/nf65zrxoK Which compiler is correct here?
I believe GCC is correct—the type must be bool exactly per [temp.constr.atomic]/3 (note that E here is std::bool_constant< T::valid >()): To determine if an atomic constraint is satisfied, the parameter mapping and template arguments are first substituted into its expression. If substitution results in an invalid type or expression, the constraint is not satisfied. Otherwise, the lvalue-to-rvalue conversion is performed if necessary, and E shall be a constant expression of type bool. The constraint is satisfied if and only if evaluation of E results in true. If, at different points in the program, the satisfaction result is different for identical atomic constraints and template arguments, the program is ill-formed, no diagnostic required. [ Example: template<typename T> concept C = sizeof(T) == 4 && !true; // requires atomic constraints sizeof(T) == 4 and !true template<typename T> struct S { constexpr operator bool() const { return true; } }; template<typename T> requires (S<T>{}) void f(T); // #1 void f(int); // #2 void g() { f(0); // error: expression S<int>{} does not have type bool } // while checking satisfaction of deduced arguments of #1; // call is ill-formed even though #2 is a better match — end example ]
69,415,408
69,418,230
BOOST C++ get rotation or orientation of a linestring
i'm trying to find the rotation of a linestring. Basically i have a linestring like typedef boost::geometry::model::linestring<point_type> linestring_type; linestring_type line; line.push_back(point_type(xx1,yy1)); line.push_back(point_type(xx2,yy2)); and i would like to know if we can know the rotation of a linestring. Basically, if the linestring point in direction of the north, i want to know.
You can lookup the arc-tangent in a "wind-rose" table. The raw output will be [-π,+π] so assume that we want to divide that in 8 segments: double constexpr segment = 0.25; struct { double bound; char const* name; bool operator<(double index) const { return index > bound; } } constexpr table[] = { {-5*segment, "(none)"}, // for safety {-4*segment, "W"}, {-3*segment, "SW"}, {-2*segment, "S"}, {-1*segment, "SE"}, { 0*segment, "N"}, {+1*segment, "NE"}, {+2*segment, "E"}, {+3*segment, "NW"}, {+4*segment, "W"}, }; Now we can calculate the arctangent and scale it to be [-1,+1] on that lookup table: #include <boost/geometry.hpp> #include <boost/geometry/geometries/linestring.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <iostream> #include <string_view> namespace bg = boost::geometry; using point_type = bg::model::d2::point_xy<int>; using linestring_type = bg::model::linestring<point_type>; std::string_view orientation(linestring_type const& ls) { double constexpr segment = 0.25; struct { double bound; char const* name; bool operator<(double index) const { return index > bound; } } constexpr table[] = { {-5*segment, "(none)"}, // for safety {-4*segment, "W"}, {-3*segment, "SW"}, {-2*segment, "S"}, {-1*segment, "SE"}, { 0*segment, "N"}, {+1*segment, "NE"}, {+2*segment, "E"}, {+3*segment, "NW"}, {+4*segment, "W"}, }; assert(ls.size() == 2); auto delta = ls.back(); bg::subtract_point(delta, ls.front()); auto frac = atan2(delta.y(), delta.x()) / M_PI; std::cout << " [DEBUG " << frac << ", " << (180 * frac) << "°] "; return std::lower_bound( // std::begin(table), std::end(table), frac - (segment / 2)) ->name; } int main() { for (auto pt : { point_type // {0, 0}, {1, 0}, {1, 1}, {0, 1}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, }) { linestring_type line { {0,0}, pt }; std::cout << bg::wkt(line) << " " << orientation(line) << "\n"; } } Note the subtle-ish - segment / 2 to achieve "nearest" rounding. Live On Coliru Prints LINESTRING(0 0,0 0) [DEBUG 0, 0°] N LINESTRING(0 0,1 0) [DEBUG 0, 0°] N LINESTRING(0 0,1 1) [DEBUG 0.25, 45°] NE LINESTRING(0 0,0 1) [DEBUG 0.5, 90°] E LINESTRING(0 0,1 -1) [DEBUG -0.25, -45°] SE LINESTRING(0 0,0 -1) [DEBUG -0.5, -90°] S LINESTRING(0 0,-1 -1) [DEBUG -0.75, -135°] SW LINESTRING(0 0,-1 0) [DEBUG 1, 180°] W LINESTRING(0 0,-1 1) [DEBUG 0.75, 135°] NW Alternative Test An alternative test rotates a unit vector (NORTH) over 16 different angles: Live On Coliru linestring_type const NORTH{{0, 0}, {0, 1'000}}; for (double angle = 0; angle <= 360; angle += 360.0 / 16) { linestring_type ls; bg::transform(NORTH, ls, rotation(angle)); std::cout << bg::wkt(ls) << " " << orientation(ls) << "\n"; } Prints LINESTRING(0 0,0 1000) [DEBUG 0.5, 90°] E LINESTRING(0 0,382 923) [DEBUG 0.375094, 67.5169°] E LINESTRING(0 0,707 707) [DEBUG 0.25, 45°] NE LINESTRING(0 0,923 382) [DEBUG 0.124906, 22.4831°] N LINESTRING(0 0,1000 0) [DEBUG 0, 0°] N LINESTRING(0 0,923 -382) [DEBUG -0.124906, -22.4831°] N LINESTRING(0 0,707 -707) [DEBUG -0.25, -45°] SE LINESTRING(0 0,382 -923) [DEBUG -0.375094, -67.5169°] S LINESTRING(0 0,0 -1000) [DEBUG -0.5, -90°] S LINESTRING(0 0,-382 -923) [DEBUG -0.624906, -112.483°] S LINESTRING(0 0,-707 -707) [DEBUG -0.75, -135°] SW LINESTRING(0 0,-923 -382) [DEBUG -0.875094, -157.517°] W LINESTRING(0 0,-1000 0) [DEBUG 1, 180°] W LINESTRING(0 0,-923 382) [DEBUG 0.875094, 157.517°] W LINESTRING(0 0,-707 707) [DEBUG 0.75, 135°] NW LINESTRING(0 0,-382 923) [DEBUG 0.624906, 112.483°] E LINESTRING(0 0,0 1000) [DEBUG 0.5, 90°] E
69,415,801
69,415,849
Why is my exception sliced to base class if I catch it with reference to base class?
So I've written a small C++ class as follows: class bad_hmean : public std::logic_error { const char *nature_; char *what_; public: bad_hmean(const char *fname); ~bad_hmean() { delete[] what_; } const char *what() { return what_; } }; inline bad_hmean::bad_hmean(const char *fname):nature_("BAD HARMONIC MEAN VALUES"), std::logic_error("BAD HARMONIC MEAN VALUES") { int len = strlen(fname) + strlen(nature_)+3; what_ = new char [len]; strcpy(what_, fname); strcat(what_, ": "); strcat(what_, nature_); } And I've tried testing it inside the following main: void fun1() { throw bad_hmean(__func__); } int main() { try { fun1(); } catch(std::exception& e) { std::cout << e.what(); } } And when I run it I encounter one problem that I can't wrap my head around. Even though I throw the exception by value and catch it by reference, slicing still happens because the output of my code is: BAD HARMONIC MEAN VALUES. But if I catch the exception as a reference to bad_hmean the output is what I intended it to be: fun1: BAD HARMONIC MEAN VALUES. Does anyone know why does this happen?
bad_hmean doesn't override what() correctly. It should match the signature of the base class what as: const char *what() const noexcept { return what_; } // ^^^^^ ^^^^^^^^ BTW: It's better to use override specifier (since C++11) to ensure that the function is overriding a virtual function from a base class. E.g. const char *what() const noexcept override { return what_; }
69,416,291
69,416,342
Why the array is not printing without the pointer? Is the following code correct?
I'm new to coding. I'm working on pointers. The following code is correct, means there is no syntax error in it but still the second while loop is not printing anything. #include<stdio.h> #include<stdlib.h> int main(){ int arr[]={10,20,30}; int *ptr=arr; int i=0; //Printing Array with Pointer while(i<3) { printf("%d\n",*ptr); ptr++; i++; } //Printing Array without Pointer printf("\n\n"); while(i<3) { printf("%d\n",*(arr+i)); i++; } return 0; }
Write i = 0; just above the while loop. After completing for loop then value i=3 so you have to again i=0 so that while loop start printing Hope you will get it
69,416,636
69,417,510
C++ pmr polymorphic memory resources choice supports to release as needed
My program is a daemon and runs for a long time. Only some of the time it will needs a lot of memory resource. I want to increase my program performance by increasing memory locality. And PMR seems like a good tool for this purpose. However, it seems that the memory resources provided by the standard does not return the memory to upstream when there are lots of memory currently not used. (i.e. synchronized_pool_resource, unsynchronized_pool_resource, monotonic_buffer_resource) I want that my program can use less memory when the load is not high. (kinds of like calling malloc_trim when needed) Is there a memory resource that will only cache small amount of currenly un-used memory, and return the rest to upstream.
A memory resource can be written to do whatever you want. However, since what you've described (returning memory that is unused) is what the default allocator does (and is one of the main reasons to use it), there wasn't much point in adding more standard library memory resources that do this. Most of the defined memory resources are all about not returning unused memory, because returning and reallocating memory is expensive. They provide different strategies for keeping that memory accessible, so that later allocation calls are as fast as possible. That is, their whole point is to avoid the cost of allocating memory from the heap. So you'll have to write a resource with the functionality you're looking for.
69,416,724
69,417,250
JsonCPP throwing a logic error:requires objectValue or nullValue
void exp::example(std::string &a, std::string &b) { if (m_root.isObject() && m_root.isMember(a)) { if (m_root[a].isMember(b)) { m_root[a].append(b); } } else { m_root[a] = Json::arrayValue; m_root[a].append(b); } } (m_root is defind in the hpp) When I'm running this code I get the logic error: in Json::Value::find(key, end, found): requires objectValue or nullValue. I found out that I got this error from this if: if (m_root[a].isMember(b)) I don't understand why do I get this error there, I used the same function in the if above him and I didn't get this error. P.S the function is working until it enter the nested if, example: a b m_root "hey" "a1" {"hey":["a1"]} "bye" "a2" {"hey":["a1"], "bye":["b1"]} "cye" "a3" {"hey":["a1"], "bye":["b1"], "cye":["a3"]} "hey" "a4" error: in Json::Value::find(key, end, found): requires objectValue or nullValue I get the error only in the 4th call. I appreciate your help!
On the 4th iteration you access the m_root["hey"] object which is of type arrayValue. Those values are not supported by the isMember method. You'll have to find the value in the array in another way. I suggest iterating over the array, in something like: bool is_inside_array(const Json::Value &json_array, const string& value_to_find) { for (const Json::Value& array_value: json_array) { if (array_value.asString() == value_to_find) { return true; } } return false; } Then replace the inner if with: if (is_inside_array(m_root[a], b))
69,416,805
69,417,190
Why does the same algorithm result in different outputs in C++ & Python?
I am running a small code in which there are periodic boundary conditions i.e.,for point 0 the left point is the last point and for the last point zeroth point is the right point. When I run the same code in Python and C++, the answer I am getting is very different. Python Code import numpy as np c= [0.467894,0.5134679,0.5123,0.476489,0.499764,0.564578] n= len(c) Δx= 1.0 A= 1.0 M = 1.0 K=1.0 Δt= 0.05 def delf(comp): ans = 2*A*comp*(1-comp)*(1-2*comp) return ans def lap(e,v,w): laplace = (w -2*v+ e) / (Δx**2) return laplace for t in range(1000000): μ = np.zeros(n) for i in range(n): ans1= delf(c[i]) east= i+1 west= i-1 if i==0: west= i-1+n if i== (n-1): east= i+1-n ans2= lap(c[east], c[i], c[west]) μ[i] = ans1 - K* ans2 dc_dt= np.zeros(n) for j in range(n): east= j+1 west= j-1 if j==0: west= j-1+n if j== (n-1): east= j+1-n ans= lap(μ[east], μ[j], μ[west]) dc_dt[j] = M* ans for p in range(n): c[p] = c[p] + Δt * dc_dt[p] print(c) The output in Python 3.7.6 version is [0.5057488166795907, 0.5057488166581386, 0.5057488166452102, 0.5057488166537337, 0.5057488166751858, 0.5057488166881142] C++ Code #include <iostream> using namespace std ; const float dx =1.0; const float dt =0.05; const float A= 1.0; const float M=1.0; const float K=1.0; const int n = 6 ; float delf(float comp){ float answer = 0.0; answer= 2 * A* comp * (1-comp) * (1-2*comp); return answer; } float lap(float e, float v, float w){ float laplacian= 0.0 ; laplacian = (e - 2*v +w) / (dx *dx); return laplacian; } int main(){ float c[n]= {0.467894,0.5134679,0.5123,0.476489,0.499764,0.564578}; for(int t=0; t<50;++t){ float mu[n]; for(int k=0; k<n; ++k){ int east, west =0 ; float ans1,ans2 = 0; ans1= delf(c[k]); if (k ==0){ west = k-1+n; } else{ west = k-1; } if (k== (n-1)) { east = k+1-n; } else{ east= k+1; } ans2= lap(c[east], c[k], c[west]); mu[k] = ans1 - K*ans2; } float dc_dt[n]; for(int p=0; p<n; ++p){ float ans3= 0; int east, west =0 ; if (p ==0){ west = p-1+n; } else{ west = p-1;} if (p== (n-1)) { east = p+1-n; } else{ east= p+1; } ans3= lap(mu[east], mu[p], mu[west]); dc_dt[p] = M* ans3; } for(int q=0; q<n; ++q){ c[q] = c[q] + dt* dc_dt[q]; } } for(int i=0; i<n; ++i){ cout<< c[i]<< " "; } return 0; } Output in C++ is 0.506677 0.504968 0.50404 0.50482 0.506528 0.507457 When I am iterating for small steps say t<1000 there is no significant difference in outputs but I am supposed to do this calculation for large number of iterations (in order of 10^7) and here the difference in output is very large.
I took your code, added the missing closing bracket of the large "for" loop and also changed the length from "50" to "1000000" as in the python version. Then I replaced all "float" with "double" and the resulting output is: 0.505749 0.505749 0.505749 0.505749 0.505749 0.505749 Thus, of course, implementing the same code in python and in c++ gives the same result. However, the types are obviously important. For example, integers are implemented in a very very different way in python3 than in c++ or almost any other language. But here it is much simpler. Python3 "float" is a "double" in c++ by definition. See https://docs.python.org/3/library/stdtypes.html Fun fact the simplest python program that you will have major trouble to reproduce in C++ or most other languages is something like myInt=10000000000000000000000000000000345365753523466666 myInt = myInt*13 + 1 print (myInt) since python can work with arbitrary large integers (until your entire computer memory is filled). The corresponding #include <iostream> int main(){ long int myInt = 10000000000000000000000000000000345365753523466666; myInt = myInt*13 + 1; std::cout << myInt << std::endl; return 0; } will simply report warning: integer constant is too large for its type and will overflow and print a wrong result.
69,416,953
69,417,169
vector of a template class with unknown parameters
I am working on a program that has to use std::vector, while the types of elements are unknown. The std::vector can hold different types of elements. Specifically, these types are enumerated from a template class. What I want to do is something like below, #include <vector> template <size_t N> class Element{ int array[N]; }; int main(){ std::vector<Element> vec; // do something } where, class Element is the types of objects to be stored in the vector. It holds an array of an arbitrary size. The vector stores some Elements objects with unknown paremter N. One solution I found is something like below, since the values of N are known at compilation time. std::vector<std::variant<Element<1>, Element<2>, Element<3> > vec; But it would be tricky as I have to enumerate all of them, and the application changes a lot. I know this simple example can be resolved through dynamic memory allocation, but this is just an example, the program is much more complex. Is there a better solution for this?
I could suggest two approaches for this. Ditching Templates You could ditch the template parameter in your Element class and have it contain a std::vector whose size is set upon construction and never changed. Something like this: class Element { public: Element(std::size_t size) : m_vector(size) {}; private: std::vector<int> m_vector; }; And then you use the m_vector just as if it was an array. No problems in your main() here. Using Inheritance and Polymorphism I think you refer to this when you talk about dynamic allocation, but I'll include it anyways. If you want to use templates, you can have your class Element inherit from a non-templated abstract class to have an interface of all the methods. For example: class ElementBase { public: ElementBase() = default; virtual ~ElementBase() = default; virtual std::size_t arraySize() const = 0; virtual const int *array() const = 0; }; template<std::size_t N> class Element : public ElementBase { public: Element() = default; ~Element() override = default; std::size_t arraySize() const override { return N; } const int *array() const override { return m_array; } private: int m_array[N]; }; With this approach you cannot have a std::vector<ElementBase> in your main() because the class is abstract, but you can have a std::vector<ElementBase*> or something like std::vector<std::unique_ptr<ElementBase>> if you are going to need dynamic allocation.
69,417,062
69,417,230
SFML not drawing multiple Circles
I am trying to program Tic Tac Toe in C++ with SFML. I have programmed it to draw a circle, once the left mouse button is click. Then when I click again, it redraws that circle in another position, instead of drawing another circle. I want to make it draw another circle in a different place. I draw the Circle with the sf::CircleShape SFML data type, in a function called CreateO: sf::CircleShape CreateO(float x_pos, float y_pos) { // Radius: 50px sf::CircleShape o(50); o.setFillColor(sf::Color::Black); o.setOutlineThickness(1); o.setOutlineColor(sf::Color::White); o.setPosition(x_pos, y_pos); return o; } In the Main function: sf::RenderWindow window(sf::VideoMode(900, 900), "Tic Tac Toe"); sf::Event event; bool draw_o; float x_pos, y_pos; while (window.isOpen()) { while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: switch (event.mouseButton.button) { case sf::Mouse::Right: draw_x = true; draw_o = false; x_pos = event.mouseButton.x; y_pos = event.mouseButton.y; break; default: break; } break; default: break; } } window.clear(); if (draw_o) window.draw(CreateO(x_pos, y_pos)); // Called here. window.display(); }
Analyze that part of your code: window.clear(); if (draw_o) window.draw(CreateO(x_pos, y_pos)); // Called here. window.display(); It clears the whole window and draws one circle given from the function. You only draw one circle in the game loop. To have multiple circles I recommend creating a circles vector, for example: std::vector<sf::CircleShape> circles; Than in the window.draw part you need to draw a whole vector using for-loop. And your CreateO function can just add a circle to the vector if the draw_o is true.
69,417,112
69,417,171
Using curly brackets instead of make_pair giving error
It gives no instance of overloaded function "lower_bound" matches the argument list error. I don't understand this behavior as curly brackets work fine in general while making a pair. Using curly brackets: vector<pair<int, int>> a; auto ptr = lower_bound(a.begin(), a.end(), {2, 3}); Using make pair: vector<pair<int, int>> a; auto ptr = lower_bound(a.begin(), a.end(), make_pair(2, 3));
Compiler has no possiblility to deduce {2, 3} to std::pair<int, int> in this context. See the declaration of lower_bound: template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value ); Compiler cannot assume that T should be equal to decltype(*first), because it doesn't have to be the case - it's only required that they are comparable. You need to disambiguate by actually naming the type you want to use - either by calling std::make_pair(2, 3) or by creating a temporary: std::pair{2, 3} (template arguments can be ommitted since C++17, for earlier standard you need std::pair<int, int>{2, 3} or make_pair).
69,417,797
69,418,002
C++ using switch-case return value as a condition for if statement
May one write something like this in c++: // ... if(value <= switch(secValue){ case First: return 1; case Second: return 2; return -1; }){ //... do some logic ... } // end if Thanks
Exactly this, no. But you could get close with a lambda expression. Example: #include <iostream> int main() { // dummy types and values needed for demo enum test_enum { First, Second } secValue = First; int value = 1; if (value <= [secValue]() // ^ Capture secValue in lambda expression { switch (secValue) { case First: return 1; case Second: return 2; default: // needed default case. Can't just have a stray return // in a switch return -1; } }()) // ^ immediately invoke lambda { std::cout << "Huzah!"; } }
69,418,500
69,430,909
Am I using the correct undistort routine? Is photo wide-angle or fisheye?
I am experimenting with undistorting images. I have the following image below, and using the undistort function have the result. The fisheye module doesn’t work. Is this because my image isn’t a fisheye but wide angle instead? And in either case how do I reduce the perspective distortion? FYI I have lost the specs on this lens but got its intrinsics from a calibration routine. input image: output image
The image seems just wide-angle, not fisheye. Images from fisheye camera usually have black circle borders, and they look like seeing through a round hole. See picture c) below (from OpenCV doc): The normal method of distinguishing wide-angle from fisheye is to check the FOV angle. Given the camera intrinsic parameters (the cameraMatrix and distCoeffs, from calibration routine), you can calculate a new camera intrinsic matrix with the largest FOV and no distortion by calling getOptimalNewCameraMatrix(). Then the FOV angle in x-direction (it's usually larger than y-direction) is arctan(cx/fx)+arctan((width-cx)/fx), where fx is the focal length in x-direction, cx is the x-coordinate of principal point, and width is the image width. In my experience, when FOV<80°, the Brown distortion model (k1, k2, k3, p1, p2) should be used. When 80°<FOV<140°, the Rational model (k1~k6, p1, p2) should be used. And when 140°<FOV<170°, the Fisheye model (k1, k2, k3, k4) should be used. More complex model (with more parameters) has better fitting ability, but also makes the calibration harder. The Fisheye model performs better than Rational model in very large FOV cases, because it has higher order radial parameter. But when FOV angle is not very large, Rational model is a better choice, because it has tangential parameters. The undistorted picture you provided seems fairly good. But if you care more about the precision, you should check the reprojection error, epipolar error (multi-camera), and even collineation error of the key points (checkerboard corners, circle centroids, or whatever features depending on your calibration pattern) in calibration procedure.
69,418,554
69,418,572
What is the meaning of: Base(int x): x{x}{}?
I was going through some tutorial online and found one c++ snippet which i am unable to figure out what exactly that snippet is doing. I need info like what this concept is called and why it is used. Code is: class Base{ int x; public: Base(){} Base(int x): x{x}{} // this line i am unable to understand. }; I want to know what this 5th line does and what is happening in compiler while compiling.
Lets start off with the following: the : after the corresponding constructor in the definition represents "Member Initialization". x is an integer C++ you are able to initialize primitive datatypes utilizing curly braces. See: https://www.educative.io/edpresso/declaring-a-variable-with-braces-in-cpp So therefore the x{x} is initializing x to the passed in value of the constructor. the last {} are for the constructor function call itself.
69,418,580
69,418,658
Incorrect result of arithmetic operations using LLVM-based compilers
Code: float fff = 255.0f; float a0 = (fff / 255.0f) * 100.0f; If I use LLVM-based compilers (for example Intel C++ compiler or clang) variable a0 equals 100.000008, but if I use g++ compiler I get the right result - 100. Why do LLVM-based compilers return the wrong results? How to fix that? I can't just switch to g++ 'cos this one has other errors which LLVM compilers have not.
I don't know much about LLVM compilers, it is odd that you get 100.000008 though, since you have only whole numbers in there, even in the intermediate results. However even with G++, you should still not rely to get an accurate result on floating point types calculations due to the (binary) rounding errors in the calculation, which is not the case for regular types (Note with regular types - what I mean by that is you won't have rounding but truncation - floating point part gets ignored) For example, try using 0.1 in g++, you will notice that the result is not 0.1 (if you look thru the debugger or compare 0.1f with 0.1, cout or printf will not show enough decimals) Rounding error Now if you want to compare 2 floating point numbers without looking if the absolute difference is below epsilon, I recommend you use a regular int type multiplied by a certain pre-scaler (x10^n) and then use for example, the last 3 digits of the number as the floating point part, for example instead of comparing volts, compare millivolts or microvolts, and then remove the pre-scaler at the end (recast to float/double before that) when you want to print the result.
69,418,628
69,418,800
I want to find the asymptotic complexity f(n) for the following C++ code
for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { statement; } } I observed that the outer loop runs rows time and the inner loop runs rows * cols times and the statement runs rows*cols times as well. How should I put all them together to find a general function f(n) to find the number of steps the whole code runs so that I could find its lower and upper bounds.
Complexity of this code is O(n²). But in your case complexity is counted as a number of steps inside the code. So if you have rows and columns (a matrix actually) then complexity is just a product of members rows*cols. In more detailed way its better to count all the code that is executed in your statement. But for the approximation method above is good. P.S. To see the bounds of the code its useful to look at the graphics of the functions like f(x)=x² (in your case).
69,418,652
69,614,728
Cmake undefined reference when linking with a library that uses another library built with a Python script
I am new to cmake and I am trying to port a project of mine previously built with handwritten makefiles. The executable uses a lib "core" that I build that needs the lib "xed" (written by intel). Xed uses a python script to be built so in the CMakeLists to build my lib core, I used an "add_custom_command" to build xed following the instructions provided by intel: project(libcore VERSION 0.1) find_package(Python3 COMPONENTS Interpreter REQUIRED) add_library(core STATIC src/arch.cpp src/cpu.cpp src/floppy.cpp src/pic.cpp src/pit.cpp src/ports.cpp src/ppi.cpp src/ram.cpp third-party/lib/libxed.a) add_custom_command(OUTPUT third-party/lib/libxed.a COMMAND ${CMAKE_COMMAND} -E make_directory third-party/xed/build COMMAND ${PYTHON3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/third-party/xed/xed/mfile.py --jobs=4 --build-dir=third-party/xed/build/obj --src-dir=${CMAKE_CURRENT_SOURCE_DIR}/third-party/xed/xed --static --opt=3 --prefix=third-party --install-dir=third-party/xed/kits/xed-install-date-os-cpu --no-amd --no-via --no-encoder --compress-operands install ) target_include_directories(core PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/third-party/include PUBLIC ${PROJECT_SOURCE_DIR}/include) target_precompile_headers(core PUBLIC include/pch.hpp) The problem is that when linking my final product with my lib "libcore.a" I have a lot of undefined references to the functions xed and I don't know how to fix that
There are two problems at once here: when trying to porting to cmake I tryed to mimic the way my makefiles worked. When I was thinking about how to embed libxed into my libcore I thought I was doing it in my makefiles but I wasn't, I was linking the final executable with my libcore and libxed. So the two problems are : how to embed a .a file into another how to do it with a makefile The first question is answered here. What I did is : create the first lib (in my case libxed.a) use the -x option of ar to extract the .o files of the first lib (in my case ar -x <path to libxed.a>/libxed.a create the new lib with all the .o files : ar -x *.o I have to do all these steps because the process of compiling xed is a bit odd and it's hard to know in advance which source file to include I still don't know how to mimic this behaviour in CMake in a portable way but if necessary it will be for another post on StackOverflow, so I will mark this as an accepted answer
69,418,973
70,617,938
Problem building C++ code with Eigen3 and CMake eigen3/Eigen/Core' file not found
I have simple C++ project that is organized like this: project |-- Input | |-- data.cpp <-- this file used eigen3 | |--- CmakeLists.txt |--- main.cpp |--- CmakeLists.txt Basically I am trying to create .so library from input and have main.cpp calls functions in it. CMake under project looks like this cmake_minimum_required(VERSION 3.20) project(myProj) find_package (Eigen3 REQUIRED) # Dependencies paths set(EIGEN_INC_DIR ${EIGEN3_INCLUDE_DIR}) if (TARGET Eigen3::Eigen) message("Eigen was found"). <--- I do see this message so Eigen3 package is found endif (TARGET Eigen3::Eigen) add_subdirectory(Input) <more cmake commands to link with main.cpp> CMake under Input looks like this cmake_minimum_required(VERSION 3.20) set(TARGET_LIB_INPUT input_data) set(SRC_FILES Data.cpp ) set(INC_DIRS ${EIGEN_INC_DIR} ) include_directories(${INC_DIRS}) add_library (${TARGET_LIB_INPUT} SHARED ${SRC_FILES}) target_link_libraries (${TARGET_LIB_INPUT} Eigen3::Eigen) in file data.cpp, I do the following include to eigen3 #include <eigen3/Eigen/Core> But I keep getting the error fatal error: 'eigen3/Eigen/Core' file not found I see the build command clearly include eigen directory: -I /usr/local/include/eigen3 Anybody knows what am I missing here? Thanks for help
The include directory defined in Eigen3::Eigen already includes eigen3 (e.g., /usr/include/eigen3 on Ubuntu). So you should use #include <Eigen/Core>. You can check this by: find_package(Eigen3 REQUIRED CONFIG) # checking property of the target get_target_property(inc_dir Eigen3::Eigen INTERFACE_INCLUDE_DIRECTORIES) message("[DEBUG] inc_dir: ${inc_dir}") # or checking the Eigen variable message("[DEBUG] EIGEN3_INCLUDE_DIRS: ${EIGEN3_INCLUDE_DIRS}") EIGEN3_INCLUDE_DIRS is defined in here.
69,419,141
69,419,162
Array Sorting Issues in C++
I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler. void min_sort(int array[], const unsigned int size){ for(int k = 0; k < size; k++) { for(int i = 0; i < size; i++) { if(array[i] > array[i+1]){ int temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; } } } }
You are not looping correctly. Looks like you are trying bubble sort which is: void min_sort(int array[], const unsigned int size){ for(int k = 0; k < size; k++) for(int i = k+1; i < size; i++) if(array[i] < array[k]){ int temp = array[i]; array[i] = array[k]; array[k] = temp; } }
69,419,229
69,419,278
What type do I use in the constructor to initialize a member variable defined by a nameless enum?
I have a struct containing a member variable category which I guess is of type "nameless enum". struct Token { Token(); enum { NUMBER, VARIABLE, PLUS, MINUS, PRODUCT, DIVISION, POWER, SIN, COS } category; union { char variable; double number; }; }; As you can see I also have a constructor Token(). I would like to be able to use the constructor like this: Token my_token(Token::NUMBER, 5); Instead of doing something like this: Token my_token; my_token.category = Token::NUMBER; my_token.number = 5; My question now is, what types do I use for the constructor? I tried something like this: //declaration Token(int category, int number); //definition Token(int category, int number) : category(category), number(number) {} But then when I try to initialize an object of the Token struct I get: error: invalid conversion from ‘int’ to ‘Token::<unnamed enum>’ [-fpermissive] I would like to keep the enum inside of the struct, some help with what type to use to initialize the union would also be appreciated.
Something like this? struct Token { enum EN { NUMBER, VARIABLE, PLUS, MINUS, PRODUCT, DIVISION, POWER, SIN, COS } category; union { char variable; double number; }; Token(const EN c, const double n) noexcept : category(c), number(n) {} //... Other constructors... }; int main() { Token t(Token::NUMBER, 3.4); } But I'd assign the category internally
69,419,300
69,438,924
VkKeyScanExA all TCHAR option list
I need to make a dll which will simulate a key press. For this I found out you can use an INPUT in combination with SendInput. If you know from the start which key to simulate it is easy because you can look in the list of Virtual-Key Codes and code it from the start with those keys, but I actually need to be able to change them, so I need it to be dynamically selected. In my research I found VkKeyScanExA which is quite nice, because this dll will be used in a native function and from Java I can send a String as the requested key to be pressed, but I ran into a problem, I could not find a complete list of key Strings to give it like i found with Virtual-Key Codes. Can anyone help me with a source that contains a list like the one here Virtual-Key Codes but for VkKeyScanExA? The problem is that if I use "4", it will use the digit 4, but what if the users whats to use num 4?! That is why a complete list would be really helpful.
After a lot of trial and error, and reading the source code from JavaFX, I found a better way to do it. I can simply get the int value of KeyCode from JavaFX and send that in a native function to C++ and not needing to send a String value I also don't need VkKeyScanExA at all. I'm not used to see an int value in this form 0x03, I though wVk can only get a String or an enum value, but for example 0x03 can be used as an int as well. Here is a simple example in case someone is having the same use case as me: a) In java static native void pressKey(int key); System.load(System.getProperty("user.dir") + "\\Data\\DLL\\Auto Key Press.dll"); pressKey(KeyCode.HOME.getCode()); b) In C++ JNIEXPORT void JNICALL Java_package_Test_pressKey(JNIEnv*, jclass, jint key) { INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wVk = (int)key; ip.ki.wScan = 0; ip.ki.dwFlags = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); }
69,419,349
69,419,414
reading and writing from structs with integer types only with c++ not working
I am using the below code to read and write to struct using the ifstream and ofstream classes. But for some reason I am not able to read back from the file. #pragma pack(1) struct test { int m_id; int m_size; //changed to integer test(int id, int size) :m_id(id), m_size(size) {} test() {}; }; #include <climits> int main() { ifstream in; ofstream out; out.open("binFile", ios::binary | ios::out); in.open("binFile", ios::in | ios::binary); test old(1, 7); out.write(reinterpret_cast<char*>(&old), sizeof(old)); test new(10,100); in.read(reinterpret_cast<char*>(&new), sizeof(new)); cout << new.m_size; //diplays 100 }
out.write(reinterpret_cast<char*>(&s1), sizeof(s1)); This will place the indicates bytes to std::ofstream's internal buffer, rather than the actual file. Like all efficient input/output frameworks, iostreams -- both input and output -- uses an internal buffer to efficiently read and write large chunks of data. When writing, all written data is collected in the internal buffer until there's enough to write the entire buffer to the file. Your small structure falls far short of being large enough to actually write anything to the file. You should either: Close the std::ofstream, which flushes all unwritten data to the actual file, or explicitly call flush(). Additionally, the shown code opens the same file both for reading and writing, simultaneously: out.open("binFile", ios::binary | ios::out); in.open("binFile", ios::in | ios::binary); Even if the output is properly flushed, first, depending on your operating system it may not be possible to simultaneously have the same file open for reading and writing. You should either: Use a single std::fstream, which handles both reading and writing, and then properly use flush(), and seekg(), to reposition the file stream for reading, or Close the output file first, then open the same file for reading, after it is closed for writing.
69,419,792
69,419,882
Why can't C++ infer array size with offset?
This code fails to compile template<unsigned n> void test(char const (*)[n + 1]) { } int main() { char const arr[] = "Hi"; test(&arr); } with error note: candidate template ignored: couldn't infer template argument 'n' However, if you change n + 1 to n, it compiles just fine. Why can't the compiler deduce n when it has an offset added to it?
From cppreference, in the " Non-deduced contexts" section: In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails. (...) A non-type template argument or an array bound in which a subexpression references a template parameter: template<std::size_t N> void f(std::array<int, 2 * N> a); std::array<int, 10> a; f(a); // P = std::array<int, 2 * N>, A = std::array<int, 10>: // 2 * N is non-deduced context, N cannot be deduced // note: f(std::array<int, N> a) would be able to deduce N (...) In any case, if any part of a type name is non-deduced, the entire type name is non-deduced context. (...) Because n + 1 is a subexpresion, the whole context then cannot be deduced.
69,421,509
69,421,572
What value explicit constructor brings when arguments passed are custom type?
I understand the value of keyword explicit when used in cases where there is a chance of creating ambiguity, like the examples I am seeing here and here. Which I understand as prevents implicit conversion of basic types to object type, and this makes sense. struct point {explicit point(int x, int y = 0); }; point p2 = 10; // Error: would be OK without explicit What I want to understand is what value explicit brings when I am using custom datatypes as constructor argument? struct X {X(int x);}; // a sample custom datatype I am referring to. struct pointA { pointA(X x);}; // here this looks to me same as struct pointB {explicit pointB(X x);}; // like here this int main() { pointA pa = 10; // fails as expected return 0; }
The point of explicit has nothing to do with the parameter list, it has to do with the type being constructed, especially if there are side-effects. For example, consider std::ofstream. void foo(std::ofstream out_file); // ... foo("some_file.txt"); Without explicit, this will attempt to open some_file.txt and overwrite its contents. Maybe this is what you want, but it's a pretty big side-effect that's not obvious at the calling point. However, consider what we'd have to do since the relevant std::ofstream constructor is explicit. foo(std::ofstream("some_file.txt")); It's far more clear, and the caller isn't surprised (or at least shouldn't be). Whether the type being constructed is built-in, from a third-party library, or something you wrote yourself: it's irrelevant. explicit is useful anytime you don't want a type to be constructed without somebody being very explicit (hence the keyword) that's their intention.
69,421,674
69,521,901
Can't get_to vector of object inside itself with Nlohmann's JSON
I've got the following code (simplified): namespace nlohmann { // https://github.com/nlohmann/json/issues/1749#issuecomment-772996219 template <class T> void to_json(nlohmann::json &j, const std::optional<T> &v) { if (v.has_value()) j = *v; else j = nullptr; } template <class T> void from_json(const nlohmann::json &j, std::optional<T> &v) { if (j.is_null()) v = std::nullopt; else v = j.get<T>(); /* ERROR LOCATION */ } } // namespace nlohmann namespace discordpp{ class Component { public: Component(const std::optional<std::vector<Component>> &components) : components(components) {} std::optional<std::vector<Component>> components; // (Resolved) NLOHMANN_DEFINE_TYPE_INTRUSIVE(Component, components) friend void to_json(nlohmann::json &nlohmann_json_j, const Component &nlohmann_json_t) { nlohmann_json_j["components"] = nlohmann_json_t.components; } friend void from_json(const nlohmann::json &nlohmann_json_j, Component &nlohmann_json_t) { nlohmann_json_j.at("components").get_to(nlohmann_json_t.components); /* ERROR LOCATION */ } }; }// namespace discordpp Compiling returns the error error: no matching function for call to ‘nlohmann::basic_json<>::get<std::vector<discordpp::Component, std::allocator<discordpp::Component> > >() const’ Is there maybe something I could predeclare to solve this? Tried setting up an adl_serializer like this, same issue namespace nlohmann { template<> struct adl_serializer<discordpp::Component> { static void to_json(json &nlohmann_json_j, const discordpp::Component &nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE( NLOHMANN_JSON_TO, type, custom_id, disabled, style, label, emoji, url, options, placeholder, min_values, max_values, components)) } static void from_json(const json &nlohmann_json_j, discordpp::Component &nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE( NLOHMANN_JSON_FROM, type, custom_id, disabled, style, label, emoji, url, options, placeholder, min_values, max_values, components)) } }; } // namespace nlohmann I changed it to a vector of shared pointers and now I get error: no matching function for call to ‘nlohmann::basic_json<>::get<discordpp::Component>() const’ in the adl_serializer I wrote to handle it template <typename T> struct adl_serializer<std::vector<std::shared_ptr<T>>> { static void to_json(json &j, const std::vector<std::shared_ptr<T>> &v) { j = json::array(); for (auto t : v) { j.push_back(*t); } } static void from_json(const json &j, std::vector<std::shared_ptr<T>> &v) { if (!j.is_array()) { throw json::type_error::create(317, "j must be an array", j); } for (auto t : j) { v.push_back(std::make_shared<T>(j.get<T>())); /* Error is here */ } } }; Mirrored at https://github.com/nlohmann/json/discussions/3047 Edit: Full source (do a recursive clone): https://github.com/DiscordPP/echo-bot/tree/dev-objects Failed build: https://github.com/DiscordPP/echo-bot/runs/3799394029?check_suite_focus=true Edit 2: It's fine when I do std::vector<std::shared_ptr<Component>> components;, it just doesn't seem to be able handle 2 third party parsers, maybe?
I was doing some thinking on @Niels's answer and I realized that friend void from_json is taking an already-constructed Component& but Component doesn't have a default constructor. I added Component() : components(std::nullopt) {} and we're off to the races!
69,421,849
69,421,883
C++ header file class declaration
So in my C++ project, I have my "cards.h" and "cards.cpp" file, and the "cards.h" file declares 3 classes: Card, Deck, Hand class Card { private: // some private attributes public: // some public methods //..... void play(Deck& deck, Hand& hand); // This method plays the card, removes it from the hand, and places it in the deck } class Deck { private: vector<Card> deckCards; public: // some public methods } class Hand { private: vector<Card> handCards; public: // some public methods } The compiler gives me an error in the play method on "Deck" and "Hand" with the error "Unknown type name Deck", "Unknown type name Hand". How can it not see the classes that are declared in the same .h file? Does C++ read the file from top to bottom ? I also can't put the Card class at the bottom, because Deck and Hand uses Card I have to put all 3 classes in the same file, the "cards.h" file.
You are correct. C++ needs the declarations to go from top to bottom. A side note you have incorrect syntax for the class declarations. Each class needs to be terminated with a semicolon after the last closing curly brace. I tested your example and it works fine. You can separate the classes into their own files and use forward class declarations since each class needs the other. Or you can leave them in the same file and add the forward class declaration prior to usage. Like below. #include <vector> using namespace std; class Deck; class Hand; class Card { private: // some private attributes public: // some public methods //..... void play(Deck& deck, Hand& hand) {}; // This method plays the card, removes it from the hand, and places it in the deck }; class Deck { private: vector<Card> deckCards; public: // some public methods }; class Hand { private: vector<Card> handCards; public: // some public methods };
69,421,880
69,421,921
std::function inside template class giving object creation error
Getting below error for the code given below. Trying to have 3 std::function inside an template class and then initialize them with different functions from different classes. Why is this error happening? What's wrong with below code? template <typename T> class CFuntion { public: std::function<void()> callback_1; std::function<void()> callback_2; std::function<void()> callback_3; template <typename A, typename B, typename C> CFuntion(A cb1, B cb2, C cb3) : callback_1(cb1), callback_2(cb2), callback_3(cb3) { } }; class Impl1 { public: void do_something1() { cout << "Inside Impl1 do_something1" << endl; } void do_something2() { cout << "Inside Impl1 do_something2" << endl; } }; class Impl2 { public: void do_something1() { cout << "Inside Impl2 do_something1" << endl; } void do_something2() { cout << "Inside Impl2 do_something2" << endl; } }; class Impl3 { public: void do_something1() { cout << "Inside Impl3 do_something1" << endl; } void do_something2() { cout << "Inside Impl3 do_something2" << endl; } }; int main() { unique_ptr<CFuntion<void>> ptr1 = make_unique<CFuntion<void>>(std::bind(&Impl1::do_something1, &Impl2::do_something1, &Impl3::do_something2)); ptr1->callback_1(); ptr1->callback_2(); ptr1->callback_3(); system("pause"); return 0; }
Look at this part: unique_ptr<CFuntion<void>> ptr1 = make_unique<CFuntion<void>(std::bind(&Impl1::do_something1, &Impl2::do_something1, &Impl3::do_something2)); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Here, you pass only one object to your CFunction<void>'s constructor. What you needed might be this: // You need to pass temporary objects to 'std::bind()' to bind non-static member functions Impl1 obj1; Impl2 obj2; Impl3 obj3; std::unique_ptr<CFuntion<void>> ptr1 = std::make_unique<CFuntion<void>>(std::bind(&Impl1::do_something1, obj1), std::bind(&Impl2::do_something1, obj2), std::bind(&Impl3::do_something2, obj3)); Or, by looking at your Impl1, Impl2 and Impl3 classes it seems you could just make their member methods static (As none of those three classes seem to need any sort of distinction between their objects or have any instance variables to access/modify.): class Impl1 { public: static void do_something1() { cout << "Inside Impl1 do_something1" << endl; } static void do_something2() { cout << "Inside Impl1 do_something2" << endl; } }; class Impl2 { public: static void do_something1() { cout << "Inside Impl2 do_something1" << endl; } static void do_something2() { cout << "Inside Impl2 do_something2" << endl; } }; class Impl3 { public: static void do_something1() { cout << "Inside Impl3 do_something1" << endl; } static void do_something2() { cout << "Inside Impl3 do_something2" << endl; } }; That way, you just need to do this, which appears to be what you want to do: std::unique_ptr<CFuntion<void>> ptr1 = std::make_unique<CFuntion<void>>(std::bind(&Impl1::do_something1), std::bind(&Impl2::do_something1), std::bind(&Impl3::do_something2));
69,422,376
69,422,767
Compile-time comparison of pointers to local variables after their end of life
Starting from C++17, it is possible to define a constexpr function that will return a pointer on its local variable. The caller will so get a pointer on an object after its end of life. Clearly such pointers cannot be dereferenced to avoid undefined behavior. But is it legal to compare them on equality? Consider an example: constexpr auto f() { char c = 0; auto p = &c; return p; }; int main() { static_assert( ( f() == f() ) == ( f() == f() ) ); //ok everywhere static_assert( f() == f() ); //true in GCC, false in Clang } The first static_assert is accepted by all compilers (if there is some undefined behavior, no single warning appear), and it basically checks that f() == f() gives consistent result true or false in each compiler. GCC says that f() == f() is true, while Clang insists on f() != f() (which looks more logical for compile-time). Demo: https://gcc.godbolt.org/z/YG1jonoG7 Which compiler (if any) is right here?
This is, oddly, implementation-defined per [basic.stc]/4: the pointers returned by f are invalid, so comparing them might do something bad. Of course, it’s not really clear what the space of possibilities includes here: a footnote mentions a runtime fault, which is usually lumped with undefined behavior, but during constant evaluation one would expect that to reliably fail the evaluation (which would be reported as “static_assert expression not constant”). Supposedly, implementations are required to document their choice here, but I doubt any of them meaningfully address this particular situation.
69,422,822
69,423,268
What should be the proper declaration of array while finding the largest number in array?
C++ This is my code in C++ for finding the largest number in array. When I was running in my IDE then there was no compilation error but it was not giving me output. I think the problem is in the declaration of array at line 8. I replaced the array declaration from line 8 to line 11 then it is working fine in my IDE. So I didn't get it that why the declaration of array was not working at line 8? #include <bits/stdc++.h> using namespace std; int largest_in_array(int a[], int n); int main() // main function { int n; // User will enter the size of array int arr[n]; // Line 8 cout << "Enter the size of array: " << endl; cin >> n; // Line 11 cout << "\nEnter the elements of array: " << endl; for (int i = 0; i < n; i++) // This loop will run for each element of array that user wants to enter { cout << "Enter the " << (i + 1) << " element:"; cin >> arr[i]; cout << endl; } cout << "Elements are: ["; for (int i = 0; i < n; i++) // Prints the elements of array { // cout << "Enter the " << (i + 1) << " element:"; cout << arr[i] << " "; // cout << endl; } cout << "]"; int res = largest_in_array(arr, n); //Function call cout << "\nLargest element in array is: " << arr[res] << endl; return 0; } int largest_in_array(int a[], int n) // function that will return the index of largest element in array { int max = 0; for (int i = 1; i < n; i++) { if (a[max] < a[i]) { max = i; } } return max; }
You declare int arr[n]; before the user has entered a value into n. n has an indeterminate value when you read it and create arr. You don't check that the user enters a positive value into n. Zero and negative sized arrays are not valid. Other points: bits/stdc++.h is not a standard header which makes your program not portable. Use the proper header files, like iostream etc. arr[n] is a Variable Length Array (VLA) which is not part of standard C++. Make it a std::vector<int> arr(n); instead. The use of std::endl is unnessesary. There is no need to flush the output streams here. Use \n instead. Example: #include <iostream> #include <limits> #include <vector> int largest_in_array(const std::vector<int>& a) { int max = 0; for(int i = 1; i < a.size(); i++) { if(a[max] < a[i]) { max = i; } } return max; } int main() // main function { int n; // User will enter the size of array std::cout << "Enter the size of array:\n"; // check that input succeeds and that the value is valid if(!(std::cin >> n) || n < 1) return 1; std::vector<int> arr(n); std::cout << "\nEnter the elements of array:\n"; for(int i = 0; i < n; i++) { std::cout << "Enter the " << (i + 1) << " element:"; if(!(std::cin >> arr[i])) { std::cout << "invalid input, bye bye\n"; return 1; } } std::cout << "Elements are: ["; for(int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << "]"; int res = largest_in_array(arr); // Function call std::cout << "\nLargest element in array is: " << arr[res] << '\n'; } That said, you could however use the standard algorithm std::max_element instead of writing your own. It returns an iterator to the maximum element. You could also make use of range-based for loop when you don't need to know the index in the array, as in your second loop. Example: #include <algorithm> #include <cstddef> #include <iostream> #include <iterator> #include <limits> #include <vector> int main() { int n; // User will enter the size of array std::cout << "Enter the size of array:\n"; if(!(std::cin >> n) || n < 1) return 1; std::vector<int> arr(n); std::cout << "\nEnter the elements of array:\n"; for(int i = 0; i < n; i++) // This loop will run for each element of // array that user wants to enter { std::cout << "Enter the " << (i + 1) << " element:"; if(!(std::cin >> arr[i])) { std::cout << "invalid input, bye bye\n"; return 1; } } std::cout << "Elements are: ["; for(auto value : arr) { // a range-based for loop std::cout << value << ' '; } std::cout << "]\n"; auto res = std::max_element(arr.begin(), arr.end()); std::cout << "Largest element in array is: " << *res << '\n'; std::size_t index = std::distance(arr.begin(), res); std::cout << "which has index " << index << '\n'; }
69,423,225
69,423,376
C++ Linked list unit test returns segment fault
My algorithm for implementing a linked-list as follows Function to add a new node and returns location pointer. One core function to handle adding a node front,end operations. linkedList.hpp #include <cstddef> class LinkedList{ public: int value {0}; LinkedList* nextNode {NULL}; }; LinkedList* addNewNode(int nodeVal){ LinkedList *newNode; newNode->value = nodeVal; newNode->nextNode = nullptr; return newNode; } Below googletest unit-test checks whether Returned node's pointer is not null. Returned node has a value. Returned node's next node value is set to NULL. linkedListTest.cpp #include <gtest/gtest.h> #include "../linkedList.hpp" int main(int argc, char **argv){ ::testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); } class LinkedListTest : public ::testing::Test{ public: LinkedList *linkedlist = new LinkedList(); virtual void SetUp(){ } virtual void TearDown(){ delete linkedlist; } }; TEST_F(LinkedListTest,addNewNodeReturnsItsNodePointer){ // act linkedlist = addNewNode(5); EXPECT_TRUE(linkedlist != nullptr); ASSERT_EQ(linkedlist->value,5); EXPECT_TRUE(linkedlist->nextNode != nullptr); } When I run this code,tests pass but I get Segmentation fault What did I miss here?
newNode in addNewNode was never initialized, so it's a pointer to nowhere: LinkedList* addNewNode(int nodeVal) { LinkedList *newNode; // Uninitialized, so undefined newNode->value = nodeVal; // `->` dereferences the pointer, but it goes nowhere! One way to initialize it is using heap allocation, i.e., operator new - but remember that you need to manage resources in C++, so you'll need to free it after your done using it. LinkedList* addNewNode(int nodeVal) { LinkedList *newNode = new LinkedList(); newNode->value = nodeVal; newNode->nextNode = nullptr; Later, to free the memory, you can do something like this: if (myNode->nextNode != nullptr) { delete myNode->nextNode; myNode.nextNode = nullptr; } But if you want to delete the whole LinkedList, you'll first have to walk to its end and start deleting from there. If you delete a node before deleting its successor, you create a memory leak bc. you no longer have a pointer to free that memory. Also make sure to turn your compiler warnings up! Default settings are way too lenient. E.g., for GCC you can use -Wall. Which tells me: <source>: In function 'LinkedList* addNewNode(int)': <source>:12:18: warning: 'newNode' is used uninitialized [-Wuninitialized] 12 | newNode->value = nodeVal; | ~~~~~~~~~~~~~~~^~~~~~~~~ And when you get a segmentation fault (segfault), you should compile your program in debug mode and run it in a debugger. It can tell you where the error happened: gcc -g -Og -o myprog myprog.c gdb ./myprog run (segfault) backtrace
69,424,015
69,424,050
glm rotation in ortho space
I set up my ortho projection like this : transform = glm::ortho(0.0f, width, height, 0.0f); this works pretty well, but when I want to use the glm::rotate function like this: transform = glm::rotate(transform, glm::radians(45.0f), glm::vec3(0, 0, 1)); my object rotates around 0 : 0 : 0. my vertices look like this: GLfloat vertices[] = { 600, 100, 0, 612, 100, 0, 612, 130, 0, 600, 130, 0 }; how can I make my object rotate around its center ?
If you want to rotate around its center you have to: Translate the object so that the center of the object is moved to (0, 0). Rotate the object. Move the object so that the center point moves in its original position. GLfloat center_x = 606.0f; GLfloat center_y = 115.0f; transform = glm::translate(transform, glm::vec3(center_x, center_y, 0)); transform = glm::rotate(transform, glm::radians(45.0f), glm::vec3(0, 0, 1)); transform = glm::translate(transform, glm::vec3(-center_x, -center_y, 0)); See also How to use Pivot Point in Transformations
69,424,025
69,425,305
Clang compiling for iOS (arm64) with -shared LDFLAG - Exec format error
Newbie alert here, sorry in advance if this question duplicates (didn't find the answer elsewhere)! I run into problems with simple hello binary for iOS (arm64) build on macOS machine (x86_64). The problem is that when I add LDFLAGS with shared framework (i.e. "-shared -framework CoreMedia" or other framework) to build my binary, it compiles fine but when it executes on device I get Exec format error: iPhone:/tmp root# ./hello -sh: ./hello: cannot execute binary file: Exec format error Build without -shared flag it runs as intended: iPhone:/tmp root# ./hello Hello Can someone please explain to me why this flag causes exec error on binary? Is it related to different platform which I'm building on than the targeted device? Should I build on arm64 platform to get -shared flag working fine? Just in case, build script is: export CLANG_BIN=`xcrun --sdk iphoneos --find clang` export CLANGXX_BIN=`xcrun --sdk iphoneos --find clang++` export SDK=`xcrun --sdk iphoneos --show-sdk-path` export CFLAGS="-fno-builtin -fno-stack-protector -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/ -fno-stack-protector -Wno-builtin-requires-header -fno-stack-check" #export LDFLAGS="-shared -framework CoreMedia" # <- exec error when this added to compile export LDFLAGS="-framework CoreMedia" # <- with just this, bin executes fine export CXX="$CLANGXX_BIN $CFLAGS -isysroot $SDK" $CXX -arch arm64 -o hello hello.c $LDFLAGS -Wall -Wconversion
-shared means you're building a shared library. You cannot run a shared library.
69,424,209
69,424,472
How can I split a string with multiple data into separate vectors - C++
I am trying to store data from a single vector into different vectors and I would like to separate each line into it's respective vector. A240 001 KERUL 41.857778 52.139167 A240 002 TABAB 40.903333 52.608333 A240 003 KRS 40.040278 53.012222 A240 004 KESEK 39.283333 55.566667 A240 005 INRAK 39.000000 56.300000 A242 001 HR 47.561667 6.732250 This is the layout of a random string and I would like to split it into 5 different vectors so that I would get a vector with [A240, A240, A242,...], [001, 002, 003,...] and so on. I've thought of regex but I'm not sure how to go about it.
Regex would be good for this, here is an example : I think you can change it to your specific case, e.g. reading your input line by line from a file. #include <iostream> #include <string> #include <regex> // helper function for showing the content of a vector. // used to show you the content of each of the 5 vectors generated. template<typename type_t> void show(const std::vector<type_t>& values) { for (const auto& value : values) { std::cout << value << " "; } std::cout << std::endl; } int main() { // I didn't know what the firs 2 entries are so just called them v1, v2 // 5 vectors in total. (you could also opt for 1 vector of a struct holding the data) std::vector<std::string> v1; std::vector<std::string> v2; std::vector<std::string> names; std::vector<double> longitudes; std::vector<double> lattitudes; // This is a regex that will work on the input you gave // also have a look at regex101.com you can // test your own regexes there // \\s+ matches one or more whitespaces // group 1 : ([A-Z][0-9]{3}), matches one letter and exactly 3 numbers // group 2 : ([A-Z]{3}), matches three letters // group 3 : ([A-Z]+), matches one or more letters // group 4 : ([0-9]+\\.[0-9]+), matches numbers with a . in it // group 5 : ([0-9]+\\.[0-9]+), matches numbers with a . in it std::regex rx{ "([A-Z][0-9]{3})\\s+([0-9]{3})\\s+([A-Z]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)" }; std::smatch match; std::string input = { "A240 001 KERUL 41.857778 52.139167 A240 002 TABAB 40.903333 52.608333 A240 003 KRS 40.040278 53.012222 A240 004 KESEK 39.283333 55.566667 A240 005 INRAK 39.000000 56.300000 A242 001 HR 47.561667 6.732250" }; // in C++ you need to explicitly go over repeated occurences auto begin = input.cbegin(); while (std::regex_search(begin, input.cend(), match, rx)) { // groups end up in match array, group 1 at index 1, group 2 at index 2, etc.. // group[0] is the whole match, but we don't need it here. v1.push_back(match[1]); v2.push_back(match[2]); names.push_back(match[3]); // you can also convert the strings to doubles if needed. longitudes.push_back(std::stod(match[4])); lattitudes.push_back(std::stod(match[5])); // skip forward to after match and look further begin = match.suffix().first; } show(v1); show(v2); show(names); show(longitudes); show(lattitudes); return 0; }
69,424,237
69,424,353
Trying to return a function from a function with an argument function within it
I am curious if that's even possible to create a static function in another function and then return that static function with an argument function within it. So far what I've tried doesn't work at all, and when I use raw function pointers the code fails to compile. #include <iostream> #include <functional> //both do not work but this one doesn't even compile /* void (*func(void (*foo)()))() { static void (*copy)(); copy = [&]() { foo(); }; return copy; } */ std::function<void(void)> Foo(std::function<void(void)> func) { static std::function<void(void)> temp = [&]() { func(); }; return temp; } int main() { Foo([]() { std::cout << 123 << '\n'; }); }
The problem with your commented func is that a lambda which captures anything cannot convert to a pointer to function. Lambda captures provide data saved at initialization to be used when called, and a plain C++ function does not have any data other than its passed arguments. This capability is actually one of the big reasons std::function is helpful and we don't just use function pointers for what it does. std::function is more powerful than a function pointer. Of course, func could instead just do copy = foo; or just return foo;, avoiding the lambda issue. One problem with Foo is that the lambda captures function parameter func by reference, and then is called after Foo has returned and the lifetime of func has ended. A lambda which might be called after the scope of its captures is over should not capture them by reference, and std::function is an easy way to get into that bad situation. The lambda should use [=] or [func] instead. Note that your static inside Foo is not like the static in front of an actual function declaration. It makes temp a function-static variable, which is initialized only the very first time and then kept. If Foo is called a second time with a different lambda, it will return the same thing it did the first time. If that's not what you want, just drop that static. Linkage of the functions/variables is not an issue here. (It's a bit strange that Foo puts a std::function inside a lambda inside a std::function which all just directly call the next, instead of just using the original std::function. But I'll assume that's just because it's a simplified or learning-only example. If the lambda did something additional or different, this would be a fine way to do it.) Your main ignores the function returned from Foo. Maybe you meant to call what Foo returns, with int main() { Foo([]() { std::cout << 123 << '\n'; })(); }
69,424,363
69,424,708
Is it allowed to name a global variable `read` or `malloc` in C++?
Consider the following C++17 code: #include <iostream> int read; int main(){ std::ios_base::sync_with_stdio(false); std::cin >> read; } It compiles and runs fine on Godbolt with GCC 11.2 and Clang 12.0.1, but results in runtime error if compiled with a -static key. As far as I understand, there is a POSIX(?) function called read (see man read(2)), so the example above actually invokes ODR violation and the program is essentially ill-formed even when compiled without -static. GCC even emits warning if I try to name a variable malloc: built-in function 'malloc' declared as non-function Is the program above valid C++17? If no, why? If yes, is it a compiler bug which prevents it from running?
The code shown is valid (all C++ Standard versions, I believe). The similar restrictions are all listed in [reserved.names]. Since read is not declared in the C++ standard library, nor in the C standard library, nor in older versions of the standard libraries, and is not otherwise listed there, it's fair game as a name in the global namespace. So is it an implementation defect that it won't link with -static? (Not a "compiler bug" - the compiler piece of the toolchain is fine, and there's nothing forbidding a warning on valid code.) It does at least work with default settings (though because of how the GNU linker doesn't mind duplicated symbols in an unused object of a dynamic library), and one could argue that's all that's needed for Standard compliance. We also have at [intro.compliance]/8 A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs. We can consider POSIX functions such an extension. This is intentionally vague on when or how such extensions are enabled. The g++ driver of the GCC toolset links a number of libraries by default, and we can consider that as adding not only the availability of non-standard #include headers but also adding additional translation units to the program. In theory, different arguments to the g++ driver might make it work without the underlying link step using libc.so. But good luck - one could argue it's a problem that there's no simple way to link only names from the C++ and C standard libraries without including other unreserved names. (Does not altering a well-formed program even mean that an implementation extension can't use non-reserved names for the additional libraries? I hope not, but I could see a strict reading implying that.) So I haven't claimed a definitive answer to the question, but the practical situation is unlikely to change, and a Standard Defect Report would in my opinion be more nit-picking than a useful clarification.
69,424,538
69,425,326
How can I iterate through the last element of the vector without going out of bounds?
The expected output is 1a1b1c but I only get 1a1b If I try putting '-1' next to input.size() in the for loop but that will just ignore the bug. What I'm looking for is that I want to be able to iterate through the last member of the string without going out of bounds. std::string input = "abc"; for (unsigned int i = 0; i < input.size(); i++){ int counter = 1; while(input.at(i) == input.at(i+1) && i < input.size()-1){ counter++; i++; } number.push_back(counter); character.push_back(input.at(i)); }
Few points for you to consdier: 1: for (unsigned int i = 0; i < input.size(); i++) specifically i++. This is a postfix operation meaning it returns i then increments the value of i. Not as big a deal here with integers but with iterators this can get very expensive as you create a copy of the iterator each time. Prefer to say what you mean / what you actually want, which is to increment i, not get a copy of i and increment i afterwards. So prefer ++i which only increments i and does not make a copy. 2: unsigned int i = 0 Firstly its better than using an int which has a signed -> unsigned conversaion every comparison with input.size() which returns a size_t. Secondly unsigned int is not guaranteed to be big enough to hold the size of the string and requires a promotion from (probably) 32 bit -> 64 bit unsigned to compare with size_t 3: cognitive complexity, nested loops which both mutate the same invariant (in this case i) makes the code more difficult to reason about and will ultimately lead to more bugs as code evolves over time. where possible only have one place where a loop invariant is mutated. 4: As pointed out by others the while loop while(input.at(i) == input.at(i+1) && i < input.size()-1) can exceed the size of the string and using the .at member function of string will throw for an out of bounds access. This can be simply resolved with point 3 by refactoring ther nested loop into a single loop. 5: Avoid so many calls to .at, we are in complete control of the index we use to index the string so you can use operator[] safely as long as we can guarantee i will always be a valid index which in this case i think you can. 6: i < input.size() using < when its not the check you want and its much more expensive than the check you actually want which is i != input.size(). Check out this trivial comparison in compiler explorer Thankfully the fix from shadowranger Fixes your problem completely ie: while(i < s.size()-1 && s.at(i) == s.at(i+1)) However i would like to offer an alternitive with no nested loops to show you how to avoid my points 3,4, 5 and 6 : void do_the_thing(std::string const& s) { std::cout << "Considering: \"" + s + "\"\n"; if(s.empty()) { return; } size_t const length = s.length(); // avoiding repeated calls to length which never changes in this case if(length == 1) { std::cout << "1" << s[0] << "\n"; return; } std::vector<unsigned> number; std::vector<char> character; // do the stuff your example did char last = s[0]; unsigned same_count = 1; for(size_t ii = 1; ii != length; ++ii) { char const cur = s[ii]; if(cur == last) { ++same_count; } else { number.push_back(same_count); character.push_back(last); last = cur; same_count = 1; } } if(*s.rbegin() == last) { number.push_back(same_count); character.push_back(last); } // print the things or use them in some way assert(number.size() == character.size()); size_t const out_len = character.size(); for(size_t ii = 0; ii != out_len; ++ii) { std::cout << number[ii] << character[ii]; } std::cout << "\n"; }
69,424,945
69,425,044
How to detect integer overflow?
Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First ask for N, then read the values into a vector, then calculate the sum of the first N values. For example: “Please enter the number of values you want to sum:” 3 “Please enter some integers (press '|' to stop):” 12 23 13 24 15 | “The sum of the first 3 numbers ( 12 23 13 ) is 48.” Handle all inputs. For example, make sure to give an error message if the user asks for a sum of more numbers than there are in the vector. Modify the program from exercise 8 to write out an error if the result cannot be represented as an int. So in exercise 9 it says to write out an error message if the result cannot be represented as an int, but if I'm only adding up integers here the only thing I can think of here that would cause a number to not be able to be represented as an int would be if there's some integer overflow and the integer goes above INT_MAX or below INT_MIN but how exactly can I detect this? This is my code: #include<vector> #include<cmath> #include<string> #include<iostream> #include<algorithm> #include<stdexcept> using namespace std; int main() { int N = 0; vector<int> values; cout << "Please enter the number of values you want to sum." << '\n'; cin >> N; cout << "Please enter some numbers" << '\n'; for (int tempnum; cin >> tempnum; ) { values.push_back(tempnum); } if (N > values.size()) { cout << "How am I gonna add up more numbers than you gave me?" << '\n'; } else { int total = 0; for (int i = 0; i < N; i++) { total += values[i]; } } } But I can't just check if total is above or below INT_MAX or INT_MIN because INT_MAX +1 or something returns some random negative value so I'm not really sure how to do this
You can do this with some arithmetic: So you want to know if acc + x > INT_MAX, where acc is the accumulator (the sum so far) and x is the next element. Adding them together may overflow though. But acc > INT_MAX - x is equivalent and x is already stored in an int. So this can also not underflow, bc. x can be at most INT_MAX. I.e., just transform the inequation to avoid overflow. In this case, subtract x from both sides. That only works for positive x though, thanks to user interjay for pointing this out. With negative x, this becomes a subtraction: acc + (-x) > INT_MAX acc - x > INT_MAX This can not overflow, because we are subtracting from acc. But it may underflow, so the question becomes: acc - x < INT_MIN acc < INT_MIN + x So: int acc = 0; for (int i = 0; i < N; ++i) { int x = values[i]; if (x >= 0 && acc > (INT_MAX - x)) { cout << "ERROR: Overflow."; return 1; } else if (x < 0 && acc < (INT_MIN - x)) { cout << "ERROR: Underflow."; return 1; } else { acc += x; } }
69,425,009
69,458,300
Activating and deactivating `while` loop with 2 mouse buttons
I want to activate a while loop with 2 mouse buttons. The first button should start and stop it and the second one should stop and reset it. It works, but I can't reset the first button. I tried a lot of GetKeyState() and GetAsyncKeyState() variants. bool loopy = false; int main() { while (true) { if (GetKeyState(VK_XBUTTON2) > 0) { loopy = true; } else { loopy = false; } if (GetKeyState(VK_XBUTTON1) < 0) { loopy = false; // BYTE keystate[256] = { 0 }; // SetKeyboardState(keystate); } if (loopy) { // do stuff... } } }
the solution if anybody is interested :) bool loopy = false; LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (wParam == WM_XBUTTONDOWN) { if (HIWORD(((PMSLLHOOKSTRUCT)lParam)->mouseData) == XBUTTON2) { loopy = !loopy; return true; } else if (HIWORD(((PMSLLHOOKSTRUCT)lParam)->mouseData) == XBUTTON1) { loopy = false; return true; } } return CallNextHookEx(0, nCode, wParam, lParam); } DWORD WINAPI ThreadProc(LPVOID lpParameter) { while (true) { if (loopy) { // do stuff } } } int main(void) { SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, GetModuleHandle(0), 0); CreateThread(0, 0, ThreadProc, 0, 0, 0); while(GetMessage(0, 0, 0, 0)); ExitProcess(EXIT_SUCCESS); } the key part is this: loopy = !loopy;
69,425,186
69,427,142
How to skip reading the first line of file?
How can I ignore the first line of the text file and start at the second line when I called it in the code? I was wondering how. Also, how can I sort the file according to first name, last name and grade? I just have the first name sorted but not the last name and grade accordingly. If you have any idea, I hope you can share it with me. Thanks for the help! Here's my code: #include <iostream> #include <fstream> using namespace std; struct studentRecord{ string lastname; string firstname; string grade; }; int main(){ ifstream ifs("student-file.txt"); string lastname, firstname, grade, key; studentRecord records[20]; if(ifs.fail()) { cout << "Error opening student records file" <<endl; exit(1); } int i = 0; while(! ifs.eof()){ ifs >> lastname >> firstname >> grade; records[i].lastname = lastname; records[i].firstname = firstname; records[i].grade = grade; i++; } for (int a = 1, b = 0; a < 20; a++) { key = records[a].firstname ; b = a-1; while (b >= 0 && records[b].firstname > key) { records[b+1].firstname = records[b].firstname; b--; } records[b+1].firstname = key; } for (int k = 0; k < 20; k++) { cout << "\n\t" << records[k].firstname << "\t"<< records[k].lastname << "\t" << records[k].grade; } }
When I saw this post it reminded me of a similar task completed at uni. I have rewritten your code to perform the same task but using classes instead of structs. I have also included a way to sort the vector by using the function here. I have included the "ignore first line" method @Scheff's Cat mentioned. Here it is: #include <iostream> #include <fstream> #include <sstream> #include <limits> #include <string> #include <vector> using namespace std; class studentrecord{ string firstname, lastname, grade; public: studentrecord(string firstname, string lastname, string grade){ this -> firstname = firstname; this -> lastname = lastname; this -> grade = grade; } friend ostream& operator<<(ostream& os, const studentrecord& studentrecord) { os << "\n\t" << studentrecord.firstname << "\t" << studentrecord.lastname << "\t" << studentrecord.grade; return os; } }; void displayRecords(vector <studentrecord*> records){ for(int i = 0; i < records.size(); i++){ cout << *records[i]; } } int main(){ //read in file ifstream infile; infile.open("student-file.txt"); infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (!infile.is_open()){ cout << "Error opening student records file" <<endl; exit(1); } vector <studentrecord*> records; string firstname, lastname, grade; while (infile >> firstname >> lastname >> grade;) { records.push_back(new studentrecord(firstname, lastname, grade)); } displayRecords(records); return 0; } To sort the vector so that it prints in order of either first name, last name or grade I used the following functions: bool sortfirstname(studentrecord* A, studentrecord* B) { return (A->getfirstname() < B->getfirstname()); } bool sortlastname(studentrecord* A, studentrecord* B) { return (A->getlastname() < B->getlastname()); } bool sortgrade(studentrecord* A, studentrecord* B) { return (A->getgrade() < B->getgrade()); } sort(records.begin(), records.end(), (sortfirstname)); sort(records.begin(), records.end(), sortlastname); sort(records.begin(), records.end(), sortgrade); If you wanted to sort by first name you would call the sort(records.begin(), records.end(), (sortfirstname)); function and then the displayrecords() function. The advantage of using classes stored in vectors is that you don't have to state the size of the vector containing the details about students since you can keep adding information to the end of the vector using the vector.push_back() function. It also makes sorting the data contained easier. If anything isn't clear, let me know and I can give you a hand.
69,425,292
69,425,372
Array and pointers to structures
So I have this structure struct Data { int id; string message; }; I am trying to create an array of struct pointers and fill it with values using this Data *stack[10]; for(int i=0; i<10; i++){ stack[i] = (struct Data*) malloc(sizeof(struct Data)); stack[i]->id = i; stack[i]->message = "message" + i; } however, I keep getting an error (segmentation fault when debugging) from stack[i]->message = "message" + i; Can anyone please help understand what's causing the error and how to solve it?
Below is the working example. You can use smart pointers for automatic memory management, that is the destructor will be called automatically when reference count goes to zero. #include <iostream> #include <memory> using namespace std; struct Data { int id; string message; Data() { std::cout<<"default consructor"<<std::endl; } ~Data() { std::cout<<"destructor "<<std::endl; } }; int main() { std::cout << "Hello World" << std::endl; std::shared_ptr<Data> stack[10]; for(int i=0; i<10; i++){ stack[i] = std::make_shared<Data>(); stack[i]->id = i; stack[i]->message = "message" + std::to_string(i);//make sure to convert the integer to std::string } //check the value of id for first element in stack std::cout<<stack[1]->id<<std::endl; return 0; } You can also use new instead of malloc but then you will have to call delete explicitly. Note the use of std::to_string() to convert the integer i to string.
69,425,307
69,425,505
How do I define __cpp_exceptions for gsl:narrow to compile?
I am getting confused again :( I have looked at this discussion: detect at compile time whether exceptions are disabled I am new to trying to use GSL. I have copied the GSL folder to my PC and added a #include to my stdafx.h file. But the gsl:narrow command is not exposed. I then see it refers to the __cpp_exceptions macro/token. I tried to #define it in my pre-processor's list in the project settings and it does not like it. How do I activate this __cpp_exceptions? The gsl header file: #ifndef GSL_GSL_H #define GSL_GSL_H #include <gsl/algorithm> // copy #include <gsl/assert> // Ensures/Expects #include <gsl/byte> // byte #include <gsl/pointers> // owner, not_null #include <gsl/span> // span #include <gsl/string_span> // zstring, string_span, zstring_builder... #include <gsl/util> // finally()/narrow_cast()... #ifdef __cpp_exceptions #include <gsl/narrow> // narrow() #endif #endif // GSL_GSL_H I am trying to compile MFC C++ project with Visual Studio 2022 Preview.
Whether or not the __cpp_exceptions macro is pre-defined by the MSVC compiler depends on your Visual Studio project's settings (i.e. whether or not C++ Exceptions are enabled). You can check/change the relevant setting by right-clicking on the project in the Solution Explorer pane and selecting the "Properties" command. In the popup that appears, open the "C/C++" node in the navigation tree on the left and select the "Code Generation" sub-node. Then, in the right-hand pane, make sure that the "Enable C++ Exceptions" option is set to "Yes (/EHsc)" (other varieties of the "Yes" option may also work): (Note: This works in Visual Studio 2019. I don't have V/S 2022 installed on my PC, so I can't check it in that version – but I would imagine the process is very similar.) The following short console-mode program demonstrates the difference caused by changing that setting: #include <iostream> int main() { #ifdef __cpp_exceptions std::cout << "yes"; // With "Yes (/EHsc)" #else std::cout << "no"; // With "No" #endif std::cout << std::endl; return 0; }
69,425,365
69,450,143
How do I port C++ code to Esp8266 and Esp32 using interrupts from code written for older boards
I am trying to port some C++ Arduino code to more recent ESP8266 and ESP32 boards. I have checked already the Arduino Stack Exchange forum unfortunately without results Porting this C++ code from older Arduino to Esp8266/Esp32 does not work, I have added also the compiling errors at the bottom of this question: /* rcTiming.ino -- JW, 30 November 2015 -- * Uses pin-change interrupts on A0-A4 to time RC pulses * * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein * */ #include <Streaming.h> static byte rcOld; // Prev. states of inputs volatile unsigned long rcRises[4]; // times of prev. rising edges volatile unsigned long rcTimes[4]; // recent pulse lengths volatile unsigned int rcChange=0; // Change-counter // Be sure to call setup_rcTiming() from setup() void setup_rcTiming() { rcOld = 0; pinMode(A0, INPUT); // pin 14, A0, PC0, for pin-change interrupt pinMode(A1, INPUT); // pin 15, A1, PC1, for pin-change interrupt pinMode(A2, INPUT); pinMode(A3, INPUT); PCMSK1 |= 0x0F; // Four-bit mask for four channels PCIFR |= 0x02; // clear pin-change interrupts if any PCICR |= 0x02; // enable pin-change interrupts } // Define the service routine for PCI vector 1 ISR(PCINT1_vect) { byte rcNew = PINC & 15; // Get low 4 bits, A0-A3 byte changes = rcNew^rcOld; // Notice changed bits byte channel = 0; unsigned long now = micros(); // micros() is ok in int routine while (changes) { if ((changes & 1)) { // Did current channel change? if ((rcNew & (1<<channel))) { // Check rising edge rcRises[channel] = now; // Is rising edge } else { // Is falling edge rcTimes[channel] = now-rcRises[channel]; } } changes >>= 1; // shift out the done bit ++channel; ++rcChange; } rcOld = rcNew; // Save new state } void setup() { Serial.begin(115200); Serial.println("Starting RC Timing Test"); setup_rcTiming(); } void loop() { unsigned long rcT[4]; // copy of recent pulse lengths unsigned int rcN; if (rcChange) { // Data is subject to races if interrupted, so off interrupts cli(); // Disable interrupts rcN = rcChange; rcChange = 0; // Zero the change counter rcT[0] = rcTimes[0]; rcT[1] = rcTimes[1]; rcT[2] = rcTimes[2]; rcT[3] = rcTimes[3]; sei(); // reenable interrupts Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1] << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl; } sei(); // reenable interrupts } The compiling error is: expected constructor, destructor, or type conversion before '(' token at line: ISR(PCINT1_vect) { I am seeking suggestions to get it working thank you.
All ESP32 GPIO pins are interrupt-capable pins. You can use interrupts, but in a different way. attachInterrupt(GPIOPin, ISR, Mode); Mode – Defines when the interrupt should be triggered. Five constants are predefined as valid values:HIGH, LOW, CHANGE, RISING, FALLING void IRAM_ATTR ISR() { Statements; } Interrupt service routines should have the IRAM_ATTR attribute, according to the ESP32 documentation
69,425,693
69,425,784
Reversing a vector using recursion in C++
I'm using the below code to reverse a vector (modify it). void revArr(int i, vector<int> arr) { int n = arr.size(); if (i >= n / 2) return; swap(arr[i], arr[n-i-1]); revArr(i + 1, arr); } int main() { vector<int> arr = {2, 13, 5, 26, 87, 65, 73}; revArr(0, arr); for (auto i: arr) { cout << i << " "; } cout << "" << endl; return 0; } Upon execution, I'm getting unchanged vector back on console: 2 13 5 26 87 65 73 Why is the vector not reversed? Thanks in advance.
As pointed out by richard-critten you are passing a copy of the vector to revArr this copy is reversed not the original arr If you want the function to modify the value passed to it you have two options: Pass by reference or pass by pointer. It will be up to you to decide which is more appropriate for your use case but given your example i think you want pass by reference. Very helpful table here to help you understand which to use and why: https://www.modernescpp.com/index.php/c-core-guidelines-how-to-pass-function-parameters
69,425,717
69,425,764
Switch statement with integer value
I am new to C++ and I am stuck on the switch statement because it doesn't seem to give an output when the value in the parentheses is an integer (Console-Program ended with exit code: 0). Although, the same code works fine when I change the type to char. Thank You. int main() { int num1; // argument of switch statement must be a char or int or enum cout<< "enter either 0 or 1" << "\n"; cin>> num1; switch (num1) { case '0': cout<< "you entered 0" << endl << endl; break; case '1': cout<< "you entered 1" << endl << endl; break; } }
You are switching on an int, which is correct, but your cases are not integers - they are char since they are surrounded in '. '0' is never equal to 0, nor is '1' ever equal to 1. Change the case values to integers. int main() { int num1; cout<< "enter either 0 or 1" << "\n"; cin>> num1; switch (num1) { case 0: cout<< "you entered 0" << endl << endl; break; case 1: cout<< "you entered 1" << endl << endl; break; } }
69,425,941
69,427,565
Mixing cuda and cpp templates and lambdas
Example code: https://github.com/Saitama10000/Mixing-cuda-and-cpp-templates-and-lambdas I want to have a kernel in a .cu file that takes an extended __host__ __device__lambda as parameter and use it to operate on data. I am using a .cuh file to wrap the kernel execution in a wrapper function. I include the .cuh file in main.cpp and use the wrapper function to do the computations. I need this .cuh, .cu type of organizing the code I'm using c++20 The example code doesn't compile. I am supposed to add a template instantiation in the .cu file, but I don't know how. I've tried this: typedef float(*op)(float); template std::vector<float> f<op>(std::vector<float> const&, op); but I still get this compilation error: In file included from Mixing-cuda-and-cpp-templates-and-lambdas/main.cpp:6: Mixing-cuda-and-cpp-templates-and-lambdas/kernel.cuh:6:20: error: ‘std::vector<float> f(const std::vector<float>&, FUNC) [with FUNC = main()::<lambda(float)>]’, declared using local type ‘main()::<lambda(float)>’, is used but never defined [-fpermissive] 6 | std::vector<float> f(std::vector<float> const& a, FUNC func); | ^ Mixing-cuda-and-cpp-templates-and-lambdas/kernel.cuh:6:20: warning: ‘std::vector<float> f(const std::vector<float>&, FUNC) [with FUNC = main()::<lambda(float)>]’ used but never defined make[2]: *** [CMakeFiles/main.dir/build.make:82: CMakeFiles/main.dir/main.cpp.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:95: CMakeFiles/main.dir/all] Error 2 make: *** [Makefile:103: all] Error 2
There are two problems with your approach. First, each lambda has it's own type even if parameters and function body are the same. For example, the following assertion fails #include <type_traits> int main(){ auto lambda1 = [](){}; auto lambda2 = [](){}; static_assert(std::is_same<decltype(lambda1), decltype(lambda2)>::value, "not same"); } That means, even if you somehow manage to explitely instantiate your template with the type of the lambda it won't be the type of the lambda which you will pass to your function. This problem can be solved by using functors instead of lambdas. Define a set of functors which may be used to call the function, and use them for template instantiation. Second, you want to pass a __host__ __device__ function. This annotation is a CUDA C++ extension which cannot be compiled with a standard C++ compiler. You have to use a CUDA compiler instead, which in turn allows you to place your kernel and wrappers in the .cuh file.
69,426,096
69,437,908
How to serialize and deserialize an object into/from binary files manually?
I've been trying to write the below object into a file and got lot of trouble since strings are dynamically allocated. class Student{ string name, email, telephoneNo; int addmissionNo; vector<string> issued_books; public: // There are some methods to initialize name, email, etc... }; So I got to know that I can't just write into a file or read from a file an object with serialization. So I searched all over the internet about serialization with cpp and got to know about Boost library.But I wanted to do it my own (I know writing a library that already exist is not good, but I wanna see what's going on inside the code). So I got to know about overloading iostream << and >>. And I also know that serialize/deserialize into/from text. But I want to serialize into a binary file. So I tried overloading ostream write and istream read. But then I got size issues(as write and read needs the sizeof the object it writes/reads).Then I also got to know about stringstream can help to serialize/deserialize objects into/from binary. But I don't how to do that? So my real question is How to serialize and deserialize an object into/from binary files without third party libraries?
I have found a solution serialize and deserialize an object into/from a file. Here is an explaination As I told you this is my class. And I have added two functions which overload the iostream's write and read. class Student{ string name, email, telephoneNo; int addmissionNo; vector<string> issuedBooks; public: void create(); // initialize the private members void show(); // showing details // and some other functions as well... // here I'm overloading the iostream's write and read friend ostream& write(ostream& out, Student& obj); friend istream& read(istream& in, Student& obj); }; But I have also told you that I have tried this already. The problem I have was how to read without object member's size. So I made changes as below (Please read comments also). // write: overload the standard library write function and return an ostream // @param out: an ostream // @param obj: a Student object ostream& write(ostream& out, Student& obj){ // writing the objet's members one by one. out.write(obj.name.c_str(), obj.name.length() + 1); // +1 for the terminating '\0' out.write(obj.email.c_str(), obj.email.length() + 1); out.write(obj.telephoneNo.c_str(), obj.telephoneNo.length() + 1); out.write((char*)&obj.addmissionNo, sizeof(obj.addmissionNo)); // int are just cast into a char* and write into the object's member // writing the vector of issued books for (string& book: obj.issuedBooks){ out.write(book.c_str(), book.length() + 1); } return out; } // read: overload the standard library read function and return an istream // @param in: an istream // @param obj: a Student object istream& read(istream& in, Student& obj){ // getline is used rather than read // since getline reads a whole line and can be give a delim character getline(in, obj.name, '\0'); // delimiting character is '\0' getline(in, obj.email, '\0'); getline(in, obj.telephoneNo, '\0'); in.read((char*)&obj.addmissionNo, sizeof(int)); for (string& book: obj.issuedBooks){ getline(in, book, '\0'); } return in; } As you can see I have wrote length+1 for the terminating '\0'. It is usefull in read function as we have used getline instead of read. So getline reads until the '\0'. So no need of a size. And here I'm writing and reading into/from a file. void writeStudent(Student s, ofstream& f){ char ch; // flag for the loop do{ s.create(); // making a student f.open("students", ios::app | ios::binary); // the file to be written write(f, s); // the overloaded function f.close(); cout << "Do you want to add another record? (y/n): "; cin >> ch; cin.ignore(); } while(toupper(ch) == 'Y'); // loop until user stop adding records. } void readStudent(Student s, ifstream& f){ char ch; // flag for the loop do{ f.open("students", ios::in | ios::binary); cout << "Enter the account no of the student: "; int no; cin >> no; int found = 0; while (read(f, s)){ if (s.retAddmissionNo() == no){ found = 1; s.show(); } } if (!found) cout << "Account Not found!\n"; f.close(); cout << "Do you want another record? (y/n): "; cin >> ch; } while(toupper(ch) == 'Y'); } That's how I solved my problem. If something wrong here please comment. Thank you!
69,426,322
69,426,733
Why is the template specialization function not being accessed
Problem Description In the following code we have 2 classes A and B whereB inherits from A. We also have 2 template functions test(T &t) and test(A &a). The output of the code is "A1". Why the test(A &a) function isn't being used in this example? // Online C++ compiler to run C++ program online #include <iostream> class A {}; class B: public A {}; template<typename T> void test(T &t){std::cout <<"A1";} template<> void test(A& a){std::cout <<"A2";} // If we put test(A& a) before test(T &t) we get the compilation error // 'test' is not a template function int main() { A *a = new B(); test(a); delete a; return 0; }
You're trying to pass a value of type A* to a function accepting A&. These are incompatible types, a pointer is not a reference. So the specialization test(A&) isn't considered, and the main template is used with T deduced as A*. If we change the call test(a) to test(*a), then the program will print A2. #include <iostream> class A {}; class B: public A {}; template<typename T> void test(T &t){std::cout <<"A1";} template<> void test(A& a){std::cout <<"A2";} // If we put test(A& a) before test(T &t) we get the compilation error // 'test' is not a template function int main() { A *a = new B(); test(*a); // <==== Here delete a; return 0; } (live demo)
69,426,330
69,426,598
Declaring lambda with int type not working
I wanted to use the lambda function somehow, but it doesn't work, and I don't know why. vector<int> v; /* ... */ int median = [](vector<int> a) { sort(a.begin(), a.end()); return a[a.size() / 2]; } I created a lambda function, but how can I call it? int median = [](vector<int> a) { ... } (v)? But it doesn't work too. I have seen lambda functions only in some examples like making custom comparator. Can I make it work in my case somehow?
Can I make it work in my case somehow? Yes you can. You can either call it immediately after the definition: int median = [](std::vector<int> a) { std::sort(a.begin(), a.end()); return a[a.size() / 2]; }(v); //^^ --> invoke immediately with argument See for reference: How to immediately invoke a C++ lambda? or define the lambda and call it later. /* const */ auto median = [](std::vector<int> a) { ...} int res = median(v); Note that I have used auto type, to specify the type of the lambda function. This is because, lambda has so-called closure type, which we can only mention either by a auto or any type erasure mechanism such as std::function. From cppreference.com The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression.
69,426,729
69,426,785
Can't use operators properly when taking integer inputs from user in classes and constructors [OOP]
I'm trying to do multiple calculations on same 2 integer variables and display their results separately. It works fine if I already set values to the variables. But if I try to take input from users then it gives me random numbers instead in the output. Here is my code in which I try to take the input/values from the user. #include<iostream> using namespace std; class calculation { public: calculation() { int num1 = 0; int num2 = 0; cout << "Write your numbers" << endl; cin >> num1>>num2; } int sum() { return num1+num2; } int sub() { return num1-num2; } int mul() { return num1*num2; } int div() { return num1/num2; } int mod() { return num1%num2; } void displayMessage() { cout<<sum()<<endl<<sub()<<endl<<mul()<<endl<<div()<<endl<<mod(); } private: int num1,num2; }; int main() { calculation obj; obj.displayMessage(); system("Pause"); return 0; } The output is not correct and it just gives me random numbers instead. But if I do it with pre set values using this code: #include<iostream> using namespace std; class calculation { public: calculation() { num1=10; num2=5; } int sum() { return num1+num2; } int sub() { return num1-num2; } int mul() { return num1*num2; } int div() { return num1/num2; } int mod() { return num1%num2; } void displayMessage() { cout<<sum()<<endl<<sub()<<endl<<mul()<<endl<<div()<<endl<<mod(); } private: int num1,num2; }; int main() { calculation obj; obj.displayMessage(); return 0; } Then it gives the correct output.
In your constructor: calculation() { int num1 = 0; int num2 = 0; cout << "Write your numbers" << endl; cin >> num1>>num2; } You have created two local variables names num1 and num2. They have the same names as your member variables, but they are not the same. They are new variables. You read values into those variables, and then they are immediately destroyed when the constructor exits. This change will use the member variables, instead of creating new variables. calculation() { num1 = 0; num2 = 0; cout << "Write your numbers" << endl; cin >> num1 >> num2; } You could also optionally use this-> to be explicit that you intend to change member variables. calculation() { this->num1 = 0; this->num2 = 0; cout << "Write your numbers" << endl; cin >> this->num1 >> this->num2; }
69,426,758
69,429,113
How to implement 1 or 2 frames lag between the main and the render thread?
I've read that engines skip 1 or 2 frames and keep this distance to ensure that the render thread and the main thread won't go too much forward. I've got a very simple command queue that allows the main thread to queue commands and the render thread to dispatch them, but I don't know how I can keep 1/2 frames distance between these threads. basic implementation: #include <iostream> #include <queue> #include <mutex> #include <functional> #include <thread> #include <condition_variable> struct CommandQueue { //not thread-safe //called only by the main thread //collects all gl calls from the main thread void Submit(std::function<void()> command) { commands.push(std::move(command)); } //called only by the main thread //when the current frame has finished pushing gl commands //we're ready to push them into the render thread void Flush() { { std::unique_lock<std::mutex> lock(mutex); commandsToExecute = std::move(commands); } cv.notify_one(); } //called only by the render thread //submit gl calls from our queue into the graphics queue bool Execute() { auto renderCommands = WaitForCommands(); if(renderCommands.empty()) { return false; } while(!renderCommands.empty()) { auto cmd = std::move(renderCommands.front()); renderCommands.pop(); cmd(); } return true; } void Quit() { quit.store(true, std::memory_order_relaxed); cv.notify_one(); } private: std::queue<std::function<void()>> WaitForCommands() { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock, [this]() { return !commandsToExecute.empty() || quit.load(std::memory_order_relaxed); }); auto result = std::move(commandsToExecute); return result; } std::mutex mutex; std::condition_variable cv; std::queue<std::function<void()>> commands; std::queue<std::function<void()>> commandsToExecute; std::atomic_bool quit{false}; }; int main() { CommandQueue commandQueue; std::thread renderThread([&](){ while(true) { if(!commandQueue.Execute()) { break; } } }); bool quit = false; while(!quit) { //example commands... commandQueue.Submit([](){ glClear(GL_COLOR_BUFFER_BIT); }); commandQueue.Submit([](){ glClearColor(1.0f, 0.0f, 0.0f, 1.0f); }); commandQueue.Submit([](){ glViewport(0, 0, 1600, 900); }); commandQueue.Submit([](){ SDL_GL_SwapWindow(window); }); //notify the render thread that there is work to be done commandQueue.Flush(); } commandQueue.Flush(); commandQueue.Quit(); renderThread.join(); return 0; } How can I implement this 1/2 frames lag?
I've found Filament Engine and it has FrameSkipper class which implements the solution I need. quick example: //what class should implement Tick functionality? std::vector<std::function<bool()>> tickFunctions; void RunAndRemove() { auto it = tickFunctions.begin(); while (it != tickFunctions.end()) { if ((*it)()) { it = tickFunctions.erase(it); } else ++it; } } void Tick(CommandQueue& queue) { queue.Submit([]() { RunAndRemove(); }); } struct Fence { Fence(CommandQueue& queue) : queue(queue) { queue.Submit([this]() { fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); std::weak_ptr<Status> weak = result; tickFunctions.push_back([this, weak]() { auto result = weak.lock(); if (result) { GLenum status = glClientWaitSync(fence, 0, 0u); result->store(status, std::memory_order_relaxed); return (status != GL_TIMEOUT_EXPIRED); } return true; }); }); } ~Fence() { queue.Submit([fence = fence]() { glDeleteSync(fence); }); } GLenum getFenceStatus() { if (!result) { return GL_TIMEOUT_EXPIRED; } return result->load(); } GLsync fence = nullptr; using Status = std::atomic<GLenum>; std::shared_ptr<Status> result{ std::make_shared<Status>(GL_TIMEOUT_EXPIRED) }; CommandQueue& queue; }; struct FrameSkipper { FrameSkipper(CommandQueue& queue, size_t latency = 1) : queue(queue), last(latency) { } ~FrameSkipper() = default; bool Begin() { auto& syncs = delayedSyncs; auto sync = syncs.front(); if (sync) { auto status = sync->getFenceStatus(); if (status == GL_TIMEOUT_EXPIRED) { // Sync not ready, skip frame return false; } sync.reset(); } // shift all fences down by 1 std::move(syncs.begin() + 1, syncs.end(), syncs.begin()); syncs.back() = {}; return true; } void End() { auto& sync = delayedSyncs[last]; if (sync) { sync.reset(); } sync = std::make_shared<Fence>(queue); } private: static constexpr size_t MAX_FRAME_LATENCY = 4; using Container = std::array<std::shared_ptr<Fence>, MAX_FRAME_LATENCY>; mutable Container delayedSyncs{}; CommandQueue& queue; size_t last; }; int main() { CommandQueue commandQueue; std::thread renderThread([&](){ while(true) { if(!commandQueue.Execute()) { break; } } }); FrameSkipper frameSkipper(commandQueue); auto BeginFrame = [&]() { Tick(commandQueue); if(frameSkipper.Begin()) { return true; } commandQueue.Flush(); return false; }; auto EndFrame = [&]() { frameSkipper.End(); Tick(commandQueue); commandQueue.Flush(); }; bool quit = false; while(!quit) { if(BeginFrame()) { commandQueue.Submit([](){ glClear(GL_COLOR_BUFFER_BIT); }); commandQueue.Submit([](){ glClearColor(1.0f, 0.0f, 0.0f, 1.0f); }); commandQueue.Submit([](){ glViewport(0, 0, 1600, 900); }); commandQueue.Submit([](){ SDL_GL_SwapWindow(window); }); EndFrame(); } } commandQueue.Flush(); commandQueue.Quit(); renderThread.join(); return 0; }
69,426,759
69,426,812
OpenGL how to set attribute in draw arrays
I have a GLfloat array containing my data that looks like this: GLfloat arr[] = { //position //color 300, 380, 0, 0, 1, 0, 300, 300, 0, 1, 1, 0, 380, 300, 0, 0, 1, 1, 380, 380, 0, 1, 0, 1 }; I'm trying to draw 4 points each with their respective color, currently I'm doing this: glPointSize(10); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, arr); glDrawArrays(GL_POINTS, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); But my attempts at modifying this to accept the color values failed. vertex and frag shaders: #version 330 core out vec4 FragColor; in vec3 ourColor; void main() { FragColor = vec4(ourColor, 1.0); } #version 330 core layout (location = 0) in vec4 position; layout (location = 1) in vec3 color; out vec3 ourColor; uniform mat4 projection; void main() { gl_Position = projection * vec4(position.xy, 0.0, 1.0); ourColor = color; }
You are using a shader program. The vertex attribute has the attribute index 0 and the color has the index 1. Use glVertexAttribPointer to define the 2 arrays of generic vertex attribute data: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, arr); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(flaot)*6, arr); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(flaot)*6, arr+3); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); The vertex array of attribute consist of a tuple with 6 components (x, y, z, r, g, b). Therefore the byte offset between consecutive generic vertex attributes (stride) is sizeof(flaot)*6 bytes. The address of the first vertex is arr and the address of the first color is arr+3 (respectively (unsigned char*)arr + sizeof(float)*3).
69,427,505
69,428,624
Segmentation Fault before even the first line of `main()` is executed and there are no non-local variables
In the C++ code below, a segmentation fault occurs before the first line of main() is executed. This happens even though there are no objects to be constructed before entering main() and it does not happen if I remove a (large) variable definition at the second line of main(). I assume the segmentation fault occurs because of the size of the variable being defined. My question is why does this occur before the prior line is executed? It would seem this shouldn't be occurring due to instruction reordering by the optimizer. I say this based on the compilation options selected and based on debug output. Is the size of the (array) variable being defined blowing the stack / causing the segfault? It would seem so since using a smaller array (e.g. 15 elements) does not result in a segmentation fault and since the expected output to stdout is seen. #include <array> #include <iostream> #include <vector> using namespace std; namespace { using indexes_t = vector<unsigned int>; using my_uint_t = unsigned long long int; constexpr my_uint_t ITEMS{ 52 }; constexpr my_uint_t CHOICES{ 5 }; static_assert(CHOICES <= ITEMS, "CHOICES must be <= ITEMS"); constexpr my_uint_t combinations(const my_uint_t n, my_uint_t r) { if (r > n - r) r = n - r; my_uint_t rval{ 1 }; for (my_uint_t i{ 1 }; i <= r; ++i) { rval *= n - r + i; rval /= i; } return rval; } using hand_map_t = array<indexes_t, combinations(ITEMS, CHOICES)>; class dynamic_loop_functor_t { private: // std::array of C(52,5) = 2,598,960 (initially) empty vector<unsigned int> hand_map_t hand_map; }; } int main() { cout << "Starting main()..." << endl << std::flush; // "Starting main()..." is not printed if and only if the line below is included. dynamic_loop_functor_t dlf; // The same result occurs with either of these alternatives: // array<indexes_t, 2598960> hand_map; // indexes_t hand_map[2598960]; } OS: CentOS Linux release 7.9.2009 (Core) Compiler: g++ (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5) Compile command: g++ -std=c++14 -Wall -Wpedantic -Og -g -o create_hand_map create_hand_map.cpp No errors or warnings are generated at compile time. Static analysis: A static analysis via cppcheck produces no unexpected results. Using check-config as suggested in the command output below yields only: Please note: Cppcheck does not need standard library headers to get proper results. $ cppcheck --enable=all create_hand_map.cpp create_hand_map.cpp:136:27: style: Unused variable: dlf [unusedVariable] dynamic_loop_functor_t dlf; ^ nofile:0:0: information: Cppcheck cannot find all the include files (use --check-config for details) [missingIncludeSystem] Attempted debug with GDB: $ gdb ./create_hand_map GNU gdb (GDB) Red Hat Enterprise Linux 8.0.1-36.el7 <snip> This GDB was configured as "x86_64-redhat-linux-gnu". <snip> Reading symbols from ./create_hand_map...done. (gdb) run Starting program: ./create_hand_map Program received signal SIGSEGV, Segmentation fault. 0x0000000000400894 in std::operator<< <std::char_traits<char> > (__s=0x4009c0 "Starting main()...", __out=...) at /opt/rh/devtoolset-7/root/usr/include/c++/7/ostream:561 561 __ostream_insert(__out, __s, (gdb) bt #0 0x0000000000400894 in std::operator<< <std::char_traits<char> > ( __s=0x4009c0 "Starting main()...", __out=...) at /opt/rh/devtoolset-7/root/usr/include/c++/7/ostream:561 #1 main () at create_hand_map.cpp:133 (gdb)
This is definitely a stack overflow. sizeof(dynamic_loop_functor_t) is nearly 64 MiB, and the default stack size limit on most Linux distributions is only 8 MiB. So the crash is not surprising. The remaining question is, why does the debugger identify the crash as coming from inside std::operator<<? The actual segfault results from the CPU exception raised by the first instruction to access to an address beyond the stack limit. The debugger only gets the address of the faulting instruction, and has to use the debug information provided by the compiler to associate this with a particular line of source code. The results of this process are not always intuitive. There is not always a clear correspondence between instructions and source lines, especially when the optimizer may reorder instructions or combine code coming from different lines. Also, there are many cases where a bug or problem with one source line can cause a fault in another section of code that is otherwise innocent. So the source line shown by the debugger should always be taken with a grain of salt. In this case, what happened is as follows. The compiler determines the total amount of stack space to be needed by all local variables, and allocates it by subtracting this number from the stack pointer at the very beginning of the function, in the prologue. This is more efficient than doing a separate allocation for each local variable at the point of its declaration. (Note that constructors, if any, are not called until the point in the code where the variable's declaration actually appears.) The prologue code is typically not associated with any particular line of source code, or maybe with the line containing the function's opening {. But in any case, subtracting from the stack pointer is a pure register operation; it does not access memory and therefore cannot cause a segfault by itself. Nonetheless, the stack pointer is now pointing outside the area mapped for the stack, so the next attempt to access memory near the stack pointer will segfault. The next few instructions of main execute the cout << "Starting main". This is conceptually a call to the overloaded operator<< from the standard library; but in GCC's libstdc++, the operator<< is a very short function that simply calls an internal helper function named __ostream_insert. Since it is so short, the compiler decides to inline operator<< into main, and so main actually contains a call to __ostream_insert. This is the instruction that faults: the x86 call instruction pushes a return address to the stack, and the stack pointer, as noted, is out of bounds. Now the instructions that set up arguments and call __ostream_insert are marked by the debug info as corresponding to the source of operator<<, in the <ostream> header file - even though those instructions have been inlined into main. Hence your debugger shows the crash as having occurred "inside" operator<<. Had the compiler not inlined operator<< (e.g. if you compile without optimization), then main would have contained an actual call to operator<<, and this call is what would have crashed. In that case the traceback would have pointed to the cout << "Starting main" line in main itself - misleading in a different way. Note that you can have GCC warn you about functions that use a large amount of stack with the options -Wstack-usage=NNN or -Wframe-larger-than=NNN. These are not enabled by -Wall, but could be useful to add to your build, especially if you expect to use large local objects. Specifying either of them, with a reasonable number for NNN (say 4000000), I get a warning on your main function.
69,427,533
69,427,568
How do i use hidden *this pointer?
I have this code: class Something { private: int m_value = 0; public: Something add(int value) { m_value += value; return *this; } int getValue() { return m_value; } }; int main() { Something a; Something b = a.add(5).add(5); cout << a.getValue() << endl; cout << b.getValue() << endl; } output: 5 10 I wanted add() to return the a object, so that the second add() is like (*this).add(5), but this doesn't work. However, b is good (how?). I expected a to be 10, the same as b. So, where did I miss the usage of hidden pointer? What should I do so that a.add(5).add(5) changes the m_value of a to be 10?
add() is returning *this by value, so it is returning a copy of *this, so the chained add() is modifying the copy, not the original. add() needs to return *this by reference instead: Something& add(int value) { m_value += value; return *this; } UPDATE: a initially has m_value set to 0, then a.add(5) sets a.m_value to 5 and then returns a copy of a. Then <copy>.add(5) sets <copy>.m_value to 10 and returns another copy, which is then assigned to b. That is why you see a is 5 but b is 10.
69,427,869
69,428,439
Vector sum calculation in C++ - Parallel code slower than serial
I'm trying to write a multi-threaded code that performs the sum of the elements of a vector. The code is very simple: The threads are defined through a vector of threads; The number of threads is defined by the ThreadsSize variable; Using ThreadsSize equal to 1, the sum is performed in about 300ms, while using 8 threads in 1200ms. I'm using an HW with 8 cores. Can someone explain why this happens? Theroetically I would expect to have 300/8 ms in case 8 threads are used. Is it not correct? Here the code: #include <iostream> #include "math.h" #include <vector> #include <thread> #include <mutex> #include <chrono> using namespace std; /* Parallel sum function */ void Function_Sum(mutex& Mutex, vector<double>& Vector, int unsigned kin, int unsigned kend, double& Sum) { for(int unsigned k =kin; k <= kend; k = k + 1) { Mutex.lock(); Sum = Sum + Vector[k]; Mutex.unlock(); } } /* Main function */ int main(int argc, char *argv[]) { // Threads and mutex initialization int unsigned ThreadsSize = 1; vector<thread> Threads; mutex Mutex; // Vector definition vector<double> Vector(10000000,1); // Indexes initialization int unsigned kin, kend; int unsigned dk = floor(Vector.size() / ThreadsSize); // Outout 1 cout << "VectorSize = " << Vector.size() << ", ThreadsSize = " << ThreadsSize << ", dk = " << dk << endl; // Parallel sum auto t_start = std::chrono::high_resolution_clock::now(); double Sum = 0; for(int unsigned k = 0; k <= ThreadsSize - 1; k = k + 1) { kin = k * dk; kend = (k + 1) * dk - 1; if(k == ThreadsSize - 1) { kend = Vector.size() - 1; } cout << k << " in: " << kin << ", end: " << kend << endl; Threads.push_back(thread(Function_Sum, ref(Mutex), ref(Vector), kin, kend, ref(Sum))); } // Threads joining for(int unsigned k = 0; k <= ThreadsSize - 1 ; k = k + 1) { Threads[k].join(); } // Elapsed time calculation auto t_end = std::chrono::high_resolution_clock::now(); double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count(); // Output 2 cout << "Sum = " << Sum << endl; cout << "Time = " << elapsed_time_ms << endl; } Thanks in advance.
This small modification of Function_Sum allows to obtain the speedup you desired: double sum = 0.; for(int unsigned k =kin; k <= kend; k = k + 1) sum += Vector[k]; Mutex.lock(); Sum += sum; Mutex.unlock(); Mutex is now being locked once per thread instead of once per addition. If you want a simple explanation, it's just because locking and unlocking mutex costs considerably more than addition.
69,428,431
69,428,869
LeetCode findAnagrams: addition of unsigned offset error
I am getting the following error when submitting the following code to leetcode, I dont know why, as the code runs fine on my local machine. How can I reproduce this error and figure out exactly what's causing it? Line 1061: Char 9: runtime error: addition of unsigned offset to 0x7ffdd1b0d720 overflowed to 0x7ffdd1b0d71e (basic_string.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1070:9 bool find_match(const std::map<char, std::pair<int, int>> &m){ for(const auto& [k, v] : m){ if(v.first != v.second) return false; } return true; } std::vector<int> findAnagrams(std::string s, std::string p){ std::vector<int> result; std::map<char, std::pair<int, int>> search; for(const char& c : p){ search[c].first++; search[c].second = 0; } for(int i = 0; i < s.size(); i++){ if(p.find(s[i]) != p.npos) search[s[i]].second++; if(find_match(search)) result.push_back(1 + i - p.size()); if((1 + i - p.size() >= 0) && (p.find(s[1 + i - p.size()]) != p.npos)) search[s[1 + i - p.size()]].second--; } return result; }
Store length of the string p at the beginning , then use that. vector<int> findAnagrams(string s, string p) { int pLen = p.size(); .... } Replace all p.size() in your code with pLen. Then you're good to go. Just like Mr. Sam Varshavchik explained in comment section, 1 + i - p.size() >= 0 this is causing the error. You can print the value of 1 + i - p.size() >= 0 in leetcode, you'll be able to see the error.