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,686,125
69,686,261
Merge Sort: segmentation fault c++
For some odd reason, I am getting a segmentation fault when I call the merge function. I am using g++ to compile and have tried passing in different data for the parameters, but I still get this issue. #include <iostream> using namespace std; // Merges two sorted subarrays of A[]. // First sorted subarray is A[l..m]. // Second sorted subarray is A[m+1..r]. // You might want to call this function in function mergeSort(). void merge(int A[], int l, int m, int r) { int i = 1; //Starting index for left sub array int j = m + 1; //Starting index for right sub array int k = 1; //starting index for temp int *temp = new int[r]; while (i <= m && j <= r) { if (A[i] <= A[j]) { temp[k] = A[i]; //A[i] is actually smoler than A[j] i++; k++; } else { if (A[i] <= A[j]) { temp[k] = A[i]; //A[j] is actually smoler than A[i] j++; k++; } } //Copy all elements from left sbuarray to temp while(i<=m){ temp[k] = A[i]; i++; k++; } //Copy all elements from right subarray to temp while(j<=r){ temp[k] = A[j]; i++; k++; } for(int z =0; z <r; z++){ A[z] = temp[z]; } } } // using mergeSort to sort sub-array A[l..r] // l is for left index and r is right index of the // sub-array of A[] to be sorted void mergeSort(int A[], int l, int r) { if (l < r) { int middle = l + (r - l) / 2; mergeSort(A, l, middle); mergeSort(A, middle + 1, r); merge(A, l, middle, r); } } int main() { cout << "Please enter the length (number of elements) of the input array: "; int n; cin >> n; if (n <= 0) { cout << "Illegal input array length!" << endl; return 0; } int *A = new int[n]; cout << "Please enter each element in the array" << endl; cout << "(each element must be an integer within the range of int type)." << endl; for (int i = 0; i < n; i++) { cout << "A[" << i << "] = "; cin >> A[i]; } cout << "Given array A[] is: "; for (int i = 0; i < n - 1; i++) cout << A[i] << ","; cout << A[n - 1] << endl; mergeSort(A, 0, n - 1); cout << "After mergeSort, sorted array A[] is: "; for (int i = 0; i < n - 1; i++) cout << A[i] << ","; cout << A[n - 1] << endl; delete[] A; return 0; } The merge function is the problem of my program. I have tried debugging and whatnot but cannot determine the problem.
Try using the below code :- #include<iostream> using namespace std; void merge(int arr[],int l,int m,int h) { int n1=m-l+1; int n2=h-m; int L[n1],M[n2]; for(int i=0;i<n1;i++) L[i]=arr[l+i]; for(int i=0;i<n2;i++) M[i]=arr[m+1+i]; int i=0,j=0,k=l; while(i<n1&&j<n2) { if(L[i]<=M[j]) arr[k++]=L[i++]; else arr[k++]=M[j++]; } while(i<n1) arr[k++]=L[i++]; while(j<n2) arr[k++]=M[j++]; } void mergesort(int arr[],int l,int h) { if(l>=h) return; int m=l+(h-l)/2; mergesort(arr,l,m); mergesort(arr,m+1,h); merge(arr,l,m,h); } int main() { int n; cout<<"Enter the no of element to be sorted:- "; cin>>n; int arr[1000000]; for(int i=0;i<n;i++) arr[i]=rand(); mergesort(arr,0,n-1); for(int i=0;i<n;i++) cout<<arr[i]<<endl; } here is the output on online compiler:-
69,686,145
69,689,019
Selection sort in single linked list without using swap
I have been trying to solve the selection sort in single linked list without using swap nodes. Using a temp list to store nodes and assign the current list with a new one //my addlastnode function void AddLastNODE(LIST &mylist, NODE *p) { //Check the list is empty or not if(isEmpty(mylist)) mylist.pHead = mylist.pTail = p; else mylist.pTail->pNext = p; mylist.pTail = p; } void selectionSort(LIST &mylist) { //Initialize a temp list to store nodes LIST mylisttemp; IntList(mylisttemp); //Create node NODE *p; NODE *i; //Create min node NODE *min; //Check if list is empty or has one node if(mylist.pHead == mylist.pTail) return; //Traverse the list till the last node for(p=mylist.pHead; p->pNext!=NULL && p!=NULL; p = p->pNext) { min=p; for(i=p->pNext; i!=NULL;i=i->pNext) { ////Find the smallest data in list if(i->data < min->data) min=i; } ////Add the smallest to a new list AddLastNODE(mylisttemp, min); } //Fill the current list to the new list if(!isEmpty(mylisttemp)) mylist = mylisttemp; }
Your code does not reduce the list you are selecting nodes from: the selected node should be removed from it. To make that happen, you need a reference to the node before the selected node, so that you can rewire the list to exclude that selected node. There is also a small issue in your AddLastNODE function: it does not force the tail node to have a null as pNext pointer. This may be a cause of errors when the function is called with a node that still has a non-null pNext pointer. Secondly, the indentation is off around the else block. It does not lead to a bug in this case, but still it is better to avoid the confusion: void AddLastNODE(LIST &mylist, NODE *p) { if(isEmpty(mylist)) mylist.pHead = p; else mylist.pTail->pNext = p; mylist.pTail = p; // indentation! p->pNext = nullptr; // <--- better safe than sorry! } Then to the main algorithm. It is quite tedious to work with a previous node reference when looking for the node with the minimum value. It helps a bit when you temporarily make the input list cyclic: void selectionSort(LIST &mylist) { if (mylist.pHead == mylist.pTail) return; // Make list temporarily cyclic mylist.pTail->pNext = mylist.pHead; LIST mytemplist; IntList(mytemplist); while (mylist.pHead != mylist.pTail) { // Select node: NODE * beforemin = mylist.pTail; for (NODE * prev = mylist.pHead; prev != mylist.pTail; prev = prev->pNext) { if (prev->pNext->data < beforemin->pNext->data) { beforemin = prev; } } NODE * min = beforemin->pNext; // Extract selected node: if (min == mylist.pTail) mylist.pTail = beforemin; if (min == mylist.pHead) mylist.pHead = min->pNext; beforemin->pNext = min->pNext; // And insert it: AddLastNODE(mytemplist, min); } // Move last remaining node AddLastNODE(mytemplist, mylist.pHead); // Copy back mylist = mytemplist; } As a side note: You might even want to always keep your list cyclic. This will mean some changes in other functions you may have, as there will be no pNext pointers that are null then.
69,686,201
69,686,325
returning string_view from function
I am writing a lot of parser code where string_view excels, and have gotten fond of the type. I recently read ArthurO'Dwyer's article std::string_view is a borrow type, where he concludes that string_view (and other 'borrow types') are fine to use as long as they "... appear only as function parameters and for-loop control variables." (with a couple of exceptions). However, I have lately started to use string_view as return value for functions that convert enum to string (which I use a lot), like this Compiler Explorer: #include <iostream> #include <string> #include <array> #include <algorithm> enum class Color { red, green, blue, yellow, last // Must be kept last }; constexpr std::string_view toString(Color color); // The rest would normally be in a .cpp file using cts = std::pair<Color, std::string_view>; constexpr std::array colorNames = {cts{Color::red, "red color"}, cts{Color::green, "green color"}, cts{Color::blue, "blue color"}, cts{Color::yellow, "yellow color"}}; static_assert(colorNames.size() == static_cast<size_t>(Color::last)); constexpr std::string_view toString(Color color) { // Normally calling a library function (which also checks for no match), instead of this: return std::ranges::find(colorNames, color, &cts::first)->second; } int main() { auto s1 = toString(Color::green); auto s2 = toString(Color::blue); std::cout << s1 << ' ' << s2 << std::endl; } The reasons I have for doing it this way are: By having it stored in an array as string_view, I can make the entire table constexpr. By returning the string_view directly, there is no need of converting the string representation, so the entire function can be constexpr, or at least avoid creating unnecessary strings even when called with a non-constexpr parameter. A side effect of having the table constexpr is that I can use static_assert to check that all elements of the enum are in the table, which is really great for catching additions to the enum. I really don't like having to put the 'last' enum value in there, but I don't see a better solution. So my question is really, is returning the string_view this way unsafe (or UB) in any way, or can I keep on doing this with good conscience? Alternatively, is there a better (faster/safer) way of solving this general problem of enum-to-string? Addition: After reading G. Sliepen's very good answer, I'd like to add upon my comment to his answer: I often have the opposite function as well, e.g.: constexpr Color fromString(string_view str) { // No-match handling omitted return std::ranges::find(colorNames, color, &cts::second)->first; } In those situations I really do need the translation as a separate table so that it can be used by both functions. But in many other cases, the function containing a switch statement is the simplest and best.
is returning the string_view this way unsafe (or UB) in any way, or can I keep on doing this with good conscience? Yes. The way you use it is perfectly ok. The string_view returned by your toString function forms a view on data that will remain intact until the program terminates. Alternatively, is there a better (faster/safer) way of solving this general problem of enum-to-string? You could make a constexpr function with a switch-statement inside it, like so: constexpr std::string_view toString(Color color) { switch (color) { case Color::red: return "red"; case Color::green: return "green"; ... } } There should be no difference in efficiency if the function is evaluated at compile-time. But the compiler can check if you added case-statements for all the possible Colors, and if not it will give a warning. There's also no need for a Color::last this way. Keeping both the enum and the std::array or switch-statement in sync can be annoying, especially if you have lots of enumeration values. X macros might help here.
69,686,829
69,687,040
Why do we need std::boolean and what is the use of it?
Since we already have true and false as the type bool in C++, why do we need the class std::boolean and what's the use of it? Useful links also appreciated.
std::boolean used to be a part of the C++20 draft standard (e.g. it can be found in N4835), but in the actual C++20 standard it is replaced by an exposition-only concept boolean-testable. The change happened around February 2020 as a result of adoption of P1964R2 . In either incarnation it is a concept, not a type. That is, a template that says whether its argument type can be used as a boolean. bool obviously can be used this way, but not only: integral types, pointer types, and any class that defines a conversion to bool and/or overloads boolean operators like ! and && also qualify.
69,686,934
69,687,663
Concept checking on struct members
What is the simple, idiomatic way, to check that a specific struct member validates a given concept ? I tried the following and it does not work because { T::f } yields type float&: #include <concepts> struct foo { float f; }; // ok static_assert(std::floating_point<decltype(foo::f)>); template<typename T> concept has_fp_member = requires (T t) { { T::f } -> std::floating_point; }; // fails static_assert(has_fp_member<foo>); Where can I "remove" that useless reference being added on { T::f } ? Without making the code super ugly, adding new concepts, etc... my main requirement is that things stay readable ! e.g. template<typename T> concept has_fp_member = std::floating_point<decltype(T::f)>; is very subpar, because my actual concept would check a large set of attributes, and I do not want a mess of std::foo<decltype(T::a)> && std::bar<decltype(T::b)> && ... Note that I use float as an example but my question is about a general solution for any type / concept.
You might want to use macro: #include <concepts> #include <type_traits> template <class T> std::decay_t<T> decay_copy(T&&); #define CHECK_MEMBER(name, type) \ { decay_copy(t.name) } -> type template<typename T> concept has_member_variables = requires (T t) { CHECK_MEMBER(f, std::floating_point); CHECK_MEMBER(i, std::integral); }; Demo.
69,687,078
69,687,159
Operator Overloaded for Array but not working in Main
I wrote a program to add, subtract and multiply two matrices together. I overloaded the operators +, -, and * for this purpose, but when I use them in the main, I get an error which says: no operator "+" matches these operands I can't figure out the problem. Maybe I used incorrect logic to overload the operators for class and now I'm stuck with it. The Code is below #include <iostream> #include <conio.h> #include <string> #include <ctime> using namespace std; class ERROR { public: string E = "Number of Columns of Matrix A is not Equal to Number of Rows of Matrix B"; }; class MATRIX { private: static const int number = 100; int matrix[number][number]; int n; int m; public: MATRIX(); MATRIX(int,int); void display(); MATRIX operator+(MATRIX x[]); MATRIX operator-(MATRIX x[]); MATRIX operator*(MATRIX x[]); MATRIX operator=(MATRIX x[]); }; int main() { srand(time(0)); MATRIX x(2, 2), y(2, 2); cout << "Matrix 1 " << endl; x.display(); cout << endl; cout << "Matrix 2 " << endl; y.display(); cout << endl; MATRIX z(2, 2); z = x + y; } // Constructors of Class Matrix MATRIX::MATRIX() { n = number; m = number; for (int loop = 0; loop < number; loop++) { for (int loop2 = 0; loop2 < number; loop2++) { matrix[loop][loop2] = 1 + rand() % 50; } } } MATRIX::MATRIX(int rows, int col) { n = rows; m = col; for (int loop = 0; loop < n; loop++) { for (int loop2 = 0; loop2 < m; loop2++) { matrix[loop][loop2] = 1 + rand() % 50; } } } // Display function for Class void MATRIX::display() { for (int loop = 0; loop < n; loop++) { for (int loop2 = 0; loop2 < m; loop2++) { cout << matrix[loop][loop2] << " "; } cout << endl; } cout << endl; } // Operators Overloaded for Array MATRIX MATRIX::operator+(MATRIX x[]) { MATRIX z(n,m); for (int loop = 0; loop < n; loop++) { for (int loop2 = 0; loop2 < m; loop2++) { z.matrix[loop][loop2]= matrix[loop][loop2] + x->matrix[loop][loop2]; } } return z; } MATRIX MATRIX::operator-(MATRIX* x) { MATRIX z(n, m); for (int loop = 0; loop < n; loop++) { for (int loop2 = 0; loop2 < m; loop2++) { z.matrix[loop][loop2] = matrix[loop][loop2] - x->matrix[loop][loop2]; } } return z; } MATRIX MATRIX::operator*(MATRIX x[]) { try { if (m == x->n) { MATRIX *y[number][number]; for (int loop = 0; loop < n; loop++) { for (int loop2 = 0; loop2 < m; loop2++) { for (int loop3 = 0; loop3 < m; loop3++) { y[loop][loop2] += matrix[loop][loop3] * x->matrix[loop3][loop2]; } } } return *this; } throw; } catch (ERROR e) { cout << e.E << endl; _getch(); exit(1); } } MATRIX MATRIX::operator=(MATRIX x[]) { for (int loop = 0; loop < n; loop++) { for (int loop2 = 0; loop2 < m; loop2++) { matrix[loop][loop2] = x->matrix[loop][loop2]; } } return *this; }
You've defined the operator + between a MATRIX and a MATRIX[] (i.e., an array of MATRIXs). You should amend the definition to operate on a MATRIX and another MATRIX: MATRIX operator+(MATRIX x); and of course, amend the implementation accordingly. EDIT: As Fabien mentioned in the comments, using a const reference will save copying the second operand when using this operator: MATRIX operator+(const MATRIX& x);
69,687,260
69,688,508
Undefined symbol in C++ when function which is declared in header is custom defined
I'm building a library for android. eglGetNativeClientBufferANDROID function is available for android .so above 26 but I want the library to support all the versions from API 23. So I'm linking my file with libEGL.so version 23 and dynamically loading the .so at runtime and getting the function from the .so file (this picks up the .so in the actual phone which can be of a later version). File A.cpp: ... #define EGL_EGLEXT_PROTOTYPES #include <EGL/egl.h> #include <EGL/eglext.h> // This provides declaration for eglGetNativeClientBufferANDROID #include <GLES/gl.h> ... EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID(hardwareBuffer); ... File B.cpp: // defining my custom function for it EGLClientBuffer eglGetNativeClientBufferANDROID(const struct AHardwareBuffer *buffer) { return doSomething(); } I'm linking A.cpp and B.cpp i.e both the obj files are linked to form the library. However, I get the following error: ld.lld: error: undefined symbol: eglGetNativeClientBufferANDROID which would not make sense because it has clearly been defined. This method worked for several other APIs which I dynamically loaded from libandroid.so. This made me more curious to strip down the symbols and see what is happening. I see that from A.obj: U eglGetNativeClientBufferANDROID which means that eglGetNativeClientBufferANDROID has to be looked up. From B.obj: 0000000000000000 T _Z31eglGetNativeClientBufferANDROIDPK15AHardwareBuffer So clearly it is defined but it is looking on another table to get the symbols (and not from B.obj). I was more curios and I stripped down what the other symbols from the same library would look like: For A.obj symbols for eglCreateImageKHR is declared like this: U eglCreateImageKHR Which it picks up from libEGL.so which is like this: 0000000000002000 d _DYNAMIC ... 0000000000001018 T eglCreateImageKHR Clearly libEGL.so does not provide more type details etc from its symbol. I changed eglGetNativeClientBufferANDROID to eglGetNativeClientBufferANDROIDCustom, declared it in A.cpp and everything starts working fine. I'm now very confused as to: Why eglGetNativeClientBufferANDROID is not being picked up from B.obj? What _DYNAMIC means in libEGL.so and why are the method symbols just the names and no other type info are present? (I think it is because egl only loads the functions to fps dynamically but I'm not 100% sure). Also, I did not want to change eglGetNativeClientBufferANDROID name to something else to solve this issue as I might later remove all the dynamic loading infuture. I solved it by forcefully defining the function in A.cpp like: EGLClientBuffer eglGetNativeClientBufferANDROID(const struct AHardwareBuffer *buffer) { return doSomething(); } and defining doSomething in B.cpp. Is there any other better way for this?
Why eglGetNativeClientBufferANDROID is not being picked up from B.obj? Because the exported method in B does not match the declaration in A. What _DYNAMIC means in libEGL.so and why are the method symbols just the names and no other type info are present? (I think it is because egl only loads the functions to fps dynamically but I'm not 100% sure). Because the "type infos" in your B object are the result of the C++ name mangling (as C++ allows function overloading where the same function name is used with different argument types, so the actual symbol name must contain the whole signature for the linker to find the right variant). If you write C++ and want C linkage, you have to use the extern "C" qualifier: extern "C" EGLClientBuffer eglGetNativeClientBufferANDROID(const struct AHardwareBuffer *buffer) {...}
69,687,687
69,688,385
How to print out elements of 2d vector vertically in c++?
I have a simple vector of vectors of integers. The output of the below code will be 1 2 3 4 5 6 7 8 9 10 11 I am trying to figure out how to get 1 6 9 2 7 10 3 8 11 4 5 int main() { using namespace std; vector<vector<int>> a { {1,2,3,4,5}, {6,7,8}, {9,10,11} }; for (int i = 0; i < a.size(); i++) { for (int j = 0; j < a[i].size(); j++ ) { cout << a[i][j] << " " ; } cout << endl; } return 0; }; Thank you!
In this line: cout << a[i][j] << " " ;, you just need to swap i and j. #include <iostream> #include <vector> #include <cstddef> // for std::size_t #include <algorithm> // using namespace std; is bad, so don't use it. int main() { std::vector<std::vector<int>> a {{1,2,3,4,5}, {6,7,8}, {9,10,11}}; std::size_t biggestSize{0}; for(const auto &i : a) { if(biggestSize < i.size()) { biggestSize = i.size(); } } for (std::size_t i {0}; i < biggestSize; ++i) // size() returns a std::size_t type { for (std::size_t j {0}; j < a.size(); ++j) //use postfix increment opreator instead of prefix { if(i >= a[j].size()) { std::cout << " "; } else { std::cout << a[j][i] << ' ' ; // swap i and j } } std::cout << '\n'; //use newline character instead of std::endl } return 0; }
69,688,016
69,691,118
Why is this program crashing and returning large values?
I'm trying to make a decimal to binary converter but its crashing the program. Could anyone please help #include <iostream> #include <cmath> #include <cstring> using namespace std; char *decToBin(unsigned long,int i=0); int main() { unsigned long n; cout<<"Enter number: "; cin>>n; cout<<decToBin(n)<<endl; }; char *decToBin(unsigned long dec, int i) { if(dec==1) { return "1"; } char *bin=new char[sizeof(dec)*8+1]; bin=strcat(decToBin((unsigned long)(dec/2),i+1),((dec%2==1)?"1":"0")); return bin; } It only works for 1 and for 2 it exits after 4.326 seconds and returns a return value 3221225477. I don't know the meaning of this return value. I didn't mention any return value. Also I'm instructed to use char arrays as strings I think the function creates an infinite loop and i don't know a way to fix this.
Below solution works up to 64 bit: #include <iostream> #include <bitset> int main() { unsigned long n; std::cout << "Enter n:"; std::cin >> n; if(0 == n) { std::cout << n << std::endl; } else { std::string binary = std::bitset<64>(n).to_string(); std::cout<< binary.erase(0, binary.find_first_not_of('0')) << std::endl; } return 0; } Example: dec2bin Enter n:10 1010
69,688,096
69,688,850
How do I use SIFT in OpenCV 4.2.0 with C++?
I am using visual studio 2017. Opencv and opencv verison of 4.2.0 is installed and files are generated using cmake. xfeatured2d420.lib is linked with compiler. And also #include "opencv2/xfeatures2d.hpp" #include "opencv2/xfeatures2d/nonfree.hpp" included. Extracting features using xfeatures2d::Sift giving me memory error. I need to compute sift keypoints from two images.
Mat img_1 = imread("C:/Users/Dan/Desktop/0.jpg", 1); Mat img_2 = imread("C:/Users/Dan/Desktop/0.jpg", 1); cv::Ptr<Feature2D> f2d = xfeatures2d::SIFT::create(); std::vector<KeyPoint> keypoints_1, keypoints_2; f2d->detect(img_1, keypoints_1); f2d->detect(img_2, keypoints_2); Mat descriptors_1, descriptors_2; f2d->compute(img_1, keypoints_1, descriptors_1); f2d->compute(img_2, keypoints_2, descriptors_2); BFMatcher matcher; std::vector< DMatch > matches; matcher.match(descriptors_1, descriptors_2, matches); vector<cv::DMatch> good_matches; for (int i = 0; i < matches.size(); ++i) { const float ratio = 0.8; if (matches[i][0].distance < ratio * matches[i] [1].distance) { good_matches.push_back(matches[i][0]); } } vector<Point2f> points1, points2; for (int i = 0; i < good_matches.size(); i++) { //-- Get the keypoints from the good matches points1.push_back(keypoints_1[good_matches[i].queryIdx].pt); points2.push_back(keypoints_2[good_matches[i].trainIdx].pt); } /* Find Homography */ Mat H = findHomography(Mat(points2), Mat(points1), RANSAC);
69,688,255
69,688,313
c++: how can I get access to private private attributes in base class from the subclass
I want to create a base class named Form and a subclass named ShrubberyCreationForm the problem is I have to set values to the base class using a subclass. I found a solution to solve it in the constructor but I can't find a way for it for the copy constructor and assignment operator. base class: class Form { private: std::string _Name; bool _isSigned; unsigned int _reqGradeToSign; unsigned int _reqGradeToExecute; public: Form(); Form( std::string Name, unsigned int reqGradeToSign, unsigned int reqGradeToExecute ); Form( const Form & src ); ~Form(); class GradeTooLowException: public std::exception { virtual const char * what() const throw(); }; class GradeTooHighException: public std::exception { virtual const char * what() const throw(); }; Form & operator = ( const Form & rhs ); std::string getName(); bool getisSigned(); unsigned int getReqGradeToSign(); unsigned int getReqGradeToExecute(); void beSigned( Bureaucrat & brc ); }; subclass class ShrubberyCreationForm: public Form { public: ShrubberyCreationForm(); ShrubberyCreationForm( std::string Name ); ShrubberyCreationForm( const ShrubberyCreationForm & src ); ~ShrubberyCreationForm(); ShrubberyCreationForm & operator = ( const ShrubberyCreationForm & rhs ); }; the subclass CPP: #include "ShrubberyCreationForm.hpp" ShrubberyCreationForm::ShrubberyCreationForm(): Form() {} ShrubberyCreationForm::ShrubberyCreationForm( std::string Name ): Form(Name, 145, 137) { } ShrubberyCreationForm::~ShrubberyCreationForm() { } // The problem here I don't know how to assign the values to the new object ShrubberyCreationForm::ShrubberyCreationForm( const ShrubberyCreationForm & src ) { } ShrubberyCreationForm & ShrubberyCreationForm::operator=( const ShrubberyCreationForm & rhs ) { }
The usual way to do this in C++ is to define a copy constructor in your superclass, that's responsible for copying/assigning to itself. Then, your subclass's copy constructor and assignment operator invoke it to handle the superclass. So, for example, the copy constructor would look like: ShrubberyCreationForm::ShrubberyCreationForm( const ShrubberyCreationForm & src ) : Form{src} { } Looks like you already defined the copy constructor and the assignment operator in the superclass, so this is the only missing piece. For the assignment operator this should be: Form::operator=(rhs);
69,688,471
69,688,666
Foreach loop uses more stack memory than traditional for loop?
In one of my programs I was using a for each loop that looked similar to this for(auto component : components) { doSomethingWithComponent(component); } and visual studio complained that this would cause the function to use more stack memory than the maximum, so I changed the loop to: for(int i = 0;i<components.size();i++) { doSomethingWithComponent(components[i]); } and the warning went away. Is this because a for each loop generates a reference/copy of the current iteration of object in the loop? But if that is the case, I don't think that a single struct with a few integers would consume that much memory? Is there a reason for this to occur? EDIT: components is an std::vector if that changes anything
for(auto component : components) { This is equivalent to having auto component=components[i]; being performed on each iteration of the loop. A (mostly useless) copy is made of each value in the container, on each iteration of the loop. Hence the stack usage. This is avoided simply by using a reference: for(auto &component : components) { Even better, if the loop is not supposed to modify the contents of the container: for(const auto &component : components) { And your C++ compiler will helpfully complain if, due to a bug, the loop attempts to modify the value in the container.
69,688,581
69,688,655
Accessing captured variables through explicit this parameter in lambda
From declarations / functions / 9.3.4.6 / 6.2 (i apologize on how to cite the specific sentence from standard): An explicit-object-parameter-declaration is a parameter-declaration with a this specifier. An explicit-object-parameter-declaration shall appear only as the first parameter-declaration of a parameter-declaration-list of either: (6.1) a member-declarator that declares a member function ([class.mem]), or (6.2) a lambda-declarator ([expr.prim.lambda]). If this as explicit object parameter is permitted from lambda expressions, what will happen when we capture variables at the same time? Based on my understandings, if we have lambda under the hood: [x = 2](this auto& func) { x = 4; }(); may have the rough equivalent of: class lambda01 { private: int x; public: constexpr lambda01(cons int& x_) : x{x_} {} constexpr void operator()(this lambda01& func) { func.x = 4; } }; lambda04 lambda04_obj {2}; lambda04_obj.operator()(); if it's right. For example no. 1: int x; // is it: [&x](this auto& func){ x = 4; }(); assert(x == 4); // or: [&x](this auto& func){ func.x = 2; }(); assert(x == 2); Are both expressions valid? Is lambda taking l-value object parameter valid? For example no. 2 that will print arguments in variadic: []<typename... Args>(const Args&... args) { [&](this auto func){ /** ... **/ }; }(1, 2, 3, 4); From the commented expression, which one is valid? (std::cout << args << '\n', ...) (std::cout << func.args << '\n', ...) both neither If the second choice is valid, then that would deserve another question regarding the possible parameter packs in 1 object. In short, is it valid to use captured variables accessed with dot operator in lambda taking explicit object parameter?
The standard doesn't allow it: For each entity captured by copy, an unnamed non-static data member is declared in the closure type. If it's "unnamed", then you can't name it. There's specific language that causes the name of a captured entity to be transformed into a this-based expression, but that's it. So you can take an explicit this parameter, and names of captured entities will automatically use that. But you can't access those variables through the explicit parameter. The only reason to explicitly take this in a lambda is to use the interfaces the standard provides: calling the lambda. AKA: recursively calling the lambda without naming the lambda.
69,688,667
69,689,235
OpenFOAM how to remove some elements from a List?
In OpenFOAM, I can access the list of times of my simulation, as follows: const auto& tlist = mesh.time().times(); //or runTime.times(); Just think of this in the context of a custom function object, where you want to access the list of times. When I print that list: Foam::Info << tlist << Foam::endl; and then run the function object via postProcess command, I get: 9 ( 0 constant 0 0 0.001 0.001 0.002 0.002 0.003 0.003 0.004 0.004 0.005 0.005 0.006 0.006 0.007 0.007 ) End I want to get rid of the first two elements from that list, i.e (0 constant) and (0 0). But I can't find any method to do that, all what I found is that if the object is a HashTable, then there is an erase method that removes the element by its key. Any ideas how can I remove the first two elements from my list of times tlist? or at least how can I convert that list to another data structure that will allow me to do that? Thank you Edit: Here is a link to the definition of List in the context of OpenFOAM: https://cpp.openfoam.org/v9/classFoam_1_1List.html
Disclaimer, I never used OpenFOAM. Looks like List has iterators. https://cpp.openfoam.org/v9/classFoam_1_1UList.html. So you could try something like this (assuming iterators work like I'm used to from other libraries): const auto& tlist = mesh.time().times(); //or runTime.times(); // assuming operator+ available on iterator. this will copy data auto sublist = List<instant>(tlist.begin()+2,tlist.end()); Foam::Info << sublist << Foam::endl; // or you could try to loop over the elements manually, this won't copy data for (auto it = tlist.begin()+2; it != tlist.end(); ++it ) { std::cout << *it << "\n"; } std::cout << std::endl;
69,689,519
69,689,564
Copying Byte Pattern For Floats Does Not Work
I am currently teaching myself c++ and learning all I can about memory. I found out that you can use a char pointer to copy the bit pattern of an int for example and store it in memory with casting: #include <iostream> using namespace std; int main() { int x = 20; char* cp = new char[sizeof(int)]; cp[0] = *((char*)&x); cp[1] = *((char*)&x+1); cp[2] = *((char*)&x+2); cp[3] = *((char*)&x+3); std::cout << (int)*cp; // returns 20; return 0; } the code above works, when I cast cp to a int so the compiler reads 4 bytes at a time, I get the correct number which is 20. However changing it to a float: #include <iostream> using namespace std; int main() { float x = 20; char* cp = new char[sizeof(float)]; cp[0] = *((char*)&x); cp[1] = *((char*)&x+1); cp[2] = *((char*)&x+2); cp[3] = *((char*)&x+3); std::cout << (float)*cp; // returns 0. return 0; } returns 0. Now I am a bit confused here. If I am copying every single byte, why is it still giving me a 0? If someone could help me out understanding this it would be very awesome.
(int)*cp; first dereferences the pointer, returning a char value, that is now static-casted to integers. This will only work for the range char can store - 0 255 or -128 127 and requires a little-endian system. It may seem that the way how to fix it would be *reinterpret_cast<float*>(cp); or *((float*)cp). Both are wrong and cause undefined behaviour because they break the strict aliasing rule. The strict aliasing rule states that one can dereference a pointer to T only if there exists an object of type T at the memory location the pointer points to. With exception of char, std::byte, unsigned char. Meaning it is correct to inspect any type through cast to char, but one cannot simply interpret bunch of bytes as a random T. The correct way to serialize and deserialize objects is: #include <iostream> using namespace std; int main() { float x = 20.0f; // This is safe. char* cp1 = reinterpret_cast<char*>(&x); // Also safe because there is a float object at cp1. std::cout << *reinterpret_cast<float*>(cp1); // No need for dynamic allocation. char cp2[sizeof(float)]; // Copy the individual bytes into a buffer. // = Serialize the object. std::memcpy(cp2, &x, sizeof(x)); // NOT SAFE, UNDEFINED BEHAVIOUR // There is no float object at cp2. std::cout << *reinterpret_cast<float*>(cp2); // Deserialization through copy float y; std::memcpy(&y, cp2, sizeof(y)); // Safe std::cout << y; return 0; }
69,689,600
69,706,641
The same assembly code with and without (__restrict) in Visual Studio C++
I would like to compare the effect of producing assembly code in C++ by Visual Studio with and without __restrict keyword. So, I used the standard C++ example on the Microsoft website as below "https://learn.microsoft.com/nl-nl/cpp/cpp/extension-restrict?view=msvc-160" The main.cpp file contains: //In main.cpp file #include <iostream> #include <chrono> #include "functions.h" using namespace std::chrono; int main() { int* a = new int[MAX]; int* b = new int[MAX]; int* c = new int[MAX]; int* d = new int[MAX]; int n = MAX; //initialize a, b, c and d arrays for (int i = 0; i < MAX; i++) { a[i] = (float) i; b[i] = (float) i; c[i] = (float) i; d[i] = (float) i; } auto start = high_resolution_clock::now(); sum2(n, a, b, c, d); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); std::cout << "Time taken by function: " << duration.count() << " microseconds" << std::endl; return 0; } The functions.h file contains: #define MAX 1000000 void sum2(int n, int* __restrict a, int* __restrict b, int* c, int* d); The functions.cpp file contains: #include "functions.h" void sum2(int n, int* __restrict a, int* __restrict b, int* c, int* d) { int i; for (i = 0; i < n; i++) { a[i] = b[i] + c[i]; c[i] = b[i] + d[i]; } } After compiling the code with /LD flag with and without __restrict keyword, I always see the same assembly code. I wonder if that means that the compiler does not care about __restrict keyword?
The answer is that I should use the /O2 flag when compiling the code. This flag will optimize the code and apply the effect of the __restrict keyword.
69,689,603
69,690,447
Why does gcc can't find opencv.hpp file?
I'm quite new to CMake, but I want to build a test .cpp file that includes OpenCV and shows me an image. I have built OpenCV in the path /usr/local and I have here folder with opencv.hpp file - /usr/local/include/opencv4/opencv2/opencv.hpp. Here is my CMakeLists.txt file: cmake_minimum_required(VERSION 3.0) project(cpp_proj) find_package(OpenCV REQUIRED) add_executable(cpp_proj opencv_cpp.cpp) include_directories(${OPENCV4_INCLUDES}) target_link_libraries(cpp_proj ) I opened ~./bashrc and added there lines: export OPENCV4_INCLUDES=/usr/local/include/ export OPENCV4_LIBRARIES=/usr/local/lib/ export PATH=$PATH:$OPENCV4_LIBRARIES export PATH=$PATH:$OPENCV4_INCLUDES When I run cmake in bash - everything is ok and even find_package finds OpenCV. But when I'm trying to run make it gives me a error: pi@raspberrypi:~/Desktop/cpp_proj/build $ cmake .. -- Configuring done -- Generating done -- Build files have been written to: /home/pi/Desktop/cpp_proj/build pi@raspberrypi:~/Desktop/cpp_proj/build $ make [ 50%] Building CXX object CMakeFiles/cpp_proj.dir/opencv_cpp.cpp.o /home/pi/Desktop/cpp_proj/opencv_cpp.cpp:1:10: fatal error: opencv2/opencv.hpp: No such file or directory #include <opencv2/opencv.hpp> ^~~~~~~~~~~~~~~~~~~~ compilation terminated. make[2]: *** [CMakeFiles/cpp_proj.dir/build.make:63: CMakeFiles/cpp_proj.dir/opencv_cpp.cpp.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/cpp_proj.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 I found questions with the same problem, but they didn't help me. What I am doing wrong? What could be the reason of this? Thanks!
In order to use a library you must specify the include directory as well as the libs. With find_package (in module mode), in your case it should populate the variables OpenCV_INCLUDE_DIRS and OpenCV_LIBS for you to use. So I recommend to add / alter your code to add the include directory & link the library (such as below) target_include_directories(${CMAKE_PROJECT_NAME} public ${OpenCV_INCLUDE_DIRS}) target_link_libraries(${CMAKE_PROJECT_NAME} public ${OpenCV_LIBS}) I don't believe you ever need to touch ~./bashrc when using find_package
69,689,938
69,690,521
QueueUserAPC function not working, reporting error 31 randomly
The following code uses the QueueUserAPC function to add commands to a dispatcher thread in order to synchronize console output. #include <Windows.h> #include <iostream> constexpr auto fenceName = L"GlobalFence"; constexpr auto dispatchCloser = L"GlobalDispatchStop"; constexpr int threadCount = 5; DWORD WINAPI pure(LPVOID lpThreadParameter) { const HANDLE dispatchCloseEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, dispatchCloser); while(WaitForSingleObjectEx(dispatchCloseEvent, INFINITE, TRUE) != WAIT_IO_COMPLETION)continue; return 0; } HANDLE dispatcher; int main() { const HANDLE dispatchCloseEvent = CreateEventW(nullptr, TRUE, FALSE, dispatchCloser); dispatcher = CreateThread(NULL, 1024, &pure, 0, 0, NULL); const HANDLE g_FenceEvent = CreateEventW(nullptr, TRUE, FALSE, fenceName); HANDLE threads[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = CreateThread(NULL, 1024*1024, [](LPVOID) -> DWORD { DWORD d = QueueUserAPC(([](ULONG_PTR) {std::cout << "thread opened\n"; }), dispatcher, NULL); if(d == 0)std::cout << GetLastError() << std::endl; HANDLE a = OpenEventW(EVENT_ALL_ACCESS, FALSE, fenceName); WaitForSingleObject(a, INFINITE); d = QueueUserAPC([](ULONG_PTR) {std::cout << "thread released\n"; }, dispatcher, NULL); if (d == 0)std::cout << GetLastError() << std::endl;//often reports error 31 return 0; }, 0, 0, NULL); } Beep(300, 300);//the length of the delay effects the behavior, somehow. SetEvent(g_FenceEvent); SetEvent(dispatchCloseEvent); WaitForMultipleObjects(threadCount, threads, TRUE, INFINITE); WaitForSingleObject(dispatcher, INFINITE); SetEvent(dispatchCloseEvent); for (int i = 0; i < threadCount; i++) CloseHandle(threads[i]); CloseHandle(g_FenceEvent); CloseHandle(dispatchCloseEvent); } The code executes correctly about 40% of the time. Sometimes (although this is somewhat rare) the "thread opened" text won't get written to the console the right amount of times, but no error is reported from getLastError()
As soon as the loop in pure() receives its 1st APC notification, the loop breaks and pure() exits, terminating the thread. Error 31 is ERROR_GEN_FAILURE, and per the QueueUserAPC() documentation: When the thread is in the process of being terminated, calling QueueUserAPC to add to the thread's APC queue will fail with (31) ERROR_GEN_FAILURE. If you expect the dispatcher thread to process more than one APC notification, it needs to stay running. You meant to use == instead of != in your loop condition: while (WaitForSingleObjectEx(dispatchCloseEvent, INFINITE, TRUE) == WAIT_IO_COMPLETION) continue; That way, if the wait exits due to a queued APC, the loop will go back to waiting for the next APC. The loop will break, exiting pure() to terminate the thread, only when it receives a return value other than an APC notification, such as WAIT_OBJECT_0 when the close event is signaled. Another problem I see is that you are signaling dispatchCloseEvent too soon, so the dispatcher thread can stop running while the fenced threads are still trying to queue APCs to it. That is why the 2nd call to QueueUserAPC() in each fenced thread fails randomly. You need to wait for all of the fenced threads to finish first, THEN signal the dispatcher to stop running. SetEvent(g_FenceEvent); WaitForMultipleObjects(threadCount, threads, TRUE, INFINITE); SetEvent(dispatchCloseEvent); // <-- move here! WaitForSingleObject(dispatcher, INFINITE); Also, all of your threads are leaking the HANDLEs they open with OpenEventW(). You need to call CloseHandle() on them, per the OpenEventW() documentation: Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed. For that matter, you don't really need OpenEventW() at all. You can pass the existing HANDLEs from main() to each thread via their LPVOID parameter instead: DWORD WINAPI pure(LPVOID lpThreadParameter) { HANDLE dispatchCloseEvent = (HANDLE) lpThreadParameter; ... return 0; } CreateThread(..., &pure, dispatchCloseEvent, ...); CreateThread(..., [](LPVOID param) -> DWORD { HANDLE a = (HANDLE) param; ... }, g_fenceEvent, ...); Or, just use global variables instead. Either way, with OpenEventW() eliminated, there is no more need to assign names to your events when calling CreateEventW(), thus no longer exposing them to potential interference from outside code. Also, you are also not closing the dispatcher thread's HANDLE either, like you are closing the fenced threads' HANDLEs.
69,690,358
69,690,765
Problem with throw exceptions when stack are empty ..... Queue / stack implementation
I need to throw an exception when both stacks are empty but i dont know how I should write it. I have to implement a queue with 2 stacks! this is main #include "QueueFromStacks.h" int main() { /* THIS IS JUST TO SHOW YOU HOW #include <stack> WORKS stack<int> st1; stack<int> st2; cout << "Size before push:" << st2.size() << "\n"; st2.push(2); st2.push(5); cout << "Size after two pushes:" << st2.size() << "\n"; cout << st2.top() << "\n"; st2.pop(); cout << "Size of st2 after one pop:" << st2.size() << "\n"; st1.push(st2.top()); st2.pop(); cout << "Size of st1:" <<st1.size()<< " Size of st2:"<< st2.size(); */ QueueFromStacks<int> qfs; qfs.QueueFromStacks(); qfs.enqueue(1); qfs.enqueue(2); qfs.enqueue(3); qfs.dequeue(); cout << "Queue Front : " << (qfs.front())<< endl; // You have to implement QueuefromStack // The logic of the queue remains the same(FIFO) but you have to use the two stacks to store your elements // In the main program create a queuefromstack object and use your implemented methods to clearly show us what u did return 0; } HEADER FILE #ifndef QUEUEFROMSTACKS_H_ #define QUEUEFROMSTACKS_H_ #include <iostream> #include <stack> #include <string> using namespace std; class QueueEmptyException{ public: QueueEmptyException(); ~QueueEmptyException(); string getMessage() { return "Queue is empty"; } }; template <typename E> class QueueFromStacks { public: QueueFromStacks(); ~QueueFromStacks(); int size() const; bool empty() const; const E& front() const throw(QueueEmptyException); void enqueue (const E& e); void dequeue() throw(QueueEmptyException); private: stack<E> st1; stack<E> st2; int numElements; }; #endif /* QUEUEFROMSTACKS_H_ */ IMPLEMENTATION #include "QueueFromStacks.h" template <typename E> QueueFromStacks<E>::QueueFromStacks() { numElements = 0; } template <typename E> QueueFromStacks<E>::~QueueFromStacks() { // TODO Auto-generated destructor stub } template <typename E> int QueueFromStacks<E>::size() const { return numElements; } template <typename E> bool QueueFromStacks<E>::empty() const { return (size() == 0); } template <typename E> const E& QueueFromStacks<E>::front() const throw(QueueEmptyException) { return st2.top(); // don't forget to check for empty and throw exception if it is empty. } template <typename E> void QueueFromStacks<E>::enqueue (const E& e) { st2.push(e); numElements++; } template <typename E> void QueueFromStacks<E>::dequeue() throw(QueueEmptyException) { **// if both stacks are empty // here i dont know what should i put as a throw condition if (st1.empty() && st2.empty()) { throw; }** // if the second stack is empty, move elements from the first stack to it if (st2.empty()) { while (!st1.empty()) { st2.push(st1.top()); st1.pop(); } // or make a call to swap(s1, s2) } // return the top item from the second stack int top = st2.top(); st2.pop(); numElements--; }
You need to change this: void QueueFromStacks<E>::enqueue (const E& e) { st2.push(e); numElements++; } to this: void QueueFromStacks<E>::enqueue (const E& e) { st1.push(e); numElements++; }
69,690,872
69,690,899
Visual C++ - folder structure
I have started to learn C++ and i stuck in front of MSVC. Have you any idea about why MSVC have this folder structure? What is the purpose 'x64' folder inside 'Hostx86'? enter image description here
Hostx86/x64 means the toolset (compiler, linker, etc) that is running on x86 32-bit host (that is 32-bit x86 applications), but produces x64 binaries.
69,690,969
69,701,037
C++ Exception Thrown while trying to debug
I am trying to learn C++ with a given tutorial. I've tried to write some code. Visual studio says, there's no error, but when I'm trying to start debugging, it does not work. Can someone help me. I am getting the following Exception thrown. Here's the error message: https://prnt.sc/1x6qqgc #include <iostream> #include <string> using namespace std; class Question { private: string text; string choices[3]; string answer; public: Question(string text, const string choices[3], string answer) { this->text = text; this->choices[3] = choices[3]; this->answer = answer; } bool checkAnswer(string answer) { return this->answer == answer; } string getText() { return this->text; }; }; class Quizz { private: Question* questions[5]; int score = 0; int questionIdx = 0; public: Quizz(Question questions) { this->questions[5] = &questions; }; Question* getQuestions() { return questions[questionIdx]; }; void displayQuestion() { Question* questions = getQuestions(); cout << questionIdx + 1 << " / " << 5 << "Question : " << questions->getText(); }; }; int main() { const string cho[3] = { "Carl","Mike","Jason" }; Question q1 = {"Who has a dog?", cho, "Carl"}; Question q2 = { "Who has a cat", cho , "Mike" }; Question q3 = { "Who knows i have a cat ", cho , "Mike" }; Question q4 = { "Who knows i haven't got a dog", cho , "Carl" }; Question q5 = { "Who knows i live in LA", cho , "Jason" }; Question questions[5] = { q1,q2,q3,q4,q5 }; Quizz quiz(questions[5]); quiz.displayQuestion(); return 0; }
It's solved, thank you for your helps. #include <iostream> #include <string> using namespace std; class Question { private: string text; string choices[3]; string answer; public: Question(string textt, string choices[] , string answerr) { text = textt; for (int i = 0; i < 3 ; i++) { this->choices[i] = choices[i]; } answer = answerr; } bool checkAnswer(string answer) { return this->answer == answer; } string getText() { return this->text; }; }; class Quizz { private: Question* questions[5]; int score = 0; int questionIdx = 0; public: Quizz(Question questions[]) { for (int i = 0; i < 5; i++) { this->questions[i] = &questions[i]; } }; Question* getQuestions() { return questions[questionIdx]; }; void displayQuestion() { Question* questions = getQuestions(); cout << questionIdx+1 << " / " << 5 << "Soru : " << questions->getText(); }; }; int main() { const string cho[3] = { "Carl","Mike","Jason" }; Question q1 = {"Who has a dog?", cho, "Carl"}; Question q2 = { "Who has a cat", cho , "Mike" }; Question q3 = { "Who knows i have a cat ", cho , "Mike" }; Question q4 = { "Who knows i haven't got a dog", cho , "Carl" }; Question q5 = { "Who knows i live in LA", cho , "Jason" }; Question questions[5] = {q1,q2,q3,q4,q5}; Quizz quiz(questions); quiz.displayQuestion(); return 0; }
69,691,035
69,691,265
Problems with template argument deduction when extending std::span
I am trying to extend std::span to have a bounds checked operator[] (I am aware gsl::span provides this) I have declared my container as follows: #include <span> #include <string> #include <utility> #include <stdexcept> template <typename ... TopArgs> class BoundsSpan : private std::span<TopArgs...> { public: typename std::span<TopArgs...>::reference operator[](std::size_t idx) const { if (idx >= this->size()) [[unlikely]] { throw std::out_of_range(std::string("span out of bounds access detected - wanted index [" + std::to_string(idx) + "] but size is " + std::to_string(this->size()))); } return std::span<TopArgs...>::operator[](idx); } template<typename ... Args> BoundsSpan(Args&& ... args) : std::span<TopArgs...>(std::forward<Args>(args) ...) {} }; This seems to work great, however I noticed that template argument deduction no longer works. E.g. int main(int argc, char *argv[]) { BoundsSpan span(argv, argc); } gives a "Too few template arguments for class template 'span'" and requires an explicit BoundsSpan<char*> instead - this is not the case with regular std::span Additionally, constructing a BoundsSpan on a C-style array with runtime length gives a "variably modified type cannot be used as a template argument" - did I overlook a template specialization here? An example reproducer would be void func(int len) { int arr[len]; BoundsSpan<int> span(arr, len); }
The std::span template parameter list is not compatible with your variadic parameter list. It takes: template <typename T, std::size_t N> class span {...}; However, your class is working in terms of a variadic type list. There is no way for you to propagate the template parameters "up" to the span base when it wants a non-type template parameter, and you only pass types. It's best to try matching the template signature of the span you're impersonating. That brings some simplifications to the problems: you can expose all of the span constructors as your own (i.e. using std::span<T, N>::span;) You can use the same deduction guides that the std::span has, renamed for your class. Here's a revised version of your code that I found to be functional: template <class T, std::size_t N = std::dynamic_extent> class BoundsSpan : private std::span<T, N> { public: using std::span<T, N>::span; using std::span<T, N>::data; using std::span<T, N>::size; // .. and all the other interface functions typename std::span<T, N>::reference operator[](std::size_t idx) const { if (idx >= this->size()) [[unlikely]] { throw std::out_of_range("span out of bounds - wanted index [" + std::to_string(idx) + "] but size is " + std::to_string(size())); } return std::span<T, N>::operator[](idx); } }; Then taking std::span's deduction guides for inspiration yields: template <class It, class EndOrSize> BoundsSpan(It, EndOrSize) -> BoundsSpan<std::remove_reference_t<std::iter_reference_t<It>>>; template<class T, std::size_t N> BoundsSpan(T (&)[N]) -> BoundsSpan<T, N>; template<class T, std::size_t N> BoundsSpan(std::array<T, N>&) -> BoundsSpan<T, N>; template<class T, std::size_t N> BoundsSpan(const std::array<T, N>&) -> BoundsSpan<const T, N>; template<class R> BoundsSpan(R&&) -> BoundsSpan<std::remove_reference_t<std::ranges::range_reference_t<R>>>; With this it should work in your examples and like span. You might want to also wrap the const version of operator[]. https://godbolt.org/z/7ec3PYe7e
69,691,682
69,734,674
Alternate scenes in a QGraphicsView
I have multiple QGraphicsScene objects that should be drawn into a single QGraphicsView at different times. Once I've assigned a scene to a view via setScene member function it's possible to change the viewed scene with another? Is it safe to assign nullptr via setScene if I don't want to show any scene or I have to pass a valid pointer each time? Example class MyViewer : public QObject{ Q_OBJECT QGraphicsView sc; QGraphicsScene scenes[10]; int i; public: //.... QGraphicsView *getView() { return &sc;} //called by a QTime event for example void update(){ if(i >= 10) i = 0; sc.setScene(&(scene[i])); i++; } }; int main(int n, const char **a){ QApplication app(n, a); MyViewer vw; /* * Do some stuffs, initialize and connect a QTimer */ vw.getView()->show(); app.exec(); }
It's possible to change the viewed scene with another? You can change the scene whenever you want, the documentation does not indicate a prohibition so you can do it. Is it safe to assign nullptr via setScene if I don't want to show any scene or I have to pass a valid pointer each time? Qt checks if the pointer is valid and accordingly performs the actions so it is safe to pass nullptr to remove the previous scene. In Qt when something is dangerous and not allowed then it will be explicitly indicated in the documentation. It is also easy to see the source code to understand the behavior.
69,691,722
69,691,736
How do we know if a pointer was allocated with new or new[]?
I'm trying to implement a unique_ptr class in C++, but how to know if the pointer we passed to it was allocated with new or new[] without using default_delete (my school standard doesn't allow c++11). I mean when you pass your pointer to the constructor like this for example: unique_ptr<int> ptr(new int[10]); how do you know inside of the class if you need to call delete[] or delete ?
You can't tell. And neither can std::unique_ptr. Think about it. If it could be determined automatically, you wouldn't need two kinds of delete. std::unique_ptr<int> ptr(new int[10]); is wrong, since it will call delete, rather than delete[]. Use std::unique_ptr<int[]> ptr(new int[10]); instead, which will call delete[], rather than delete.
69,691,956
69,692,025
Decrementing inside of an if statement C++
I am confused as to how to have equivalent logic without having the the decrement inside of the if statement. if(A && !B && !(C--)) { } I thought that this is equivalent to: if(A && !B && !(C)) { C--; }
In the first example, C is decremented if the first two conditions are true. In the second example, C is decremented if all three conditions are true. The difference is that if !C is not true (the third condition is false), the first example will decrement C while the second will not.
69,691,960
69,785,978
C++ jsoncons : cbor to json
I would like to convert cbor into json using the C++ jsoncons library (https://github.com/danielaparker/jsoncons/blob/master/doc/ref/cbor/cbor.md). But when I print the result to console some entries are weird. My Code: const std::vector<uint8_t> data1 = { 0xa4, 0x01, 0x58 , 0x65 , 0x83 , 0x43 , 0xa1 , 0x01 , 0x0a , 0xa1 , 0x05 , 0x4d , 0xba , 0xe3 , 0xff , 0x8c , 0x34 , 0x9e , 0x98 , 0x15 , 0xe1 , 0x79 , 0x85 , 0x4c , 0xec , 0x58 , 0x4e , 0x7b , 0x3e , 0x19 , 0x05 , 0x32 , 0x00 , 0x79 , 0x72 , 0x8f , 0x48 , 0xe4 , 0xe0 , 0x12 , 0x96 , 0xb2 , 0xd9 , 0x84 , 0xfd , 0xd5 , 0x62 , 0x7e , 0x42 , 0x6d , 0x68 , 0xe9 , 0xde , 0xe2 , 0xf2 , 0xc4 , 0xef , 0xe6 , 0xf2 , 0x72 , 0x76 , 0xad , 0xee , 0xbf , 0x17 , 0x06 , 0x91 , 0xca , 0x15 , 0x7f , 0x09 , 0x45 , 0x08 , 0x67 , 0xdc , 0xeb , 0x7d , 0xf8 , 0xeb , 0xea , 0x02 , 0x01 , 0x99 , 0x7a , 0xc0 , 0xc6 , 0x7b , 0x17 , 0xf2 , 0x2e , 0xd5 , 0x76 , 0x9d , 0x88 , 0xc0 , 0xfc , 0x20 , 0x41 , 0x7d , 0x9d , 0x8a , 0x17 , 0x91 , 0xec , 0x01 , 0x06 , 0x1a , 0x61 , 0x73 , 0x19 , 0x72 , 0x07 , 0x01 , 0x08 , 0xa1 , 0x01 , 0xa2 , 0x01 , 0x04 , 0x20 , 0x50 , 0xf7 , 0x77 , 0xd3 , 0xb7 , 0x82 , 0x01 , 0xef , 0x29 , 0x49 , 0x09 , 0xde , 0xe0 , 0x8b , 0x7a , 0xd3 , 0x59}; json j = cbor::decode_cbor<json>(data1); // Pretty print std::cout << "(1)\n" << pretty_print(j) << "\n\n"; And the Output is: (1) { "1": "g0OhAQqhBU264_-MNJ6YFeF5hUzsWE57PhkFMgB5co9I5OASlrLZhP3VYn5CbWjp3uLyxO_m8nJ2re6_FwaRyhV_CUUIZ9zrffjr6gIBmXrAxnsX8i7Vdp2IwPwgQX2diheR7AE", "6": 1634933106, "7": 1, "8": { "1": { "-1": "93fTt4IB7ylJCd7gi3rTWQ", "1": 4 } } } Everything seems fine but compared to an online Tool to convert cbor to string (http://cbor.me/). The results are different Output from online Tool (the expected output): { "1": h'8343A1010AA1054DBAE3FF8C349E9815E179854CEC584E7B3E1905320079728F48E4E01296B2D984FDD5627E426D68E9DEE2F2C4EFE6F27276ADEEBF170691CA157F09450867DCEB7DF8EBEA0201997AC0C67B17F22ED5769D88C0FC20417D9D8A1791EC01', "6": 1634933106, "7": 1, "8": { "1": { "-1": h'F777D3B78201EF294909DEE08B7AD359', "1": 4 } } } Values of 1 and -1 are different which I dont understand. I would guess that typing is the problem but I dont know how I can print the values of 1 and -1 properly. This might help (https://github.com/danielaparker/jsoncons/blob/master/doc/ref/cbor/cbor.md). It shows the type conversion from cbor to json but I still struggle with printing the values of 1 and -1 correctly (the only ones I really need).
The values in your output are base64-encoded, but you expect them in hex. See Base64 decode snippet in C++ for help with decoding in C++. Or see this example from the jsoncons documentation.
69,692,056
69,692,090
Prevent heap allocations in a function?
In C++, is there any way to ensure that a function does no heap allocations? I am imagining something like this would be very useful in a non-release build. int doSomething() { enable_no_heap_allowed(); // Do lots of complex work. // Program would crash/assert here if heap is allocated to. disable_no_heap_allowed(); } Currently it seems like in order to determine if a heap allocation happens I would have to actually audit all the code being run (including all nested functions). Does such functionality exist? Are there any languages other than C++ which have such a feature?
You could have enable_no_heap_allowed() increment a thread-local int, and decrement_no_heap_allowed() decrement it. Then write a global-new operator that checks the thread-local variable and throws an exception/assert if it’s non-zero, or allocates the requested memory otherwise. Note that this approach isn't a full solution since it only looks at calls to the new and delete operators; as @HolyBlackCat points out, heap-accesses that are done by directly calling malloc() or free() or other C-level heap-manipulation functions will not be detected. Regardless, here is some C++11 example code (which btw you can use to figure out what std::string considers a "short string" for purposes of its short-string optimization): #include <stdio.h> #include <string> static thread_local int _heapDisallowedCount = 0; void begin_no_heap_allowed() {_heapDisallowedCount++;} void end_no_heap_allowed() {_heapDisallowedCount--;} void check_heap_allowed(const char * desc, size_t numBytes) { if (_heapDisallowedCount != 0) { printf("ERROR, heap access in heap-disallowed section (reported by %s, %zi bytes)\n", desc, numBytes); // add code to assert() or throw an exception here if you want } } void * operator new(size_t s) throw(std::bad_alloc) { check_heap_allowed("operator new", s); void * ret = malloc(s); if (ret == NULL) throw std::bad_alloc(); return ret; } void * operator new[](size_t s) throw(std::bad_alloc) { check_heap_allowed("operator new[]", s); void * ret = malloc(s); if (ret == NULL) throw std::bad_alloc(); return ret; } void operator delete(void * p) throw() { check_heap_allowed("delete", -1); return free(p); } void operator delete[](void * p) throw() { check_heap_allowed("delete[]", -1); return free(p); } static void SomeFunction() { char buf[256]; fgets(buf, sizeof(buf), stdin); char * newline = strchr(buf, '\n'); if (newline) *newline = '\0'; printf("You typed: [%s]\n", buf); std::string s(buf); printf("As a std::string, that's: [%s]\n", s.c_str()); } int main(int, char **) { printf("Enter a string:\n"); SomeFunction(); printf("Enter another string (now with new/delete calls being detected:\n"); begin_no_heap_allowed(); SomeFunction(); end_no_heap_allowed(); return 0; }
69,692,150
69,692,178
Mathematical constant cannot be accessed
#include<numbers> int main(){ double x = pi; } on C++ 20 throws the error: error: 'pi' was not declared in this scope I'm fairly new to C++, what could be wrong? What was wrong? The compiler wasn't ready for this. I updated it and added -std=c++20 at compile time.
The constant pi: Requires C++20 And is defined in the std::numbers namespace. You must verify that your compiler implements at least this part of C++20, and provide any required compilation flags for C++20 support, as well as either replace the reference to fully-qualified std::numbers::pi, or add using namespace std::numbers, or maybe a few other aliasing alternatives that you will find explained in your C++ textbook.
69,692,722
69,692,954
How can I have a function pointer template as a template parameter?
I am trying to create a class template that expects a type and a function pointer as template parameters. The function pointer is expected to be a member function of the type passed in. I want the user of the class template to be able to pass in a void member function of the type passed in. That member function will then be called on instances of the type passed in every time a certain function of the class template is called. It's a bit hard to explain but it's supposed to work sort of like this: template<Type, Function> // For the purpose of explaining it class Foo { public: template<Args... args> void callOnAll(Args... args) { for(Type* ptr : ptrs_) { ptr->Function(std::forward<Args>(args)...); } } private: std::vector<Type*> ptrs_; } Assuming that something like this is possible (which I realize it might not be), the key would have to be getting the template parameters for the class right, and getting the update function right. This is what I've come up with but I still can't get it to work: template<typename T, template<typename... Args> void(T::*func)(Args... args)> class EngineSystem { public: template<typename... Args> void update(Args... args) { for (T* handler : handlers_) { ((*handler).*func)(std::forward<Args>(args)...); } } private: std::vector<T*> handlers_; }; The code above does not compile. It points me to the line where I declare the template parameters for the class, underlines void and says expected 'class' or 'typename'. Is it clear what I'm trying to achieve, and is it possible?
C++ doesn't allow non-type template template parameters. That means you can't have a parameter-pack for your member-function pointer parameter. Assuming you're using C++17 or newer, you can use an auto template parameter instead: template<typename T, auto func> public: template<typename... Args> void update(Args... args) { for (T* handler : handlers_) { (handler->*func)(std::forward<Args>(args)...); } } private: std::vector<T*> handlers_; }; Live Demo Technically that will accept any object for func, but assuming update is called, then (handler->*func)(std::forward<Args>(args)...) still has to be well-formed or compilation will fail. If you want compilation to fail even if update never gets called, you could use some type traits and a static_assert (or some SFINAE hackery, if you need it) to ensure that func is actually a pointer to a member function of T: template <typename T, typename U> struct IsPointerToMemberOf : std::false_type {}; template <typename T, typename U> struct IsPointerToMemberOf<T, U T::*> : std::true_type {}; template <typename T, typename U> struct IsPointerToMemberFunctionOf : std::integral_constant< bool, IsPointerToMemberOf<T, U>::value && std::is_member_function_pointer<U>::value > {}; template<typename T, auto func> class EngineSystem { static_assert(IsPointerToMemberFunctionOf<T, decltype(func)>::value, "func must be a pointer to a member function of T"); //... }; Live Demo
69,692,790
69,692,917
Is something::something something() also a way to use scope resolution operator?
I was trying to understand a C++ program which used point cloud library and in that code I came across a strange syntax - pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); I read about scope resolution operator but I am still confused whether or not this ''cloud_normals'' is a function of Ptr library. Can someone help me understand whats happening in this line of code?
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); Here cloud_normals is a shared pointer to a PointCloud which contains pcl::Normal types. Check here. This line is creating an object of type PointCloud<pcl::Normal> and assigning it to the share pointer cloud_normals.
69,692,853
69,693,205
Is C++11's std::thread compatible with POSIX semaphores?
I want to use threads in my C++ application by using the standard C++ std::thread library, however y wanted to use semaphores and using the C++20's semaphores wasn't possible, I wanted to know if POSIX semaphores <semaphore.h> is compatible with C++ STD's Threads or I have to change my code in order to use POSIX threads
The C++ standard library will implement std::thread as a wrapper over pthreads on POSIX systems, so using <semaphore.h> would be fine. Semaphores are usually implemented regardless of the specific threading interface, though the C standard library may do some book-keeping at the same time using pthreads. For this reason, calling sem_wait() from a thread (whether it be a pthread_t or an std::thread) will have the same effect, though it may be better to just use pthreads, as they would be the most "compatible", especially since you are only targeting POSIX systems anyway.
69,693,109
69,701,790
Read Access violation when running gui.get<typename>("") with sfml backend in TGUI
I'm currently trying to use TGUI with SFML as the backend, everything works fine when I had this code #include <iostream> #include <TGUI/TGUI.hpp> int main() { sf::RenderWindow window{ {800, 600}, "TGUI window with SFML" }; tgui::GuiSFML gui{ window }; gui.loadWidgetsFromFile("menus/startMenu.txt"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { gui.handleEvent(event); if (event.type == sf::Event::Closed) { window.close(); } } window.clear(); gui.draw(); window.display(); } } However, I then tried to add a line to refer to a button loaded from tgui::Button::Ptr aButton = gui.get<tgui::Button>("a");. #include <iostream> #include <TGUI/TGUI.hpp> int main() { sf::RenderWindow window{ {800, 600}, "TGUI window with SFML" }; tgui::GuiSFML gui{ window }; gui.loadWidgetsFromFile("menus/startMenu.txt"); tgui::Button::Ptr aButton = gui.get<tgui::Button>("a"); // right here while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { gui.handleEvent(event); if (event.type == sf::Event::Closed) { window.close(); } } window.clear(); gui.draw(); window.display(); } } and it gives me this error Exception thrown at 0x7956271B (tgui.dll) in maze 2.exe: 0xC0000005: Access violation reading location 0x000003E4 I'm currently dynamically linking tgui and sfml, using TGUI-0.9 and SFML-2.5.1 with Debug x86 on Visual Studio c++. The error also tells me it's coming from template <class T> typename T::Ptr get(const String& widgetName) const { return std::dynamic_pointer_cast<T>(get(widgetName)); } in Container.hpp in TGUI. I think that the problem is the dynamic_pointer_cast throwing an error, but I don't know how to fix it. I also don't understand why everything else works except the gui.get<typename>("sometext"); function. Any help? Edit 1: I've gone ahead and tested with gui.get(), which works perfectly fine. This means that the problem is definitely in the dynamic_pointer_cast, since gui.get<typename>() just calls gui.get() and runs dynamic_pointer_cast on it.
Ok so I just had to restart Visual studio, and it now works perfectly
69,693,750
69,693,751
How to disable specific compilation warnings from CPP compiler in VSCode? (preferably using build options)
I am using VSCode and ESP-IDF to program Arduino. Some of the Arduino library files are generating warnings such as below. 988/1135] Building CXX object esp-idf/arduino/CMakeFiles/__idf_arduino.dir/libraries/WiFi/src/WiFiScan.cpp.obj /Users/sr/projects/gcp-iot/components/arduino/libraries/WiFi/src/WiFiScan.cpp:45:21: warning: 'const char* cipher_str(int)' defined but not used [-Wunused-function] static const char * cipher_str(int cipher) ^~~~~~~~~~ [1003/1135] Building CXX object esp-idf/arduino/CMakeFiles/__idf_arduino.dir/libraries/WiFi/src/WiFiGeneric.cpp.obj /Users/sr/projects/gcp-iot/components/arduino/libraries/WiFi/src/WiFiGeneric.cpp:187:21: warning: 'const char* auth_mode_str(int)' defined but not used [-Wunused-function] static const char * auth_mode_str(int authmode) ^~~~~~~~~~~~~ [1013/1135] Building CXX object esp-idf/arduino/CMakeFiles/__idf_arduino.dir/libraries/Wire/src/Wire.cpp.obj /Users/sr/projects/gcp-iot/components/arduino/libraries/Wire/src/Wire.cpp: In member function 'uint8_t TwoWire::requestFrom(uint16_t, uint8_t, bool)': /Users/sriraj/projects/gcp-iot/components/arduino/libraries/Wire/src/Wire.cpp:363:15: warning: variable 'err' set but not used [-Wunused-but-set-variable] esp_err_t err = ESP_OK; I have tried setting -Wno-unused-function flag in various places but have failed to disable these warnings. Can someone please advise the right place to set this build option so I don't see these warnings. I am using VSCode on MacOS. Thank you in advance.
Navigate to your ESP-IDF directory and look for build.cmake file under esp-idf/tools/cmake directory. In the build.cmake file - look for the section called function(__build_set_default_build_specifications) - this contains all the default compiler options that are executed at build time. Include -Wno-unused-function here, save and recompile your project! But be aware that this will disable this warning globally and affect other projects as well.
69,693,808
69,694,108
Access vector of vector pointers
I wanted to create a matrix with vectors. In the below code, I created a vector with each entry containing a pointer to another vector(myvector) that acts as columns. I push random values to the myvector (i.e. columns). But when I try to access the values of arrays, it pops an compile error saying "error: no match for 'operator*' (operand type is 'std::vector<int>') at the cout statement. I wonder how do I access the values. I'm pretty sure this is a naive question. #include <iostream> #include <vector> using namespace std; int main () { std::vector<vector<int>*> main; for(int j=0; j<3; j++){ vector<int> *myvector = new vector<int>; main.push_back(myvector); } main[0]->push_back(1); main[0]->push_back(4); main[1]->push_back(6); main[1]->push_back(7); main[1]->push_back(8); main[2]->push_back(3); for(int j=0; j<3; j++){ for(uint32_t i=0; i<main[j]->size(); i++) std::cout<<main[j][i]<<" "; cout<<"\n"; } return 0; }
This example shows both the syntax you where looking for, and also an example of how you should use std::vector without new/delete. #include <iostream> #include <vector> #include <memory> // using namespace std; <== teach yourself NOT to do this. // https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice void access_pointers_in_2d_vector() { std::vector<std::vector<int>*> values; // don't call your variables main! for (int j = 0; j < 3; j++) { std::vector<int>* myvector = new std::vector<int>; values.push_back(myvector); } values[0]->push_back(1); values[0]->push_back(4); values[1]->push_back(6); values[1]->push_back(7); values[1]->push_back(8); values[2]->push_back(3); for (int j = 0; j < 3; j++) { for (uint32_t i = 0; i < values[j]->size(); i++) { //================================================================== // this is the syntax you're looking for // first dereference the pointer then use operator[] std::cout << (*values[j])[i] << " "; //================================================================== } std::cout << "\n"; } // don't forget to cleanup your memory! // if you typed new somewhere then there should // ALWAYS be a matching delete in your code too! for (int j = 0; j < 3; j++) { delete values[j]; // <<==== !!!!!!! } } // for dynamic memory managment new/delete aren't recommended anymore. // use std::unique_pointer (or if your design really requires it std::shared_ptr) void using_unique_pointer() { // If you really need pointers, use std::unique_ptr // it will prevent you from introducing memory leaks const std::uint32_t size = 3ul; std::vector<std::unique_ptr<std::vector<int>>> values(size); for (auto& p : values) { p = std::make_unique<std::vector<int>>(); } values[0]->push_back(1); values[0]->push_back(4); values[1]->push_back(6); values[1]->push_back(7); values[1]->push_back(8); values[2]->push_back(3); // output loop is same as for normal pointers. // no need to call delete, std::unique_ptr will do that for you } void without_pointers() { // However your whole code in idiomatic c++ should look like this. // https://en.cppreference.com/w/cpp/container/vector/vector constructor (10) // https://en.cppreference.com/w/cpp/language/range-for these loops avoid bugs related to // letting indices go out of bounds. std::cout << "\nusing (nested) initializer list and range based for loops : \n"; std::vector<std::vector<int>> rows{ {1,4}, {6,7,8}, {3} }; for (const auto& row : rows) { for (const auto& value : row) { std::cout << value << " "; } std::cout << "\n"; } } int main() { access_pointers_in_2d_vector(); using_unique_pointer(); without_pointers(); return 0; }
69,693,897
69,694,086
Using std::apply on class method
I'm trying to get the following to compile (g++-11.2, C++20), but I get: error: no matching function for call to '__invoke(std::_Mem_fn<void (Foo::*)(int, double)>, std::__tuple_element_t<0, std::tuple<int, double> >, std::__tuple_element_t<1, std::tuple<int, double> >)' 1843 | return std::__invoke(std::forward<_Fn>(__f), Code: #include <iostream> #include <tuple> struct Foo { void bar(const int x, const double y) { std::cout << x << " " << y << std::endl; } void bar_apply() { // fails std::apply(std::mem_fn(&Foo::bar), std::tuple<int, double>(1, 5.0)); } }; int main() { Foo foo; foo.bar_apply(); };
I recommend using C++20 bind_front, which is more lightweight and intuitive. Just like its name, member functions require a specific class object to invoke, so you need to bind this pointer to Foo::bar. void bar_apply() { std::apply(std::bind_front(&Foo::bar, this), std::tuple<int, double>(1, 5.0)); } Demo.
69,694,109
69,694,187
Why g++/clang++ throw error "does not give a valid preprocessing token"
Below is minimal code to reproduce problem. #include <chrono> #include <functional> #include <iostream> using namespace std; class Test { public: Test() {} void test1() { cout << __func__ << endl; } void test2() { cout << __func__ << endl; } void testPrepare() { cout << __func__ << endl; } private: }; #define DO_TEST(obj, testName) \ { \ obj.testPrepare(); \ std::function<void(void)> test = std::bind(&Test::##testName, obj); \ /*test(); \ Some other code which use test()*/ \ } int main(int argc, char const *argv[]) { Test obj; DO_TEST(obj, test1); DO_TEST(obj, test2); /* code */ return 0; } This works well and doing what is expected with cl.exe, but on g++/clang++ throwing a compile time error, as seen below: g++ d.cpp d.cpp:19:53: error: pasting "::" and "test1" does not give a valid preprocessing token 19 | std::function<void(void)> test = std::bind(&Test::##testName, obj); \ | ^~ d.cpp:26:3: note: in expansion of macro ‘DO_TEST’ 26 | DO_TEST(obj, test1); | ^~~~~~~ d.cpp:19:53: error: pasting "::" and "test2" does not give a valid preprocessing token 19 | std::function<void(void)> test = std::bind(&Test::##testName, obj); \ | ^~ d.cpp:27:3: note: in expansion of macro ‘DO_TEST’ 27 | DO_TEST(obj, test2); | ^~~~~~~ Compiler details: cl.exe Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30133 for x86 clang++ version 10.0.0-4ubuntu1, Target: x86_64-pc-linux-gnu g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 Note: I do know that changing &Test::##testName to &Test:: testName would solve the issue. But I want to understand whether it's bug of cl.exe to allow the code above or if g++/clang++ throwing an error is a bug.
According to the C spec: each instance of a ## preprocessing token in the replacement list is deleted and the preceding preprocessing token is concatenated with the following preprocessing token. ... If the result is not a valid preprocessing token, the behavior is undefined. So using ## in such a way as to not create a single token is undefined -- the compiler can give a diagnostic about it, but is not required to, and it can instead (as an extension) do something else.
69,694,151
69,694,220
How to find the power set of a given set without using left shift bit?
I'm trying to figure out how to implement an algorithm to find a power set given a set, but I'm having some trouble. The sets are actually vectors so for example I am given Set<char> set1{ 'a','b','c' }; I would do PowerSet(set1); and I would get all the sets but if I do Set<char> set2{ 'a','b','c', 'd' }; I would do PowerSet(set2) and I would miss a few of those sets. Set<Set<char>> PowerSet(const Set<char>& set1) { Set<Set<char>> result; Set<char> temp; result.insertElement({}); int card = set1.cardinality(); int powSize = pow(2, card); for (int i = 0; i < powSize; ++i) { for (int j = 0; j < card; ++j) { if (i % static_cast<int> ((pow(2, j)) + 1)) { temp.insertElement(set1[j]); result.insertElement(temp); } } temp.clear(); } return result; } For reference: cardinality() is a function in my .h where it returns the size of the set. insertElement() inserts element into the set while duplicates are ignored. Also the reason why I did temp.insertElement(s[j]) then result.insertElement(temp) is because result is a set of a set and so I needed to create a temporary set to insert the elements into then insert it into result. clear() is a function that empties the set. I also have removeElem() which removes that element specified if it exists, otherwise it'll ignore it.
Your if test is nonsense -- it should be something like if ((i / static_cast<int>(pow(2,j))) % 2) you also need to move the insertion of temp into result after the inner loop (just before the temp.clear()). With those changes, this should work as long as pow(2, card) does not overflow an int -- that is up to about card == 30 on most machines.
69,694,519
69,699,993
How to sort map using comparator with reflection in original map?
How to sort the multimap using comparator. It should be reflected in the multimap container #include <bits/stdc++.h> using namespace std; // Comparator function to sort pairs // according to second value bool cmp(pair<string, int>& a, pair<string, int>& b) { return a.second < b.second; } // Function to sort the map according // to value in a (key-value) pairs void sort(multimap<string, int>& M) { // Declare vector of pairs vector<pair<string, int> > A; // Copy key-value pair from Map // to vector of pairs for (auto& it : M) { A.push_back(it); } // Sort using comparator function sort(A.begin(), A.end(), cmp); // Print the sorted value for (auto& it : A) { cout << it.first << ' ' << it.second << endl; } } // Driver Code int main() { // Declare Map multimap<string, int> M; // Given Map M = { { "GfG", 3 }, { "To", 2 }, { "Welcome", 1 } }; // Function Call sort(M); cout<<"\n"; for(auto i:M) { cout<<i.first<<" "<<i.second<<endl; } return 0; } This is code I got from Geekforgeeks! I totally understood the concept but I need to know how to sort the map itself if the map is multimap.? OUTPUT Welcome 1 To 2 GfG 3 GfG 3 To 2 Welcome 1
Basically the answer has been given in the comments already. I will summarize again and show an alternative. The background is that we often want to use the properties of an associative container, but later sort it by its value and not by the key. The unsorted associative containers, like std::unsorted_set, std::unordered_map , std::unordered_multiset and std::unordered_multimap cannot be ordered, as their names say. They are using a hash algorithm to store and retrieve their values. Please read also in the CPP Reference about STL container. And, if we look at the sorted associative container, we see that the std::set and the std::multiset do not work with key value pairs and the other two, the std::map and std::multimap have a key and value but are always sorted by their key. But as said, we often want to have the advantages of an Associative container with a key - value pair and later some sorted-by-the-value data. This can only be acieved by using 2 container having the needed property. In your above example the data is copied into a std::vector and then sorted. This mechanism can be used always, with any sortable container, by adding a std::pair of key and value to a container. So: using Pair = std::pair<std::string, int>; using Conatiner = std::vector<Pair>; An often needed use case is counting something. For example, counting the letters in a string. This can be really easily achieved with a std::map or std::unordered_map and the sorted by the value using a 2nd container. Please see some example code below: #include <iostream> #include <string> #include <utility> #include <set> #include <unordered_map> #include <type_traits> // ------------------------------------------------------------ // Create aliases. Save typing work and make code more readable using Pair = std::pair<char, unsigned int>; // Standard approach for counter using Counter = std::unordered_map<Pair::first_type, Pair::second_type>; // Sorted values will be stored in a multiset, because their may be double ranks struct Comp { bool operator ()(const Pair& p1, const Pair& p2) const { return (p1.second == p2.second) ? p1.first<p2.first : p1.second>p2.second; } }; using Rank = std::multiset<Pair, Comp>; // ------------------------------------------------------------ // Function to get the rank of letters in a string Rank getRank(const std::string& str) { Counter counter; for (const char c : str) counter[c]++; return { counter.begin(), counter.end() }; } // Test / Driver Code int main() { if (std::string userString{}; std::getline(std::cin, userString)) for (const auto& [letter, count] : getRank(userString)) std::cout << (int)letter << ' ' << count << ' '; } So, we use the property of the std::unordred map as a fast associative container, not sorted by the key, in combination with a std::multiset which will act as a "sorter". Or, you can take a std::multiset from the beginning. Example: #include <iostream> #include <string> #include <utility> #include <set> // ------------------------------------------------------------ // Create aliases. Save typing work and make code more readable using Pair = std::pair <std::string, int> ; // Sorted values will be stored in a multiset struct Comp { bool operator ()(const Pair& p1, const Pair& p2) const { return (p1.second == p2.second) ? p1.first<p2.first : p1.second<p2.second; } }; using Sorted = std::multiset<Pair, Comp>; // ------------------------------------------------------------ // Driver Code int main() { Sorted data { { "GfG", 3 }, { "To", 2 }, { "Welcome", 1 } }; for (const auto& [key, value] : data) std::cout << key << '\t' << value << '\n'; } Depends of course all on what you want to achieve . . .
69,694,630
69,694,775
Why do I get the error "use of deleted function 'class : : class()"
#include <iostream> using namespace std; class student { protected: string name; int roll; int age; public: student(string n, int r, int a) { name = n; roll = r; age = a; } }; class test : public student { protected: int sub[5]; public: void marks() { cout << "Enter marks in 5 subjects: " << endl; cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4]; } void display() { cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl; cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl; } }; class sports { protected: int sportmarks; public: sports(int sm) { sportmarks = sm; } }; class result : public test, public sports { int tot; float perc; public: void calc() { tot = sportmarks; for(int i = 0; i < 5; i++) tot = tot + sub[i]; perc = (tot / 600.0) * 100; cout << "Total: " << tot << "\nPercentage: " << perc << endl; } }; int main() { student ob1("Name", 781, 19); sports ob2(78); result ob; ob.marks(); ob.display(); ob.calc(); } I've been asked to use parameterized constructors to do this problem and notice I get these errors when I use constructors. Sorry if this post is inconvenient to read. In what way can I run this code while creating objects from parameterized constructors? use of deleted function 'result::result()' use of deleted function 'test::test()'. no matching function for call to 'student::student()' no matching function for call to 'sports::sports()'
student and sports have user-defined constructors, so the compiler does not generate default constructors for them. test and result have no user-defined constructors, so the compiler will generate default constructors for them. However, since student and sports have no default constructors, the generated default constructors are marked delete'd as they are not usable. That is why you get errors. To make your main() compile as-is, you need to define your own default constructors for test and result which pass explicit parameter values to their base classes, eg: #include <iostream> using namespace std; class student { protected: string name; int roll; int age; public: student(string n, int r, int a) { name = n; roll = r; age = a; } }; class test : public student { protected: int sub[5]; public: test() : student("", 0, 0) {} void marks() { cout << "Enter marks in 5 subjects: " << endl; cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4]; } void display() { cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl; cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl; } }; class sports { protected: int sportmarks; public: sports(int sm) { sportmarks = sm; } }; class result : public test, public sports { int tot; float perc; public: result() : test(), sports(0) {} void calc() { tot = sportmarks; for(int i = 0; i < 5; i++) tot = tot + sub[i]; perc = (tot / 600.0) * 100; cout << "Total: " << tot << "\nPercentage: " << perc << endl; } }; int main() { student ob1("Name", 781, 19); sports ob2(78); result ob; ob.marks(); ob.display(); ob.calc(); } Online Demo However, this is not very useful, so I would suggest tweaking result's constructor to take the student and sports objects you have already created beforehand, and pass them to the base class copy constructors, which the compiler will generate for you, eg: #include <iostream> using namespace std; class student { protected: string name; int roll; int age; public: student(string n, int r, int a) { name = n; roll = r; age = a; } }; class test : public student { protected: int sub[5]; public: test(const student &s) : student(s) {} void marks() { cout << "Enter marks in 5 subjects: " << endl; cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4]; } void display() { cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl; cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl; } }; class sports { protected: int sportmarks; public: sports(int sm) { sportmarks = sm; } }; class result : public test, public sports { int tot; float perc; public: result(const student &s, const sports &sp) : test(s), sports(sp) {} void calc() { tot = sportmarks; for(int i = 0; i < 5; i++) tot = tot + sub[i]; perc = (tot / 600.0) * 100; cout << "Total: " << tot << "\nPercentage: " << perc << endl; } }; int main() { student ob1("Name", 781, 19); sports ob2(78); result ob(ob1, ob2); ob.marks(); ob.display(); ob.calc(); } Online Demo
69,694,776
69,694,973
What does this strange number mean in the output? Is this some memory Location?
The node Class is as follow: class node { public: int data; //the datum node *next; //a pointer pointing to node data type }; The PrintList Function is as follow: void PrintList(node *n) { while (n != NULL) { cout << n->data << endl; n = n->next; } } If I try running it I get all three values (1,2,3) but I get an additional number as well which I'm unable to figure out what it represents, Can someone throw light on the same? int main() { node first, second, third; node *head = &first; node *tail = &third; first.data = 1; first.next = &second; second.data = 2; second.next = &third; third.data = 3; PrintList(head); } I Know it can be fixed with third.next = NULL; But I am just curious what does this number represents in output, If I omit the above line 1 2 3 1963060099
As described in the comment by prapin, third.next is not initialized. C++ has a zero-overhead rule. Automatically initializing a variable would violate this rule as the value might be initialized (a second time) later on or never even be used. The value of third.next is just the data that happened to live in the same memory location as third.next does now. For this reason, it's recommended to always initialize your variables yourself.
69,694,932
69,694,968
Does not flushing a buffer lead to files having incorrect output
In the code below, if I don't flush the buffer using fflush(STDOUT), could it be that FILE2 ends up getting both "Hello world 1" and "Hello world 2" since the buffer might be flushed at the end of the program and it might be holding both those statements by the end? #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { int FILE1 = dup(STDOUT_FILENO); int FILE2 = open("HelloWorld.txt",O_WRONLY|O_CREAT,0666); dup2(FILE1,STDOUT_FILENO); printf("Hello World 1\n"); //THE LINE OF CONCERN fflush(stdout); dup2(FILE2,STDOUT_FILENO); printf("Hello World 2\n"); close(FILE2); close(FILE1); return 0; }
The problem is that you work on different levels here. The stdio-system and stdout will have its own buffer which will not be closed or flushed when you do the second dup2 call. The contents of the stdout buffer will still remain and be written when stdout is closed at process termination. So the fflush call is needed to actually flush the stdout buffer to the "file".
69,694,978
69,695,096
String Rev function, strange behavior for out of bounds exception (c++)
I played with the string function,i wrote the following one, obviously I set the first character in the ret string to be written in a place that is out of bounds, but instead of an exception, I get a string that has one extra place . std::string StringManipulations::rev(std::string s) { std::string ret(s.size(), ' '); for (int i = 0; i < s.size(); i++) { std::string ch; ch.push_back(s[i]); int place = s.size() -i; ret.replace(place,1,ch); } return ret; } I write by mistake in a position that corresponds to a place that is one larger than the original string size that I assign at the beginning of the function. Why don't we get an error ? s = StringManipulations::rev("abcde"); std::cout << s.size(); std::cout << s; output is : 6 _edcba any help ? solved: adding ch as a String adds a null terminator automatically, and by doing so we can get a new string with size+1.
C++ has a zero-overhead rule. This means that no overhead, (like checking if an index is in-bounds) should be done unintentionally. You don't get an exception because c++ simply doesn't verify if the index is valid. For the extra character, this might have something to do with (regular) c strings. In c, strings are arrays of type char (char*) without a defined size. The end of a string is denoted with a null terminator. C++ strings are backwards compatible, meaning that they have a null terminator too. It's possible that you replaced the terminator with an other character but the next byte was also a zero meaning that you added one more char.
69,695,565
69,707,892
Is there a way to map a 2D array's x and y to a screen's resolution?
I have this SDL & C++ code to render the 24 x 24 array to the screen. int main(int argc, char *argv[]) { // Init SDL_Window *mainwindow = SDL_CreateWindow("window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_W, SCREEN_H, SDL_WINDOW_SHOWN); SDL_Renderer *mainrenderer = SDL_CreateRenderer(mainwindow, -1, SDL_RENDERER_PRESENTVSYNC); SDL_Texture *maintexture = SDL_CreateTexture(mainrenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, SCREEN_W, SCREEN_H); Uint32 *buffer = new Uint32[SCREEN_W * SCREEN_H]; memset(buffer, 0, SCREEN_H * SCREEN_W * sizeof(Uint32)); //Loop while(true){ if(quit_event() == false){break;} for(int y = 0; y < MAP_H; y++){ for(int x = 0; x < MAP_W; x++){ if(worldMap[y][x] == 0){ Uint32 colour = 0; colour += 0xFF; colour <<= 8; colour += 0xFF; colour <<= 8; colour += 0xFF; colour <<= 8; colour += 0; buffer[(y * SCREEN_W) + x] = colour; } } } SDL_UpdateTexture(maintexture, NULL, buffer, SCREEN_W * sizeof(Uint32)); SDL_RenderClear(mainrenderer); SDL_RenderCopy(mainrenderer, maintexture, NULL, NULL); SDL_RenderPresent(mainrenderer); } delete[] buffer; SDL_DestroyRenderer(mainrenderer); SDL_DestroyTexture(maintexture); SDL_DestroyWindow(mainwindow); SDL_Quit(); } When running the program this is displayed. How could I map the X and Y values of worldMap to one's of those on a screen without making the worldMap array the size of the screen? EDIT: I have changed the program and it sort of works now. #include <iostream> #include "SDL.h" #define MAP_W 8 #define MAP_H 8 #define MAP_A 64 #define GRID_S 64 #define SCREEN_W 640 #define SCREEN_H 480 using namespace std; int worldMap[]= { 1,1,1,1,1,1,1,1, 1,0,1,0,0,0,0,1, 1,0,1,0,0,0,0,1, 1,0,1,0,0,0,0,1, 1,0,0,0,0,0,0,1, 1,0,0,0,0,1,0,1, 1,0,0,0,0,0,0,1, 1,1,1,1,1,1,1,1, }; bool quit_event(){ SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { return false; } } return true; } int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_EVERYTHING); // Init SDL_Window *mainwindow = SDL_CreateWindow("window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_W, SCREEN_H, SDL_WINDOW_RESIZABLE); SDL_Renderer *mainrenderer = SDL_CreateRenderer(mainwindow, -1, SDL_RENDERER_PRESENTVSYNC); //Loop while(true){ SDL_SetRenderDrawColor(mainrenderer,0,0,255,255); SDL_RenderClear(mainrenderer); SDL_SetRenderDrawColor(mainrenderer,0,255,255,255); if(quit_event() == false){break;} SDL_Rect rect; rect.w = GRID_S; rect.h = GRID_S; for(int y = 0; y < MAP_H; y++){ rect.y = 0 + (y * GRID_S); for(int x = 0; x < MAP_W; x++){ rect.x = 0 + (x * GRID_S); if(worldMap[y*MAP_W+x] == 1){ SDL_RenderDrawRect(mainrenderer,&rect); SDL_RenderFillRect(mainrenderer,&rect); } } } SDL_RenderPresent(mainrenderer); } SDL_DestroyRenderer(mainrenderer); SDL_DestroyWindow(mainwindow); SDL_Quit(); } Now I'm just confused on how the rectangles are rendered wonky...
This seems to be a recent open issue. https://github.com/libsdl-org/SDL/issues/4001 In your case the issue is apparently with the top side, instead of the bottom one, but it's the same issue overall. Try leaving out SDL_RenderDrawRect and use just SDL_RenderFillRect.
69,695,664
69,708,742
Strange behavior of CUDA kernel
I am trying to make a simple Cuda application that creates integral image of given matrix. One of the steps I need to do, is to create integral image of every row. In order to do this, I want to assign 1 thread to each row. Function that is supposed to do this: __global__ void IntegrateRows(const uchar* img, uchar* res) { int x = blockIdx.x * blockDim.x + threadIdx.x; int y = blockIdx.y * blockDim.y + threadIdx.y; if (x >= Width || y >= Height) return; int sum = 0; int row = y * Width; for (int i = 0; i < Width - x; ++i) { res[row + i + x] = sum + img[row + i + x]; sum += img[row + i + x]; } } I use a matrix of size 3840x2160 filled with ones (cv::Mat::ones(Size(Width, Height), CV_8UC1)) for tests. When I try to print out content of the result, it always returns sequence of numbers from 1 to 255: The execution configurations is: dim3 threadsPerBlock(1, 256); dim3 numBlocks(1, 16); IntegrateRows<<<numBlocks, threadsPerBlock >>>(img, res); My GPU is Nvidia RTX 3090.
tl;dr: Make your output matrix have larger elements If you integrate/prefix-sum the sequence 1, 1, 1, 1, ... You get: 0, 1, 2, 3, ... and this sequence will wrap around to 0 when you reach the maximum value of your element type. In your case, it's a uchar, i.e. unsigned char. And its maximum value is 255. Add another 1 to it, and you get 0. So: 0, 1, 2, 3, ... 253, 254, 255, 0, 1, ... and so on. If you change the output matrix element type to unsigned short (or maybe simply unsigned int) - you won't get the wrap-around behavior. Of course, if you add up 255's instead of 1's, and/or your matrix is larger, then again the type's represented range might not be large enough.
69,695,743
69,696,012
How to add 0x padding to a uintptr_t in a variable?
So I'm trying to figure out how can I add 0x padding to a uintptr_t. The current value of it is: 400000. However I would like it to be 0x400000. So currently to achieve this I am adding the 0x padding when I'm printing this out. However how would I go about this so I can store the padded value of uintprt_t? uintptr_t modBase = GetModuleBaseAddress(pID, "ac_client.exe"); cout << "0x" << hex << modBase <<endl; //Output is 0x400000 The reason for trying to achieve this is that later I would like to find a dynamic base address as shown here: uintptr_t dynamicBaseAddress = modBase + 0x10f4f4; cout << "DynamicBaseAddress is: " << dynamicBaseAddress << endl; // Again var is missing 0x And again the result is: 50f4f4 without the padding.
The type of the expression printed in both cases is uintptr_t, so in both cases output stream behaves the same way, i.e. not add the prefix. As an alternative to @RetiredNinja's suggestion in the comments (use std::showbase), you could create a wrapper type with a custom operator<< which would allow you to implement the way the information is printed regardless of the current state of the stream (i.e. changing back to decimal in between wouldn't change, how the value is printed). This does require you to implement operators for operations you want to be available for this type though: class UintptrWrapper { public: UintptrWrapper(uintptr_t value) : m_value(value) { } // + operation should work, so we need to implement it friend UintptrWrapper operator+(UintptrWrapper const& summand1, UintptrWrapper const& summand2) { return { summand1.m_value + summand2.m_value }; } // custom printing of info friend std::ostream& operator<<(std::ostream& s, UintptrWrapper const& value) { auto oldFlags = s.flags(); s << "0x" << std::hex << value.m_value; s.flags(oldFlags); return s; } private: uintptr_t m_value; }; UintptrWrapper modBase = 0x400000; std::cout << modBase << '\n'; auto dynamicBaseAddress = modBase + 0x10f4f4; // result is another UintptrWrapper with the same behaviour when writing to the stream as above std::cout << "DynamicBaseAddress is: " << dynamicBaseAddress << '\n'; Output: 0x400000 DynamicBaseAddress is: 0x50f4f4
69,695,842
69,696,002
how to add ZERO on beginning of binary number
void to_binary(int x) { while (x) { a4 = x % 2; x /= 2; new_b += a4 * pow(10, g);//g=0 g++; } } I wrote the function of converting a number to a binary number system, but there is one but if the number has leading zero, for example, 0011, then I see only 11 in the console. Can I fix this problem? I thought through the vector and bitset but they don`t work for me also.
You did not elaborate what was wrong with std::bitset. For me it seem to do what you want: #include <iostream> #include <bitset> int main() { unsigned long long x = 3; // 8 digits std::cout << "x = " << std::bitset<8>(x) << std::endl; // 4 digits std::cout << "x = " << std::bitset<4>(x) << std::endl; } Output: x = 00000011 x = 0011
69,696,170
69,837,310
std::variant with const arguments in C++
There is a nice unanswered question about having union with const members: Can you write a copy constructor for a union with const members? One of suggestions there is to use std::variant instead. Indeed, const types must be supported P0086 - Variant design review. The relevant paragraph says: variant<int, const int> A variant can handle const types: they can only be set through variant construction and emplace(). So I assume variant copy construction must support them as well. But an attempt to use this option: #include <string> #include <variant> using S = std::variant<const int, const std::string>; int main() { S s(1); S u = s; S v("abc"); S w = v; } fails in GCC with a very long error (quote only its beginning here): n file included from <source>:2: /opt/compiler-explorer/gcc-trunk-20211024/include/c++/12.0.0/variant: In instantiation of 'constexpr std::__detail::__variant::_Variadic_union<_First, _Rest ...>::_Variadic_union(std::in_place_index_t<_Np>, _Args&& ...) [with long unsigned int _Np = 1; _Args = {const int&}; _First = const std::__cxx11::basic_string<char>; _Rest = {}]': /opt/compiler-explorer/gcc-trunk-20211024/include/c++/12.0.0/variant:409:4: required from 'constexpr std::__detail::__variant::_Variadic_union<_First, _Rest ...>::_Variadic_union(std::in_place_index_t<_Np>, _Args&& ...) [with long unsigned int _Np = 2; _Args = {const int&}; _First = const int; _Rest = {const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >}]' /opt/compiler-explorer/gcc-trunk-20211024/include/c++/12.0.0/bits/stl_construct.h:119:7: required from 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = std::__detail::__variant::_Variadic_union<const int, const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >; _Args = {const std::in_place_index_t<2>&, const int&}]' Demo: https://gcc.godbolt.org/z/ocajj3aao Is there something wrong with my code, or GCC must accept it?
As noted in the comment above, the code only started to be rejected by GCC trunk very recently (and is accepted by all released versions of GCC), after I implemented P2231R1. As I said in the bug report, before P2231R1 the libstdc++ std::variant was playing a bit fast and loose with constructing the active member of the union. After the P2231 changes we need to construct the correct union member, or it won't be valid in constexpr functions. That required some refactoring to be able to use the index of the member when constructing it. It's fixed now, thanks for noticing the bug.
69,696,245
69,696,378
Why does std::apply fail with function template, but not with a lambda expression with explicit template parameter list?
In looking at std::apply references from cpprefrence we can see that function templates cannot be passed as callable object of std::apply. Let's consider the following function template: template<typename T> T add_generic(T first, T second) { return first + second; } So as the function template can't be deduced in std::apply call, we can't use the follwing code: std::apply(add_generic, std::make_pair(2.0f, 3.0f)); // Error: can't deduce the function type Please note that this is not the same question as this question. In that answer, the author writes a lambda expression without explicit template parameters. std::cout << std::apply( [](auto first, auto second) { return add_generic(first, second); }, std::make_tuple(2.0f,3.0f)) << '\n'; but as you know in c++20 you can have lambda expressions with explicit template parameter list. So I tried this feature to the case and surprisingly the compiler did not raise any errors. std::apply([]<typename T>(T first,T second){ return first+second; },std::make_pair(2.0,3.0)); Why will the compiler be able to deduce type in the last case? Is there any difference between the two?
A function template is not a function, just like a cookie cutter is not a cookie. C++ templates create new functions for every set of template arguments. And this is precisely why add_generic is not a viable argument. It's not a function, it cannot be passed around as a value. To obtain the function, the compiler needs to deduce the template arguments. But it can only do that inside apply after the callable has been passed. Chicken and egg right there. Why does a lambda work? Because it's not a plain function either. It produces a hidden object type struct __lambda_at_line_N { template<typename T> auto operator()(T first, T second) { /* ... */ } }; And passes that std::apply(__lambda_at_line_N{},std::make_pair(2.0,3.0)); This is an actual object, a value. Its type does not depend on the template argument deduction that needs to happen inside std::apply to call operator(). That's why it works.
69,696,368
69,697,073
How to solve a while loop that suddenly terminates itself?
I have code to look for permutations which takes input from the user until the user is satisfied with the amount of input added. However, when receiving more than 4x input, the code suddenly stuck/terminated itself. I've tried changing the array type to dynamic memory, but the result continues to be the same. Strangely when I test this code using http://cpp.sh/, it runs normally. I think the problem is with my compiler (I used VS code and MinGW to compile and run it.) What do you think is wrong? My code is below: #include <iostream> #include <string> using namespace std; int main() { int KombAngka; bool Lanjut = true; int x = 0; int *Angka = new int(x); string YaTidak; while(Lanjut) { cout << "Number-" << x + 1 << ": "; cin >> Angka[x]; LoopYaTidak: cout << "Are the numbers enough?(y/n)?: "; cin >> YaTidak; if (YaTidak == "y") { Lanjut = false; } else if (YaTidak == "n") { Lanjut = true; } else { cout << "Enter the correct answer!(y/n)" << endl; goto LoopYaTidak; } x++; } cout << "All numbers: ("; for (int z = 0; z <= x - 2; z++) { cout << Angka[z] << ", "; } cout << Angka[x - 1] << ")" << endl; cout << "The number of combinations of numbers used: "; cin >> KombAngka; int JumlahAngka = x; const int StopLoop = JumlahAngka - KombAngka; for (int i = JumlahAngka - 1; i > StopLoop; i--) { JumlahAngka = JumlahAngka * i; } cout << "The number of queue numbers consisting of " << KombAngka << " different numbers are " << JumlahAngka << endl; system("pause"); return 0; }
This line int *Angka = new int(x); creates an integer on the heap with a value held by x which here it is 0. You are accessing memory which you should not, and as mentioned by @fredrik it may cause a buffer overflow. If you want to create an array on the heap you should do int *Angka = new int[x]; This creates an array (on heap) of size x. But since you are using c++ it's better to use vectors, you can simply create a vector with std::vector<int> Angka; Vector will take care of memory allocation and all other stuff that you would have to handle if you were to create an array with new.
69,696,504
69,790,679
What's actually happens when we try to extract line in file after which `eof` character is present with istream::getline() and std::getline()
roha.txt I really love to spend time with you. Let's go for coffee someday. Enjoy whole day and cherish the memories. Code-1 #include <iostream> #include <fstream> int main() { char str[100]; std::ifstream fin; fin.open("roha.txt", std::ios::in); for(int i=0; i<=3; i++) { std::cout<<bool(fin.getline(str,100) )<<" "<<str<<fin.fail()<<"\n"; } } Output 1 I really love to spend time with you.0 1 Let's go for coffee someday.0 1 Enjoy whole day and cherish the memories.0 0 1 Code-2 #include <iostream> #include <fstream> #include <string> using std::string; int main() { string str; std::ifstream fin; fin.open("roha.txt", std::ios::in); for(int i=0; i<=3; i++) { std::cout<<bool(std::getline(fin,str) )<<" "<<str<<fin.fail()<<"\n"; } } Output 1 I really love to spend time with you.0 1 Let's go for coffee someday.0 1 Enjoy whole day and cherish the memories.0 0 Enjoy whole day and cherish the memories.1 I know C-style char array, istream::getline and string, std::getline are different. But I want to know what actually happens. I am guessing that for string, std::getline, it extracts string for 1st, 2nd and when it tries to extract the 3rd time it sees eof so it extracts just before eof. The next time we try to extract it, just encounters eof so it didn't extract anything and set fail-bit. string str didn't get modified, so when we try to print it, only the string last extracted gets printed. I don't know if what I’m thinking is right... Also I can’t make any such case regarding istream::getline(), C-style char array.
To quote the standard, section 21.3.3.4 inserters and extractors [string.io]: Clause 6: […] After constructing a sentry object, if the sentry converts to true, calls str.erase() and then extracts characters from is and appends them to str […] until any of the following occurs: end-of-file occurs on the input sequence (in which case, the getline function calls is.setstate(ios_base::eofbit)). […] Section 29.7.4.1.3 Class basic_istream::sentry: explicit sentry(basic_istream<charT, traits>& is, bool noskipws = false); Effects: If is.good() is false, calls is.setstate(failbit) […] If, after any preparation is completed, is.good() is true, ok_ != false otherwise, ok_ == false. During preparation, the constructor may call setstate(failbit) […] explicit operator bool() const; Returns: ok_ So, what is happening with the string version: You extract the last string. This sets eofbit, but not failbit You getline again getline constructs a sentry The sentry checks is.good(). This is false because eofbit is set The sentry sets the failbit and sets its member ok_ to false The getline function checks if the sentry is true (operator bool). This is false The getline function returns before clearing your old string Section 29.7.4.3 Unformatted input functions Clause 21 (this is about the C-string version): In any case, if n is greater than zero, it then stores a null character (using charT()) into the next successive location of the array The rest of the wording is similar to the string version. In other words, the C-string version of getline always stores a '\0' character, even if it failed. The std::string version does not, presumably because it doesn't introduce the same memory safety issues that you have with the C version if you forget to check the failbit.
69,696,793
69,696,840
C++ no instance of constructor matches the argument list e0289
So the code should work, but it is not. How can I fix it? enter image description here #include <iostream> class Button{ private: unsigned width; unsigned height; public: Button(): width(0), height(0){}; Button(unsigned _width, unsigned _height): width(_width), height(_height){}; unsigned getWidth(){ return width; }; unsigned getHeight(){ return height; }; void setWidth(unsigned _width){ width = _width; }; void setHeight(unsigned _height){ height = _height; }; }; class Window{ protected: Button button; int x; int y; public: Window(){ x = y = 0; } Window(int _x, int _y, Button _button): x(_x), y(_y), button(_button){}; ~Window(){ x = 0; y = 0; } }; class Menu: public Window{ private: char *title; public: Menu() = default; Menu(char* _title, int _x, int _y, Button _button): title(_title), Window(_x, _y, _button){ std::cout << "Menu has been created." << std::endl; }; ~Menu(){ title = NULL; std::cout << "Menu has been deleted." << std::endl; } friend std::ostream& operator<<(std::ostream& os, Menu& menu){ os << "Button \"" << menu.title << "\" on (" << menu.x << "," << menu.y << ") with size " << menu.button.getWidth() << "x" << menu.button.getHeight() << "."; return os; } }; int main(){ Button button(10, 10); Menu menu("A main menu", 5, 5, button); std::cout << menu << std::endl; return 0; }
At least declare the data member title like const char *title; and the constructor like Menu( const char* _title, int _x, int _y, Button _button): Window(_x, _y, _button), title(_title) { std::cout << "Menu has been created." << std::endl; }; Because string literals in C++ (opposite to C) have types of constant character arrays. Though instead of the type const char * of the data member title it will be much better to use the type std::string std::string title.
69,696,908
69,697,109
How to push strings (char by char) into a vector of strings
This code is just a prototype, how I'm expecting my output.. My program should be able to insert char by char to particular index of vector; This program works fine for vector<vector<int>> #include<bits/stdc++.h> using namespace std; int main() { vector<vector<string>>v; for(auto i=0;i<5;i++) v.emplace_back(vector<string>()); v[0].emplace_back('z'); v[1].emplace_back('r'); v[0].emplace_back('x'); v[1].emplace_back('g'); for(auto i:v){ for(auto j:i) cout<<j<<" ";cout<<endl;} return 0; } My Expected output: z x r g Error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(char)’ { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
It seems you need something like the following #include <iostream> #include <string> #include <vector> int main() { std::vector<std::vector<std::string>> v( 2 ); v[0].emplace_back( 1, 'z' ); v[1].emplace_back( 1, 'r' ); v[0][0].append( 1, ' ' ); v[1][0].append( 1, ' ' ); v[0][0].append( 1, 'x' ); v[1][0].append( 1, 'g' ); for ( const auto &item : v ) { std::cout << item[0] << '\n'; } return 0; } The program output is z x r g Otherwise declare the vector like std::vector<std::vector<char>> v; For example #include <iostream> #include <string> #include <vector> int main() { std::vector<std::vector<char>> v( 2 ); v[0].emplace_back( 'z' ); v[1].emplace_back( 'r' ); v[0].emplace_back( 'x' ); v[1].emplace_back( 'g' ); for ( const auto &line : v ) { for ( const auto &item : line ) { std::cout << item << ' '; } std::cout << '\n'; } return 0; }
69,697,011
69,699,335
Constexpr Sorted Unique Container Set as Array wrapper
I want to create a constexpr container like std::array that is also sorted and all elements are unique. What I want to achieve is to check at compile time if the given data in the constructor are sorted and unique. I believe an std::set interface is more close to what I want to achieve but it is not constexpr (yet?). I plan to create a wrapper and use an std::array internally while I expose the std::set interface externally. The current implementation looks like this struct ConstexprSet { constexpr ConstexprSet(const std::array<DataType, Size>& data) : mData(data) { if constexpr (!std::is_sorted(std::cbegin(mData), std::cend(mData))) throw std::runtime_error("Data not sorted"); if constexpr (std::adjacent_find(std::cbegin(mData), std::cend(mData)) != std::cend(mData)) throw std::runtime_error("Data not unique"); } [[nodiscard]] constexpr auto GetData() const noexcept { return mData; } private: std::array<DataType, Size> mData; }; The error I get is that "this" is not a constant expression. If I change the mData with the data argument I get that data is not a constant expression. So what is a constant expression after all? If I pass the whole array as an NTTP will this work? The desired use case would be something like this constexpr ConstexprSet features{"A"sv, "B"sv, "C"sv, "D"sv, "E"sv, "F"sv}; where the template arguments will be deduced from the input arguments like it is done in the std::array. The following two examples should not compiled successfully and they should give comprehensive messages constexpr ConstexprSet features{"A"sv, "D"sv, "C"sv, "B"sv, "E"sv, "F"sv}; // Data not sorted constexpr ConstexprSet features{"A"sv, "B"sv, "B"sv, "D"sv, "E"sv, "F"sv}; // Data not unique An other failed experiment was to create a constructor with an initializer list and pass it straight to the internal array but that does not work either... Any ideas on how to overcome this problem or any other approach I can follow to achieve the desired behavior of this container would be more than welcome The current draft I used for experimentation can be found here https://godbolt.org/z/1468cEjhW
struct ConstexprSet { std::array<DataType, Size> mData; You can't do that - at the class level, DataType and Size aren't even declared identifiers. Let's declare them (T for DataType, n for Size): template<typename T, auto n> class Set { std::array<T, n> mData; // TODO What I want to achieve is to check at compile time if the given data in the constructor are sorted and unique Then you need a constructor which is consteval (must be run at compile-time), not constexpr (runtime/compile-time "polymorphic"): public: consteval Set(auto... ts): mData{std::move(ts)...} { if (n == 0) return; // can't think of a ready STL algorithm for (auto prev = mData.begin(), cur = prev + 1; cur != mData.end(); ++prev, ++cur) if (*prev >= *cur) throw std::logic_error{"not sorted / not unique"}; } }; A deduction guide for convenience: Set(auto t, auto... ts) -> Set<decltype(t), sizeof...(ts) + 1>; Tests: int main() { constexpr Set set1{"A"sv, "B"sv, "D"sv}; // ok constexpr Set set2{"A"sv, "D"sv, "B"sv}; // error constexpr Set set3{"A"sv, "D"sv, "D"sv}; // error } should give comprehensive messages source>:24:16: error: constexpr variable 'set2' must be initialized by a constant expression constexpr Set set2{"A"sv, "D"sv, "B"sv}; // error ^~~~~~~~~~~~~~~~~~~~~~~~~ <source>:17:5: note: subexpression not valid in a constant expression throw std::logic_error{"not sorted / not unique"}; source>:25:16: error: constexpr variable 'set3' must be initialized by a constant expression constexpr Set set3{"A"sv, "D"sv, "D"sv}; // error ^~~~~~~~~~~~~~~~~~~~~~~~~ <source>:17:5: note: subexpression not valid in a constant expression throw std::logic_error{"not sorted / not unique"};
69,697,289
69,697,434
Why don't people check if containers allocation failed?
When we declare a std::vector, or std::string, ..., like that for example std::string hello("Hello"); isn't it wrong? shouldn't we do std::string hello; try { hello = "Hello"; } catch (std::exception &e) { std::cout << e.what() << std::endl; return (-1); } Because if I understood how it works, when an allocation fails, it will result in an uncaught exception otherwise, so why do I often see code like this ? : std::string s("hello"); s += " world"; s += "!"; s.reserve(100); ... without any check?
Most people know how memory-intensive their app is, but what are you going to do if you can't allocate a string? You probably also at that point can't do much of anything, and you're going to have to exit. When you have actual recovery you can do, people will probably catch all exceptions at a higher level -- several method calls back, and then do what they can. Hopefully by rolling back the stack a bit, you'll release enough resources you can do whatever error handling you'd like before exiting.
69,697,403
69,697,593
Access violation when the object goes out of scope in switch case
Ok, then. I started learning C++, and my task is to create a process manager with the Win32 API. It is going to look like this: I have a TBuffer class: (Buffer will keep information about the processes) #pragma once #include <wtypes.h> #define BUFFER_SIZE 10 #define WM_UPDATELIST WM_USER enum TProcessState { psEmpty, psNew, psRunning, psTerminated, psError }; struct TProcessInfo { TProcessState State; char Name[100]; HANDLE Handle; int PID; int UserTime, KenelTime; }; class TBuffer { private: HWND Wnd; CRITICAL_SECTION cs; TProcessInfo Buf[BUFFER_SIZE]; public: TBuffer(HWND AWnd); ~TBuffer(); int Count(); int AddProcess(char *AName); void Get(int Id, TProcessInfo &Pi); void Set(int Id, const TProcessInfo Pi); const char* ProcessStateToString(TProcessState state); }; The class constructor has the following realization: TBuffer::TBuffer(HWND AWnd) { Wnd = AWnd; InitializeCriticalSection(&cs); for (int i = 0; i < BUFFER_SIZE; i++) { Buf[i].State = psEmpty; Buf[i].Handle = 0; Buf[i].Name[0] = 0; Buf[i].PID = 0; Buf[i].UserTime = 0; Buf[i].Handle = 0; } } And the destructor: TBuffer::~TBuffer() { DeleteCriticalSection(&cs); } The method using critical section: void TBuffer::Set(int Id, const TProcessInfo Pi) { EnterCriticalSection(&cs); ... LeaveCriticalSection(&cs); } In the main .cpp file, I have a global variable: TBuffer *Buffer; And in the MainWndProc function where messages are processed, in the case WM_INITDIALOG I am asked to create a TBuffer class object to initialize the critical section and so on: case WM_INITDIALOG: { TBuffer Buf(hWnd); Buffer = &Buf; ... return TRUE; } My problem is that, as I read, the class object after return TRUE is going out of scope and its destructor is called. That's why the critical section is deleted and then other class methods like Set() and Get() are not able to enter the critical section. So I'm looking for a way to leave the object in scope. I think that something is wrong in WM_INITDIALOG with object creation. By the way, when the WM_DESTROY message is processed, I free the allocated memory for the global variable: case WM_DESTROY: delete[] Buffer; PostQuitMessage(0); return TRUE;
You're correct in your understanding, case WM_INITDIALOG: { TBuffer Buf(hWnd); Buffer = &Buf; ... return TRUE; // <-- Buf is destructed here, Buffer is now a dangling pointer } To allocate something that lives longer than its enclosing scope, allocate it on the heap using new: case WM_INITDIALOG: { Buffer = new TBuffer(hWnd); ... return TRUE; } And remember to delete later.
69,697,450
69,698,045
Alternative to Pimpl
I am required to provide a solution to the following problem: A class is published as a library and made available to the world. It is designed in a way which does not use the pimpl approach. Two new data members need to be defined in this class. How can these additional data members be added to the class without breaking the ABI? The solution should be a generic approach that can be used to avoid ABI breakages for any class designed, which does not use the pimpl approach. My first solution was to create a new class which inherits from this previous class and then adding the 2 new members there. Then source code which require these 2 new data members can make use of this newly created class. However, my solution was marked incorrect. I was told that I must repurpose an existing data member for other purposes in a similar approach to pimpl. I did not understand what this really means, as I was not provided with any interfaces of this existing class. What alternatives are there to pimpl which allow changes to existing classes without breaking the ABI?
My guess would be as follows. Suppose your class contains a pointer data member, say char* x (the type is not important) that is used for thing unrelated to your planned expansion. Your professor wants you to interpret x as a pointer to another thing: struct expansion { char* newX; int newDataMember1; double newDataMember2; }; Now whenever you see x in the old code, replace it with a call to a member function getX(): private: char*& getX() { return ((expansion*)x)->newX; } You should initialize x in the constructor: x = (char*)new expansion; // or MyClass() : x((char*)new expansion) and free it in the destructor. Now you have your old x as getX(), and the new data members (write an obvious member function to access them). Of course you should never ever do anything like that in any real code, which is why I do not discuss smart pointers, exception safety, new style casts and other things that could be remotely considered advanced or good style. Add those to taste. This is not a way to write production code, but purely an exercise to satisfy your professor. What if you don't have a pointer member in your class? In this case you will have to break some actual C++ rules (in addition to principles of good software design, which went down the drain the moment you started even thinking about this "solution"). Repurpose some integral member instead (note, the C++ standard doesn't guarantee it will work at all, though with most implementations it's OK as long as the size of your member is at least the size of a pointer). Or repurpose more than one member that are adjacent to each other (use reinterpret_cast or placement new to place a pointer there). Or, if your class has a vector of something, use data managed by the vector to store a pointer, again with a cast or placement new hack. Everything goes... as long as you get your professor's approval of course, the C++ standard be damned.
69,697,490
69,698,703
Boost datetime posix_time time_input_facet fails to parse single digit day
When using time_input_facet boost datetime posix_time fails to parse single digit day of month. Unbeknownst to me at the time of initial posting, https://github.com/boostorg/date_time/issues/106 describes this issue, as pointed out in the accepted answer. #include <boost/date_time/posix_time/posix_time.hpp> #include <vector> void date_from_string(const std::string& format, const std::string& date_str, boost::posix_time::ptime& date) { auto* facet = new boost::posix_time::time_input_facet; facet->format(format.c_str()); std::stringstream ss(date_str); ss.imbue(std::locale(std::locale::classic(), facet)); ss >> date; // delete facet; > "Your program has UB. delete facet; leads to double-free." } int main() { std::cout << "Boost Version: " << BOOST_VERSION << std::endl; // 107500 // Boost Version: 107500 for (auto& i : std::vector<std::pair<std::string,std::string>>{ {"%a, %d %b %Y %H:%M:%S %ZP","Thu, 17 Oct 2021 15:00:00 GMT"}, // 2021-Oct-17 15:00:00 from str: Thu, 17 Oct 2021 15:00:00 GMT using: %a, %d %b %Y %H:%M:%S %ZP {"%a, %d %b %Y %H:%M:%S %ZP","Thu, 7 Oct 2021 15:00:00 GMT"}, // not-a-date-time from str: Thu, 7 Oct 2021 15:00:00 GMT using: %a, %d %b %Y %H:%M:%S %ZP {"%d", "7"}, // not-a-date-time from str: 7 using: %d {"%d", "07"} // 1400-Jan-07 00:00:00 from str: 07 using: %d }) { boost::posix_time::ptime m_date; date_from_string(i.first, i.second,m_date); std::cout << boost::posix_time::to_simple_string(m_date) << " from str: " << i.second << " using: " << i.first << std::endl; } } %d Day of the month as decimal 01 to 31. When used to parse input, the leading zero is optional. (emphasis mine) https://www.boost.org/doc/libs/1_75_0/doc/html/date_time/date_time_io.html (format flags)
Your program has UB. delete facet; leads to double-free. Further more, you're only using a time input facet. I wondered whether the date input facet would be required in addition. So I extended the example to rule out some of these concerns: Live On Compiler Explorer #include <boost/date_time/local_time/local_time_io.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <iomanip> using DateTime = boost::local_time::local_date_time; using PTime = boost::posix_time::ptime; using Date = boost::gregorian::date; using boost::date_time::not_a_date_time; void date_from_string( // std::string const& dformat, std::string const& dtformat, std::string const& date_str, DateTime& date) { std::stringstream ss(date_str); ss.imbue(std::locale::classic()); ss.imbue(std::locale( // ss.getloc(), new boost::gregorian::date_input_facet(dformat))); ss.imbue(std::locale( ss.getloc(), new boost::local_time::local_time_input_facet(dtformat))); ss >> date; } void date_from_string( // std::string const& dformat, std::string const& dtformat, std::string const& date_str, PTime& date) { std::stringstream ss(date_str); ss.imbue(std::locale::classic()); ss.imbue(std::locale(ss.getloc(), new boost::gregorian::date_input_facet(dformat))); ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_input_facet(dtformat))); ss >> date; } void date_from_string(std::string const& dformat, std::string const& date_str, Date& date) { std::stringstream ss(date_str); ss.imbue(std::locale::classic()); ss.imbue(std::locale(ss.getloc(), new boost::gregorian::date_input_facet(dformat))); ss >> date; } int main() { std::cout << "Boost Version: " << BOOST_VERSION << std::endl; // 107500 std::string const fmt = "%a, %d %b %Y"; struct { std::string dformat, dtformat, input; } tests[]{ {fmt, fmt + " %H:%M:%S %ZP", "Thu, 17 Oct 2021 15:00:00 GMT"}, {"%d", "%d", "07"}, {fmt, fmt + " %H:%M:%S %ZP", "Thu, 7 Oct 2021 15:00:00 GMT"}, {"%d", "%d", "7"}, }; for (auto& [df, dtf, input] : tests) { std::cout << " -- from str: " << std::quoted(input) << " using: " << std::quoted(df) << "\n"; Date m_date; DateTime m_datetime(not_a_date_time); PTime m_ptime(not_a_date_time); date_from_string(df, input, m_date); date_from_string(df, dtf, input, m_datetime); date_from_string(df, dtf, input, m_ptime); std::cout << " Date: " << to_simple_string(m_date) << "\n"; std::cout << " Local: " << to_simple_string(m_datetime.date()) << "\n"; std::cout << " Posix: " << to_simple_string(m_ptime.date()) << "\n"; } } And the output confirms the bug: Boost Version: 107700 -- from str: "Thu, 17 Oct 2021 15:00:00 GMT" using: "%a, %d %b %Y" Date: 2021-Oct-17 Local: 2021-Oct-17 Posix: 2021-Oct-17 -- from str: "07" using: "%d" Date: 1400-Jan-07 Local: 1400-Jan-07 Posix: 1400-Jan-07 -- from str: "Thu, 7 Oct 2021 15:00:00 GMT" using: "%a, %d %b %Y" Date: not-a-date-time Local: not-a-date-time Posix: not-a-date-time -- from str: "7" using: "%d" Date: not-a-date-time Local: not-a-date-time Posix: not-a-date-time What Next? I'd lend support to this existing ticket: https://github.com/boostorg/date_time/issues/106 Also, I can point at this adaptive_parser I made in the past, which sidesteps the problem by not using IO streams parsing here C++ boost date_input_facet seems to parse dates unexpectedly with incorrect formats passed to the facet constructor
69,697,629
69,697,811
How do I prevent decimals from rounding off when printed in C++?
I'm doing my ICT homework and I ran into this problem: the decimals keep on getting rounded off when I print them. I've already included the <iomanip> header and used the fixed and setprecision manipulators, but it still keeps getting rounded off. Here's my code: #include <iostream> #include <iomanip> using namespace std; int main () { double num1 = 3.12345678 cout << fixed << setprecision (4); cout << num1 << endl; return 0; } When I run the program, "3.1235" comes out instead of "3.1234," which is the expected output according to my teacher. How do I prevent the fourth decimal from rounding off?
Expanding answer of @eerorika. You can use std::fesetround() to set rounding strategy, as in code below. It outputs 3.1234 as you wished. Possible values for this function's argument are FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD. Try it online! #include <iostream> #include <iomanip> #include <cfenv> int main() { double num = 3.12345678; std::fesetround(FE_TOWARDZERO); std::cout << std::fixed << std::setprecision(4) << num << std::endl; } Output: 3.1234
69,697,745
69,697,776
Erasing object from vector causes double free
When i use vector of class B, which contains allocated memory, double free error occurs. class B { public: std::string a; std::string b; int *hehe; B() { a = "Hello"; b = ", World!"; hehe = new int[7]; for (int i = 0; i < 7; ++i) { hehe[i] = i; } } ~B() { if (hehe) delete[] hehe; } }; std::vector<class B> a(5); a.erase(a.begin() + 2); Error message: a.out(46830,0x10e0015c0) malloc: *** error for object 0x7ff12dc02a80: pointer being freed was not allocated a.out(46830,0x10e0015c0) malloc: *** set a breakpoint in malloc_error_break to debug And this code is working fine. I am stunned. std::vector<class B> a(1); a.erase(a.begin());
You did not define the copy constructor or move constructor. So the same value of the pointer hehe is copied from one object to another object and the destructor frees the memory pointed to by the pointer hehe more than one time due to storing the same value of hehe in more than one object. For example the copy constructor could be defined the following way B( const B &b ) : a( b.a ), b( b.b ), hehe( new int[7] ) { for (int i = 0; i < 7; ++i) { hehe[i] = b.hehe[i]; } } Also you need to define explicitly the copy assignment operator.
69,698,066
69,698,116
When do we use arrays over vectors in C++ and vice versa?
I saw the following from this link: Vectors are part of STL. Vectors in C++ are sequence containers representing arrays that can change their size during runtime . They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements. Vectors are the dynamic arrays that are used to store data.It is different from arrays which store sequential data and are static in nature, Vectors provide more flexibility to the program. Vectors can adjust their size automatically when an element is inserted or deleted from it. If vectors can do so much, under what circumstances do we still prefer arrays? Thanks!
If vectors can do so much, under what circumstances do we still prefer arrays? A good design is not when there is nothing left to add, rather when there is nothing left to remove. Or introducing extra complexity only when it is needed.
69,698,143
69,746,334
How to fix lock order inversion?
I'm using RAII style locks such as shared_lock and lock_guard but I see that I'm hitting deadlocks. I want to know why deadlocks happen in this case so I used tsan and tsan found that there is a lock order inversion. It outputted a stack-trace and it went over my head. I can't seem find what exactly causing the lock order inversion. I however believe it might have to do with functions that takes quite bit time to return. I found that it's bad to lock for long period of time but I have to lock in order to avoid data races. I also thought that it might have to do with the fact the callbacks get invoked asyncally. Pseudo code std::unordered_map<size_t, Connection> connections; std::shared_mutex connectionMapMutex; void LongRoutine(Connection &connection) { // Do work } void onRTCDataMessage(RTC::Message message) { std::shared_lock guard(connectionMapMutex); auto connection = connections.find(message.targetPeer); if(connection == connections.end()) { return; } LongRoutine(conenction); } void onMessage(size_t peer, std::shared_ptr<TUSocket> socket) { std::lock_guard<std::shared_mutex> guard(connectionMapMutex); auto [element, inserted] = connections.try_emplace(peer); auto& connection = element->send; { // Long routine call LongRoutine(connection); return; } } void onDisconnected(size_t peer) { std::lock_guard<std::shared_mutex> guard(connectionMapMutex); connections.erase(peer); } TSan dead-lock stacktrace (Uploaded to pastebin since Stackoverflow limit the size of chars) https://pastebin.com/raw/SCq2u4Aw The stacktrace I posted is from my actual application.
Thanks to Nate Eldredge, I was eventually able to track down the second mystery mutex using GDB backtrace. I was running several lambda callbacks inside the LongRoutine but in same time re-assigning the Lambda callbacks again to the same Library Instance. According to the author of the library I'm using requires the callback thread to return before proceeding. So the solution was making sure the Lambda callbacks only assigned once not twice or more.
69,698,294
69,698,936
Should classes manage dynamic memory on their own?
If a class needs to allocate memory dynamically (e.g. std::vector), is it acceptable for the class to simply allocate and deallocate the memory internally, using operator new or malloc? The answer isn't entirely obvious to me. The lack of a system managing the memory allocation like in garbage collected languages is obviously empowering; but on the other hand, it is precisely this lack of coordination that ends up wasting memory. For instance, it would be quite trivial to make a 'fake' allocator that just passes stack memory to an object which would, under normal circumstances, require dynamic memory, but which the programmer can assert will never need more than X amount of bytes. Perhaps you think that this issue is irrelevant in the days of large address spaces, but it feels a bit lame to fall back on the hardware, this is C++ after all. EDIT I realize now how cryptic I was with the question... Let me explain it a bit better. When I say 'wasting memory', I specifically mean the kind of memory-wasting that happens with heap fragmentation. Reducing heap fragmentation is the most compelling point of making a memory managing system in C++, since (as many comments have pointed out) destructors already handle the resource management side of things. When your allocations are essentially random (you don't know where your new memory is in relation to other allocated memory) and every class could potentially allocate, you run into the sort of problem that data oriented design tries to fix: poor data locality. So the question is: would it make sense for there to be a class that does the memory management, object management, heap compaction, and maybe statistics tracking (for debugging purposes) to make the most efficient use of memory and data locality? [In this view, every class or function that allocates memory dynamically has to get a reference to that class, somehow.] Or is it better to let every class be able to allocate without necessarily making it part of the interface of that class?
If a class needs to allocate memory dynamically (e.g. std::vector), is it acceptable for the class to simply allocate and deallocate the memory internally, using operator new or malloc? Usually, we have two kinds of classes: managers of resources (including dynamic memory); "business logic" classes. Most of the times we shouldn't mix the layers of resource management and domain logic. So, if your class is a manager of a raw resource, it allocates/deallocates, initializes/deinitializes its only resource and does nothing else. In this case, new is OK and even necessary (e.g. you can't instead use std::vector when writing your own dynamic array, otherwise you don't need to write it at all). See RAII. If your class contains some app logic, it is not permitted to explicitly allocate dynamic memory, open sockets etc., but it uses other RAII-classes for that. At this high level C++ provides you with something that GC languages don't: it makes RAII-owners manage files, sockets etc. - any kind of resource, not just raw bytes of heap memory, so you don't need manual Java/C#-style try-with-resources everywhere you create a not-of-raw-memory manager object - the compiler does it for you as soon as you have a RAII class for that.
69,698,323
69,698,471
How do I fix this warning - "control reaches end of non-void function [-Wreturn-type]"
During compiling, it shows this warning - control reaches end of non-void function [-Wreturn-type]. I googled and found that this warning shows when you don't return anything in the function. But I couldn't figure out where's the error in my code. Here's my code: #include <iostream> #include <algorithm> using namespace std; int findUnique(int *a, int n){ sort(a, a+n); int i=0; while(i<n){ if(a[i]==a[i+1]){ i += 2; } else{ return a[i]; } } } int main(){ int t; cin >> t; while (t--){ int size; cin >> size; int *input = new int[size]; for (int i = 0; i < size; ++i) { cin >> input[i]; } cout << findUnique(input, size) << endl; } return 0; }
You have to know why this warning is shown to understand what to do about it, this warning is shown when your function has a return type but you haven't returned value from one or more exit points of a function. Now see in your function, you return a[i] but consider a situation where your code doesn't go in the else block at all. So after coming out of the while block. There is no return statement therefore compiler is throwing control reaches the end of non-void function [-Wreturn-type].
69,698,769
69,698,898
Why this code is NOT causing redefinition error?
#include <initializer_list> struct Foo { template <typename T> Foo(std::initializer_list<T>) {} template <typename T> Foo(std::initializer_list<typename T::BarAlias>) {} }; struct Bar { using BarAlias = Bar; }; int main() { Foo foo{ Bar{} }; } I believe that a compiler should produce two exactly the same constructors inside of Foo. Why is it even working?
You have two templates with unrelated template arguments Ts. For the second constructor to be a candidate, T should be deducible, at least. However, in template <typename T> Foo(std::initializer_list<typename T::BarAlias>) {} T is in a non-deduced context. As a result, this constructor will always be rejected thanks to SFINAE. Note how your code is different from template<class T> struct Foo { Foo(std::initializer_list<T>); Foo(std::initializer_list<typename T::BarAlias>); }; which for Foo<Bar> foo{Bar{}}; will indeed produce an error that you expect.
69,699,324
69,699,368
Program that finds the number you are thinking doesn't work properly, what is wrong?
Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input "=" it should output 16 instead it always outputs 50. Could anyone help me locate the error? #include <iostream> #include <cmath> #include <string> using namespace std; unsigned int search (unsigned int boundInf, unsigned int boundSup); int main () { int b; b = search (1, 100); cout << "Your number must be : " << b << endl; } unsigned int search (unsigned int boundInf, unsigned int boundSup) { string magnitude; int b; b = (boundSup + boundInf) / 2; cout << "Is your number <, > or = to " << b << "? "; cin >> magnitude; if (magnitude == "<") { cout << "Between " << boundInf << " and " << b << endl; search (boundInf, b); } else if (magnitude == ">") { cout << "Between " << b << " and " << boundSup << endl; search (b, boundSup); } return b; }
You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so: unsigned int search(unsigned int boundInf, unsigned int boundSup) { string magnitude; int b; b = (boundSup + boundInf) / 2; cout << "Is your number <, > or = to " << b << "? "; cin >> magnitude; if (magnitude == "<") { cout << "Between " << boundInf << " and " << b << endl; b = search(boundInf, b); } else if (magnitude == ">") { cout << "Between " << b << " and " << boundSup << endl; b = search(b, boundSup); } return b; }
69,699,327
69,707,439
V8 c++ - Failed to deserialize the V8 snapshot blob
I'm trying to use V8 library compiled via vcpkg install v8 but receiving the following error: Failed to deserialize the V8 snapshot blob. This can mean that the snapshot blob file is corrupted or missing. I'm testing it on shipped hello-world.cc example: v8::V8::InitializeICUDefaultLocation(argv[0]); v8::V8::InitializeExternalStartupData(argv[0]); std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); Isolate* isolate = Isolate::New(create_params); // << here is the crash Isolate::Scope isolate_scope(isolate); This error is generated in Isolate* isolate = Isolate::New(create_params); because inner variable i_isole doesn't have assigned any snapshot_blog: if (!i::Snapshot::Initialize(i_isolate)) { // If snapshot data was provided and we failed to deserialize it must // have been corrupted. if (i_isolate->snapshot_blob() != nullptr) { FATAL( "Failed to deserialize the V8 snapshot blob. This can mean that the " "snapshot blob file is corrupted or missing."); } Unfortunately, I'm not able to find any reference to this error. Thanks for any advice. Updated: I'm trying it on Visual Studio 2019, the same on 32-bit build and 64-bit build too. Updated: Based on vcpkg.json file, the version is "9.0.257.17". I will try to update it to the latest version if this is not some already fixed bug.
For v8::V8::InitializeExternalStartupData(argv[0]); to work, make sure you have the file snapshot_blob.bin in the same directory as the executable you've compiled. Alternatively, make sure you're passing the correct path instead of argv[0]. I don't know anything about vcpkg install v8; it could be that the library you get that way is compiled without V8_USE_EXTERNAL_STARTUP_DATA, in which case you should turn off external startup data for your build as well. If you don't have a snapshot_blob.bin file at all, that would be an indicator that this is the case.
69,699,392
69,699,465
Multithreaded idiomatic find first of substrings in a string using modern C++
It is easy to find a string in a set of strings using set::find or first of a set of strings in a set of strings using std::find_first_of. But I think that STL doesn't handle this case of find_first_of set of strings (substrings) in a string. For low latency reasons I use parallel execution, would you please let me know if this implementation is idiomatic using modern C++ : #include <string> #include <list> #include <atomic> #include <execution> #include <iostream> class Intent{ const std::list<std::string> m_Context; const std::string m_Name; std::atomic_bool m_Found; public: Intent(const std::list<std::string> context, const std::string name) : m_Context(context) , m_Name(name) , m_Found(false) {} Intent(const Intent & intent) = delete; Intent & operator=(const Intent & intent) = delete; Intent(Intent && intent) : m_Context(std::move(intent.m_Context)) , m_Name(std::move(intent.m_Name)) , m_Found(static_cast< bool >(intent.m_Found)) {} bool find(const std::string & sentence) { for_each( std::execution::par , std::begin(m_Context) , std::end(m_Context) , [& m_Found = m_Found, & sentence](const std::string & context_element){ // // Maybe after launching thread per context_element one of them make intent Found // so no need to run string::find in the remaining threads. // if(!m_Found){ if(sentence.find(context_element) != std::string::npos) { m_Found = true; } } } ); return m_Found; } const bool getFound() const {return m_Found;} const std::string & getName() const {return m_Name;} }; int main() { Intent intent({"hello", "Hi", "Good morning"}, "GREETING"); std::cout << intent.find("Hi my friend."); }
I think the idiomatic way of doing it would be to use std::find_if. Then you don't need the atomic<bool> either. // return iterator to found element or end() auto find(const std::string & sentence) { return std::find_if( std::execution::par , std::begin(m_Context) , std::end(m_Context) , [&sentence](const std::string & context_element) { return sentence.find(context_element) != std::string::npos; } ); } If you really only want a bool you could use std::any_of: bool find(const std::string & sentence) { return std::any_of( std::execution::par , std::begin(m_Context) , std::end(m_Context) , [&sentence](const std::string & context_element) { return sentence.find(context_element) != std::string::npos; } ); } You may want to consider using a std::vector instead of a std::list too. vectors provide random access iterators while lists only provide bidirectional iterators.
69,699,441
69,699,477
Store struct with deleted copy and move constructor in container
I have a struct with deleted copy and move constructors and operators, but I want to add this struct to a container. How can I solve this problem? class NonCopyable { public: NonCopyable() = default; NonCopyable(NonCopyable &&) = default; NonCopyable(const NonCopyable&) = delete; NonCopyable& operator=(const NonCopyable&) = delete; NonCopyable& operator=(NonCopyable&&) = default; }; class NonMovable { public: NonMovable() = default; NonMovable(NonMovable &&) = delete; NonMovable(const NonMovable&) = default; NonMovable& operator=(const NonMovable&) = default; NonMovable& operator=(NonMovable&&) = delete; }; struct Data : NonCopyable, NonMovable { Data(std::string str, int data) : m_str(std::move(str)), m_data(data) {} private: std::string m_str; int m_data; }; int main(int argc, char** argv) { std::unordered_map<std::string, Data> table; table.emplace("test", Data{"data",10}); return 0; } Error: /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/memory:1881:31: error: no matching constructor for initialization of 'std::__1::pair<const std::__1::basic_string<char>, Data>' ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
table.emplace("test", Data{"data",10}) will still call the move constructor of Data, you need to use std::piecewise_construct to construct the pair: std::unordered_map<std::string, Data> table; table.emplace(std::piecewise_construct, std::make_tuple("test"), std::make_tuple("data",10)); Demo. According to cppreference: template<class... Args1, class... Args2> constexpr pair(std::piecewise_construct_t, std::tuple<Args1...> first_args, std::tuple<Args2...> second_args); Forwards the elements of first_args to the constructor of first and forwards the elements of second_args to the constructor of second. This is the only non-default constructor that can be used to create a pair of non-copyable non-movable types.
69,699,589
69,701,123
freshly built Ubuntu executable fails with "Invalid argument" (exit code 126)
I've compiled and built a C++ program (that uses SDL2, in case that matters) on Ubuntu 20.0.4, but when I try to run it, it just prints "Invalid argument". If I try to run it via gdb, it also prints "Invalid argument" and then "During startup program exited with code 126." (This before it hits a breakpoint set at main.) Things I have tried: Verified that the execute bit is set on the file. Added the -no-pie linker flag, which makes it build a normal ELF executable rather than a relocatable one (see here). readelf and file now both agree it is an executable. file now prints: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=432e038be2c1180ec019b585ffbca182a80f6c55, for GNU/Linux 3.2.0, with debug_info, not stripped Checked its library dependencies with ldd. A couple dozen libraries are listed but all appear to be found successfully. Tried executing it via sudo, in case it was some weird ownership/permission problem. Same error occurs. My Makefile is pretty simple, but it ends up doing the whole compile & link process with just this one command: gcc -no-pie -o Build/soda src/*.cpp src/editline/complete.c src/editline/editline.c src/editline/sysunix.c src/MiniScript/*.cpp src/compiledData/*.c -Isrc -Isrc/editline -Isrc/MiniScript -Isrc/compiledData -lstdc++ -lm -lSDL2_image -lSDL2 Nothing funny here that I can see, except maybe for -no-pie which I mentioned above (without it, I get the same result but file sees it is a shared library). I'm out of ideas. Googling "invalid argument" doesn't work very well, but the few relevant hits I have found suggest that it's a generic error message for any failure to execute a file: wrong architecture, wrong file type, etc. But since I have literally just built it on this very machine, it's hard to see how those could apply. What else can I do to pin down what is causing this failure?
I finally stumbled upon the answer. I was working in a Parallels shared folder, i.e. a folder from the host OS (macOS, in this case) which has been mounted as a drive in the Linux file system (of the Parallels virtual machine). Apparently, running any executable from such a shared folder simply does not work. Copying the same executable to my Linux home directory, and running it from there, works fine. Conversely if I build a program in my Linux directory (where it works fine), and then copy it to a shared folder and try to run it from there, I get the "Invalid argument" error. Many thanks to all who attempted to help, and I hope the next poor sap who runs into this gotcha finds this question.
69,699,756
69,700,745
Parse command line arguments string into array for posix_spawn/execve
Given single string cmd representing program command line arguments, how to get array of strings argv, that can be passed to posix_spawn or execve. Various forms of quoting (and escaping quotes) should be processed appropriately (resulting invocation should be same as in POSIX-compatible shell). Support for other escape characters would be desirable. Examples: #1, #2, #3.
As Shawn commented, in Linux and other POSIXy systems, you can use wordexp(), which is provided as part of the standard C library on such systems. For example, run.h: #ifdef __cplusplus extern "C" { #endif /* Execute binary 'bin' with arguments from string 'args'; 'args' must not be NULL or empty. Command substitution (`...` or $(...)$) is NOT performed. If 'bin' is NULL or empty, the first token in 'args' is used. Only returns if fails. Return value: -1: error in execv()/execvp(); see errno. -2: out of memory. errno==ENOMEM. -3: NULL or empty args. -4: args contains a command substitution. errno==EINVAL. -5: args has an illegal newline or | & ; < > ( ) { }. errno==EINVAL. -6: shell syntax error. errno==EINVAL. In all cases, you can use strerror(errno) for a descriptive string. */ int run(const char *bin, const char *args); #ifdef __cplusplus } #endif and compile the following C source to an object file you link into your C or C++ program or library: #define _XOPEN_SOURCE #include <stdlib.h> #include <unistd.h> #include <wordexp.h> #include <string.h> #include <errno.h> int run(const char *bin, const char *args) { /* Empty or NULL args is an invalid parameter. */ if (!args || !*args) { errno = EINVAL; return -3; } wordexp_t w; switch (wordexp(args, &w, WRDE_NOCMD)) { case 0: break; /* No error */ case WRDE_NOSPACE: errno = ENOMEM; return -2; case WRDE_CMDSUB: errno = EINVAL; return -4; case WRDE_BADCHAR: errno = EINVAL; return -5; default: errno = EINVAL; return -6; } if (w.we_wordc < 1) { errno = EINVAL; return -3; } if (!bin || !*bin) bin = w.we_wordv[0]; if (!bin || !*bin) { errno = ENOENT; return -1; } /* Note: w.ve_wordv[w.we_wordc] == NULL, per POSIX. */ if (strchr(bin, '/')) execv(bin, w.we_wordv); else execvp(bin, w.we_wordv); return -1; } For example, run(NULL, "ls -laF $HOME"); will list the contents of the current user's home directory. Environment variables will be expanded. run("bash", "sh -c 'date && echo'"); executes bash, with argv[0]=="sh", argv[1]=="-c", and argv[2]=="date && echo". This lets you control what binary will be executed.
69,699,854
69,699,907
Switch & Mapping issues - Called object type is not a function or function pointer
I am having issues with my switch function that made use of mapping to call functions from a class that I have created, and a switch function to pick them. void MerkelMain::processUserOption() { std::map<int, void(MerkelMain::*)()> menu; menu[1] = &MerkelMain::printHelp; menu[2] = &MerkelMain::printMarketStats; menu[3] = &MerkelMain::enterOffer; menu[4] = &MerkelMain::enterBid; menu[5] = &MerkelMain::printWallet; menu[6] = &MerkelMain::goToNextTimeFrame; switch (MerkelMain::getUserOption()) { case 1: menu[1](); break; case 2: menu[2](); break; case 3: menu[3](); break; case 4: menu[4](); break; case 5: menu[5](); break; case 6: menu[6](); break; default: std::cout << "Invalid input. Please enter a value between 1 and 6." << std::endl; } } This is the compile error that I've received.
All those map's values are member function pointers and needs special syntax to call. For instance for your first map entry you need (this->*menu[1])(); ^^^^^^^^^^^^^^^^ Or use more generic function std::invoke (require C++17 or later) #include <functional> // std::invoke std::invoke(menu[1], this);
69,700,068
69,700,126
When to not use lambdas over normal functions?
I am aware how a lambda works, I use lambdas pretty much everywhere in my code, is there any scenario where I should prefer using normal functions instead of lambdas
When not to use lambdas: When the function is declared in a header and implemented in a .cpp files. Can't do this with lambda. When the function is a template, and you want to be able to manually specify template arguments. Doing this with lambas requires an ugly syntax: foo.operator()<...>(...). When to use lambdas: When the function is overloaded/templated, and you want to conveniently pass it as an argument to a different function. You want to avoid ADL. Other than that, preferring regular functions over lambdas is just a convention. If you want to go against this convention, you should be prepared to explain your reasoning.
69,700,210
69,700,396
How to display output in rows of five numbers?
I'm new to programming and I have to display all the prime numbers that are the product of this code in rows of five. After too many hours of trying to find something online, this is what I came up with. This way, not even the prime numbers are being displayed in the end; only 1s all the way. I'd be happy to know what I did wrong or what I could change. #include <iomanip> #include <iostream> #include <cmath> #include <vector> using namespace std; int main() { int n { 0 }; cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl; cin >> n; vector<bool> cygnus(n + 1); for (int m = 0; m <= n; m++) { cygnus[m]=true; } for (int j = 2; j < n; j++) { if (cygnus[j] == true) { for (int i = j + 1; i <= n; i++) { if (i % j == 0) { cygnus[i] = false; } } } } int s = 0; for (auto value : cygnus) { if (value == true && s > 0) { for (int counter = s; counter++; ) { if (counter % 5 == 0) { cout << setw(3) << s << " \n "; } if (counter % 5 != 0) { cout << setw(3) << s << " "; } } } s++; } cout << endl; return 0; }
You are seriously over-complicating your output logic. Just have a counter variable declared (and initialized to zero) outside the for loop that does the output and then, every time you print a number, increment it. When that reaches the value of 5, print a newline and reset it to zero. A couple of other points: The STL containers (like std::vector) use the size_t type (not int) for their sizes and indexes. In the code below, I have changed all your int variables to this type; fortunately, that won't affect your algorithm. Note that 1 is not a prime number. Here's a re-worked version of your code: #include <iostream> #include <iomanip> #include <vector> using namespace std; int main() { size_t n{ 0 }; cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl; cin >> n; vector<bool>cygnus(n + 1); for (size_t m = 0; m <= n; m++) { cygnus[m] = true; } for (size_t j = 2; j < n; j++) { if (cygnus[j] == true) { for (size_t i = j + 1; i <= n; i++) { if (i % j == 0) { cygnus[i] = false; } } } } size_t s = 0; size_t counter = 0; for (auto value : cygnus) { if (value == true && s > 1) { // Note that 1 is NOT a prime number cout << setw(3) << s << " "; if (++counter == 5) { cout << "\n "; counter = 0; } } s++; } if (counter != 0) cout << "\n "; // Add newline for any partial last line. cout << endl; return 0; }
69,700,258
69,700,378
While loop with two conditions joined by an AND operator in HLA. Converting C++ to HLA
I want to translate (or manually compile) my program from c++ into HLA. The program reads an inputted number. Then subtracting off three and tens or only tens, determine if that value ends in a zero or a three. Three such numbers in a row win the game! One value that does not end in those numbers lose the game. I don't know how can I do a while loop with two conditions joined by an AND operator in HLA. while ((iend != 1) && (iscore < 3)) This is the full code I wrote in C++ and I want to translate it to HLA: #include <iostream> using namespace std; int main() { int inum; int iend = 0; int iscore = 0; int icheckthree; //To check if it ends in 3 int icheckzero; //To check if it ends in zero while ((iend != 1) && (iscore < 3)) { cout << "Gimme a number: "; cin >> inum; //Case 1: ends in three icheckthree = inum - 3; while (icheckthree > 0) { icheckthree = icheckthree - 10; if (icheckthree == 0) { cout << "It ends in three!" << endl; iscore++; } } icheckzero = inum; while (icheckzero > 0) { icheckzero = icheckzero - 10; } //Case 2: ends in zero if (icheckzero == 0) { cout << "It ends in zero!" << endl; iscore++; } //Case 3: Loose the game else { if (icheckzero != 0) { if(icheckthree != 0) { iend = 1; } } } if (iend == 1) { cout << "\n"; cout << "Sorry Charlie! You lose the game!" << endl; } else if (iscore == 3) { cout << "\n"; cout << "You Win The Game!" << endl; } else { cout << "Keep going..." << endl; cout << "\n"; } } }
Use logical transformations. For example, the statement: if ( <c1> && <c2> ) { <do-this-when-both-true> } can be translated to: if ( <c1> ) { if ( <c2> ) { <do-this-when-both-true> } } These two constructs are equivalent, but the latter does not use the conjunction. A while loop can be taken to if-goto-label as follows: while ( <condition> ) { <loop-body> } Loop1: if ( <condition> is false ) goto EndLoop1; <loop-body> goto Loop1; EndLoop1: Next, separately, an if statement involving the inversion of a conjunction, &&, as follows: if ( <c1> && <c2> is false ) goto label; aka if ( ! ( <c1> && <c2> ) ) goto label; Is simplified as such: if ( ! <c1> || ! <c2> ) goto label; This is by Demorgan's law of logic that relates negation with conjunction and disjunction. And, lastly, that above disjunction can be easily simplified (similar to the conjunction simplification from above) as follows: if ( ! <c1> ) goto label; if ( ! <c2> ) goto label; If the condition of a while loop is a conjunction (&&), you can put the above transformations together to create a conditional exit disjunction sequence.
69,700,465
69,700,594
How to print page by page with cout in C++?
Imagine I have this code: for (int i=0; i<1000; i++) { cout << i << endl; } So in the console, we see the result is printed once until 999. We can not see the first numbers anymore (let say from 0 to 10 or 20), even we scroll up. How can I print output page by page? I mean, for example if there are 40 lines per page, then in the console we see 0->39, and when we press Enter, the next 40 numbers will be shown (40->79), and so on, until the last number.
You could use the % (remainder) operator: for (int i=0; i<1000; i++) { std::cout << i << '\n'; if(i % 40 == 39) { std::cout << "Press return>"; std::getchar(); } } This will print lines 0-39, then 40-79 etc. If you need something that figures out how many lines the terminal has and adapts to that, you could use curses, ncurses or pdcurses. For windows, (I think) pdcurses is what you should go for. #include <curses.h> #include <iostream> int main() { initscr(); // init curses int Lines = LINES; // fetch number of lines in the terminal endwin(); // end curses for(int i = 0; i < 1000; i++) { std::cout << i << '\n'; if(i % Lines == Lines - 1) { std::cout << "Press return>"; std::getchar(); } } } This only initializes curses, fetches the number of lines in the terminal and then deinit curses. If you want, you could stay in curses-mode and use the curses functions to read and write to the terminal instead. That would give you control over the cursor position and attributes of what you print on screen, like colors and underlining etc.
69,700,503
69,700,832
myProgrammingLab Palindrome Challenge Using Recursion
I'm taking an Intro to Programming class and a good chunk of the material is drilled into our heads through myProgrammingLab. I'm having a little trouble with the concept of Recursion... It's sort of been hit or miss for me. This particular problem has me stumped. When I submit my code, it offers me CTest1.cpp: In function 'bool isPalindrome(int*, int)': CTest1.cpp:9: error: invalid conversion from 'int' to 'int*' CTest1.cpp:9: error: initializing argument 1 of 'bool isPalindrome(int*, int)'" as advice, which I can assure you is not very helpful. Lol I think my main problem is when I get to the actual recursion. I'm aware that something's off, but.. If you could just point me in the right direction, I would very much appreciate it. A 'array palindrome' is an array which, when its elements are reversed, remains the same (i.e., the elements of the array are same when scanned forward or backward) Write a recursive, bool-valued function, isPalindrome, that accepts an integer -valued array , and the number of elements and returns whether the array is a palindrome. An array is a palindrome if: the array is empty (0 elements ) or contains only one element (which therefore is the same when reversed), or the first and last elements of the array are the same, and the rest of the array (i.e., the second through next-to-last elements ) form a palindrome. My code so far: bool isPalindrome(int arr[], int n) { if (n == 0 || n == 1) { return true; } else if (arr[n-1] == isPalindrome(arr[((n-1) - n) +1 ], n)) { return true; } else { return false; } }
Recursion mostly has three main components: a stopping condition (when you reach an array size small enough to be a guaranteed palindrome (0 or 1)), a computation step (e.g. to compare the first and last item of the array and determine whether it makes sense to continue) and a data subset selection for the nested recursion call (e.g. an array of size n - 2, excluding the first and last characters, which we already compared and found “palindrome-worthy”). The three components in code: bool isPalindrome(int arr[], size_t n) { return n < 2 || ( arr[0] == arr[n - 1] && isPalindrome(arr + 1, n - 2)); } Of course you may want to test the function a bit (and do not forget to run it under valgrind as well): #include <iostream> int main() { std::cout << isPalindrome((int[0]){}, 0) << std::endl; std::cout << isPalindrome((int[1]){1}, 1) << std::endl; std::cout << isPalindrome((int[2]){1, 1}, 2) << std::endl; std::cout << isPalindrome((int[2]){2, 1}, 2) << std::endl; std::cout << isPalindrome((int[2]){1, 2}, 2) << std::endl; std::cout << isPalindrome((int[3]){1, 2, 1}, 3) << std::endl; std::cout << isPalindrome((int[3]){2, 2, 2}, 3) << std::endl; std::cout << isPalindrome((int[3]){2, 2, 1}, 3) << std::endl; std::cout << isPalindrome((int[4]){1, 2, 1, 2}, 4) << std::endl; std::cout << isPalindrome((int[4]){1, 2, 2, 1}, 4) << std::endl; std::cout << isPalindrome((int[4]){1, 2, 3, 2}, 4) << std::endl; std::cout << isPalindrome((int[4]){2, 3, 2, 1}, 4) << std::endl; std::cout << isPalindrome((int[4]){1, 3, 3, 1}, 4) << std::endl; } As a side note, this^^^ deadly struggle with arrays suggests that a different data type would be a much better choice. For example, std::string or std::vector can be initialized way easier, should be passed by reference and, as a bonus, STL containers carry size information with them. Additionally, you can use std::string_view for substrings and std::span for “subvectors” in your recursion, without copying the container over and over on each recursion level. Here’s an example with std::string_view and three different implementations (one with recursion and two without recursion): #include <iostream> #include <string_view> bool isPalindrome1(const std::string_view s) { return s.size() < 2 || ( s[0] == s[s.size() - 1] && isPalindrome1(s.substr(1, s.size() - 2))); } bool isPalindrome2(const std::string_view s) { const size_t end = s.size() / 2; for (size_t i = 0; i < end; ++i) if (s[i] != s[s.size() - i - 1]) return false; return true; } bool isPalindrome3(const std::string_view s) { auto b = s.begin(); const auto end = b + s.size() / 2; auto e = s.rbegin(); for (; b < end; ++b, ++e) if (*b != *e) return false; return true; } int main() { for (auto isPalindrome : {isPalindrome1, isPalindrome2, isPalindrome3}) { std::cout << isPalindrome("") << std::endl; std::cout << isPalindrome("a") << std::endl; std::cout << isPalindrome("ab") << std::endl; std::cout << isPalindrome("aa") << std::endl; std::cout << isPalindrome("abc") << std::endl; std::cout << isPalindrome("aba") << std::endl; std::cout << isPalindrome("baab") << std::endl; std::cout << isPalindrome("baba") << std::endl; } }
69,700,628
69,722,545
Simulating a kCGEventOtherMouseDown only works for right-clicking
The following code for right-clicking works: auto event = CGEventCreateMouseEvent(nullptr, kCGEventOtherMouseDown, {x, y}, kCGMouseButtonRight); CGEventSetIntegerValueField(event, kCGMouseEventClickState, 1); CGEventPost(kCGHIDEventTap, event); CFRelease(event); however, the exact same code with kCGMouseButtonRight replaced with kCGMouseButtonLeft doesn't. Sidenote: I have wondered if this is due to the latter event not registering, so I tried a "Key Test" and found out that both events register as the middle-button(although the right-click works as expected for other applications). Why does the left-click not work and how can I make it?
I was able to solve this by using kCGEventLeftMouseDown instead of kCGEventOtherMouseDown. This goes in hand with the Apple documentation of kCGEventOtherMouseDown: Specifies a mouse down event with one of buttons 2-31. (left = 0, right = 1, center = 2, extra buttons = 3-31) This also explains why the website registered left & right as center, but it does not explain why the right-click still worked(opened the context menu), but I guess that's what you gotta deal with when not looking at the docs properly.
69,700,770
69,700,786
Class constructor defining inherited classes constructor syntax error in header file
I have the below code giving me a syntax error on the BindingSocket definition, my understanding was if I wanted to define an inherited classes constructor I continue the BindingSocket definition with BindingSocket(...):Socket(...);, however this gives me a standard syntax error output. #ifndef NETWORKING_BINDINGSOCKET_HPP_ #define NETWORKING_BINDINGSOCKET_HPP_ #include <stdio.h> #include "Socket.hpp" namespace HDE { class BindingSocket: public Socket { public: BindingSocket(...) : Socket(...); }; } and then within my main cpp file I can write: HDE::BindingSocket::BindingSocket(...): Socket(...) { Strangely enough if I add a {} at the end of the header definition for the class I get no syntax error.
The inheritance is given by class BindingSocket: public Socket. The : Socket(...) after the constructor calls the parent constructor and belongs to the definition and not to the declaration. So it has to be: namespace HDE { class BindingSocket: public Socket { public: BindingSocket(...); }; } And: HDE::BindingSocket::BindingSocket(...): Socket(...) {
69,700,806
69,700,949
Handling variadic function arguments of type 'std::size_t'
I am trying to get the hang of variadic function/template parameters. However, in the two functions below, I am very confused as to why SumIndices does not compile (I get the compiler error "expansion pattern ‘std::size_t’ {aka ‘long unsigned int’} contains no parameter packs") while SumValues does. template <typename ...t_data_type> constexpr auto SumValues(t_data_type ..._values) { return (_values + ...); } constexpr auto SumIndices(std::size_t ..._indices) { return (_indices + ...); } I would much appreciate it if anyone can clarify this confusion for me!
In first case you have parameter pack. In second case, you have variadic function from C. Variadic templates allow you to type-safely pass different types into your function. Example of print with this: // Create this function to terminate argument depended lookup void PrintValues(std::ostream&){} template<typename TFirstArg, typename ...TArgs> void PrintValues(std::ostream& output, const TFirstArg& arg, const TArgs... other_args){ // Recursive call to another function which has N-1 args // If other_args are empty, it would call `void PrintValues(std::ostream&)` // If they are non empty, it would call another instantiation of this template PrintValues(output << arg, other_args...); } And this can be called this way: PrintValues(std::cout, 5LL, 7.59, "Hello world", std::string{"bingo"}); With varargs you can do this: void PrintFewNumbers(size_t number_of_args, ...) { va_list args; va_start(args, number_of_args); for (size_t idx_of_arg, idx_of_arg < number_of_args; ++idx_of_arg){ size_t current_arg = va_arg(args, size_t); std::cout << current_arg; } va_end(args); } And you can call it using this: PrintFewNumbers(0); PrintFewNumbers(5, 1,2,3,4,5); You should prefer variadic templates to variadic args because they are type safe. However, they are not always usable.
69,700,985
69,701,133
Why does the loop in openmp run sequentially?
I try run example for scheduling in openmp, but its work sequentially. omp_set_num_threads(4); #pragma omp parallel for schedule(static, 3) for (int i = 0; i < 20; i++) { printf("Thread %d is running number %d\n", omp_get_thread_num(), i); } Result: Thread 0 is running number 0 Thread 0 is running number 1 Thread 0 is running number 2 Thread 0 is running number 3 Thread 0 is running number 4 Thread 0 is running number 5 Thread 0 is running number 6 Thread 0 is running number 7 Thread 0 is running number 8 Thread 0 is running number 9 Thread 0 is running number 10 Thread 0 is running number 11 Thread 0 is running number 12 Thread 0 is running number 13 Thread 0 is running number 14 Thread 0 is running number 15 Thread 0 is running number 16 Thread 0 is running number 17 Thread 0 is running number 18 Thread 0 is running number 19 How can I get the code to work in parallel? I am using Microsoft Visual Studio 2017.
In Microsoft Visual Studio, OpenMP support is disabled by default. You can enable it with the /openmp compiler option. This option can be enabled in the project properties, under C/C++->Language->Open MP Support.
69,701,240
69,701,305
Are the sources added to a library via the add_library command PUBLIC or PRIVATE?
I'm trying to add some more structure to my CMake project. One step of this process is to move source additions to the CMakeLists.txts in a few subdirectories, whereas they are currently added during target creation via add_library. Unlike add_library, however, target_sources gives you the choice between PUBLIC, INFERFACE, and PRIVATE. The sources added by add_library obviously aren't interfaces, but I'm unsure if they are PUBLIC or PRIVATE.
CMake command add_library interprets its immediate sources as PRIVATE: the sources belongs only to the created target and aren't propagated to the target linked with the library. In general, non-PRIVATE sources has a very limited usage. If two or more targets are linked together and share a source file, then linker usually reports "multiple definitions" error about symbols defined in that file.
69,701,920
69,702,931
Why is my texture getting rotated by 90 degrees?
I am trying to draw a simple quad with a texture. I am using gluOrtho2d to set up an orthographic projection. I am unable to understand why the texture inside the quad is getting rotated 90° clockwise. The texture is a simple PNG file. This is the problematic code :- #include <GL/glew.h> #include <GL/gl.h> #include <GL/glu.h> #include <SFML/Graphics.hpp> #include <iostream> using namespace std; const int WINDOW_WIDTH = 800, WINDOW_HEIGHT = 600; sf::Texture texture; void draw() { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); float x = 0; float y = 0; sf::Texture::bind(&texture); glBegin(GL_QUADS); glVertex2f(x, y); glTexCoord2f(0, 0); glVertex2f(x + 400, y); glTexCoord2f(1, 0); glVertex2f(x + 400, y + 400); glTexCoord2f(1, 1); glVertex2f(x, y + 400); glTexCoord2f(0, 1); glEnd(); } int main() { sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "problem"); window.setActive(true); texture.loadFromFile("texture.png"); glewInit(); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); gluOrtho2D(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT); glMatrixMode(GL_MODELVIEW); bool isRunning = true; while(isRunning) { sf::Event event; while(window.pollEvent(event)) { if(event.type == sf::Event::Closed) { isRunning = false; } } draw(); window.display(); } } This is the output. Here you can see the texture is rotated by 90°
glVertex*() calls "lock in" the current color/texture-coordinates/position for a vertex and hand off those values to the GL driver: glVertex commands are used within glBegin/glEnd pairs to specify point, line, and polygon vertices. The current color, normal, texture coordinates, and fog coordinate are associated with the vertex when glVertex is called. The way you have it now: glVertex2f(x, y); glTexCoord2f(0, 0); ...that first glVertex() call is re-using the most recently set texture coordinates, those from the previous frame: glTexCoord2f(0, 1) So you need to set texture coordinates for a vertex before the position: glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x + 400, y); glTexCoord2f(1, 1); glVertex2f(x + 400, y + 400); glTexCoord2f(0, 1); glVertex2f(x, y + 400);
69,702,266
69,716,583
SDL rect not appearing
I am trying to get an SDL_Rect to appear on screen with a texture from a bitmap. I run this program and the screen is simply white, with no image. #include "SDL.h" int main(int argc, char** args) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window* window = NULL; window = SDL_CreateWindow("window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, SDL_WINDOW_SHOWN); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); SDL_Surface* surface = SDL_LoadBMP("car.bmp"); SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = 1280; rect.h = 720; SDL_RenderCopy(renderer, texture, NULL, &rect); SDL_Delay(2000); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
I got it working, I simply had to add SDL_RenderPresent()
69,702,267
69,702,395
"no instance of overloaded function "transform" matches the argument list" error with parallel execution
I have a seemingly simple problem with C++17. In below code only the last line is producing an error where I am trying to go with a parallel execution: vector<double> v(1000); transform(v.begin(), v.end(), v.begin(), [](double a) { return 2.0 * a; }); // This is fine transform(std::execution::par, v.begin(), v.end(), v.begin(), [](double a) { return 2.0 * a; }); // std::execution::par does not seem to of the right type Looks like std::execution::par is of the wrong type which is leading to "no instance of overloaded function "transform" matches the argument list" error. I am using C++17 with Visual Studio 19 where the intellisense is okay with it. The error is appearing during compilation. What could be the problem? Edit: Here is the full error message: 1>c:\users\*\file_path_name.cpp(128): error : name followed by "::" must be a class or namespace name 1> 1>c:\users\*\file_path_name.cpp(128): error : no instance of overloaded function "transform" matches the argument list 1> argument types are: (<error-type>, std::_Vector_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<double>, std::_Vec_iter_types<double, size_t, ptrdiff_t, double *, const double *, double &, const double &>>>>, std::_Vector_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<double>, std::_Vec_iter_types<double, size_t, ptrdiff_t, double *, const double *, double &, const double &>>>>, std::_Vector_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<double>, std::_Vec_iter_types<double, size_t, ptrdiff_t, double *, const double *, double &, const double &>>>>, lambda [](double)->double) 1>
Found out the problem. Cuda was interfering with it. Switching to a non cuda console project fixed the problem.
69,702,522
69,702,652
Unable to store numbers using vector
vector<int> oper(int A, int B) { std::vector <int> arrayV; int addition = A + B; arrayV.push_back(addition); int mutiplication = A * B; arrayV.push_back(mutiplication); int subtraction; if(A >=B ){ subtraction = A - B; } else(B >A );{ subtraction = B - A; } arrayV.push_back(subtraction); int division; if(A >=B ){ division = A / B; } else(B >A );{ division = B / A; } arrayV.push_back(division); } //Can anyone letme know where did I go wrong with my code that it keeps telling me "egmentation Fault (SIGSEGV)", I want arrayV to be able to store numbers after +, *, -, /;
As I and others have pointed out in the comments, you forgot to return arrayV;. Also, your else has the wrong syntax std::vector<int> oper(int A, int B) { std::vector <int> arrayV; int addition = A + B; arrayV.push_back(addition); int mutiplication = A * B; arrayV.push_back(mutiplication); int subtraction; if(A >=B ){ subtraction = A - B; } else{ subtraction = B - A; } arrayV.push_back(subtraction); int division; if(A >=B ){ division = A / B; } else{ division = B / A; } arrayV.push_back(division); return arrayV; }
69,702,654
69,704,688
What is the difference between ${CMAKE_CURRENT_LIST_DIR} and . (relative directory)?
I understand the difference between ${CMAKE_CURRENT_LIST_DIR} and ${CMAKE_CURRENT_SOURCE_DIR}, but I don't understand what the difference is between the former and simply .? For example, are there any scenarios where target_include_directories(foo PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) would behave differently than target_include_directories(imgwarp PRIVATE .) ?
Simple counterexample: add_custom_command allows you to specify a custom WORKING_DIRECTORY. Passing relative filenames to such a command would be relative to the working directory. Explicitly making them absolute with CMAKE_CURRENT_SOURCE_DIR solves that.
69,702,807
69,702,895
Possible way to find the actual billboard locations in the Billboard Highway Problem [Dynamic Programming]
I've been learning about dynamic programming the past few days and came across the Highway Billboard Problem. From what I can understand we are able to find the maximum revenue that can be generated from the possible sites, revenue, size of the highway and the minimum distance between two certain billboards. Is there a possible way we can also find out the actual billboard locations alongside the maximum revenue. For the code I've been looking at this https://www.geeksforgeeks.org/highway-billboard-problem/
Yes, it is possible to write down the sequence of the chosen sites. There are two max function calls. Replace them by own maximum choice with if, and inside branch where current site is used, add current position to list (to the emptied list in the first max clause, as far as I understand) For example, maxRev[i] = max(maxRev[i-1], revenue[nxtbb]); change to this (pseudocode, did not check validity) if (revenue[nxtbb] > maxRev[i-1]) { maxRev[i] = revenue[nxtbb]; sitelist.clear(); sitelist.push(i); } else maxRev[i] = maxRev[i-1]; and maxRev[i] = max(maxRev[i-t-1]+revenue[nxtbb], maxRev[i-1]); change to if (maxRev[i-t-1]+revenue[nxtbb] > maxRev[i-1]) { maxRev[i] = maxRev[i-t-1]+revenue[nxtbb]; sitelist.push(i); } else maxRev[i] = maxRev[i-1];
69,702,979
69,702,995
How to make the type of vector in struct determined by the user?
I have this struct that makes multiplication, addition, and subtraction on a matrix of integers. Now I want to make the type of matrix (i.e. the type of vectors) determined by the user of this struct i.e. int, double, long, etc.. struct Matrix { vector<vector<int>> mat1, mat2; vector<vector<int>> mult() { vector<vector<int>> res(mat1.size(), vector<int>(mat2.back().size())); for (int r1 = 0; r1 < mat1.size(); ++r1) { for (int c2 = 0; c2 < mat2.back().size(); ++c2) { for (int r2 = 0; r2 < mat2.size(); ++r2) { res[r1][c2] += mat1[r1][r2] * mat2[r2][c2]; } } } return res; } vector<vector<int>> add() { vector<vector<int>> res(mat1.size(), vector<int>(mat1.back().size())); for (int i = 0; i < mat1.size(); ++i) { for (int j = 0; j < mat1.back().size(); ++j) { res[i][j] = mat1[i][j] + mat2[i][j]; } } return res; } vector<vector<int>> subtract() { vector<vector<int>> res(mat1.size(), vector<int>(mat1.back().size())); for (int i = 0; i < mat1.size(); ++i) { for (int j = 0; j < mat1.back().size(); ++j) { res[i][j] = mat1[i][j] - mat2[i][j]; } } return res; } };
I want to make the type of matrix (i.e. the type of vectors) determined by the user of this struct i.e. int, double, long, etc.. You can make your Martix struct to be a template struct template<typename T> struct Matrix { std::vector<std::vector<T>> mat1, mat2; // .... replace all your int with T } Now you instantiate a Matrix class Matrix<int> mat1; // for integers Matrix<long> mat2; // for long Matrix<double> mat3; // for doubles As a side notes: Why is "using namespace std;" considered bad practice?
69,703,067
69,703,422
Performing calculations on elements, and retrieving index the index of an element in a vector
Here I am trying to perform calculations and comparisons on elements in a vector, finding average, lower value, higher value and difference. I am also having issues printing the index of elements in a vector. #include <iostream> #include <string> #include <vector> enum class OrderBookType{bid, ask}; class OrderBookEntry{ public: double price; double amount; std::string timestamp; std::string product; OrderBookType orderType; double computeAveragePrice(std::vector<OrderBookEntry>& entries); OrderBookEntry(double _price, double _amount, std::string _timestamp, std::string _product, OrderBookType _orderType): price(_price), amount(_amount), timestamp(_timestamp), product(_product), orderType(_orderType) { } //* Other kinds of functions I hope to implement for this program. */ // double computeLowPrice(std::vector<OrderBookEntry>& entries); // double computeHighPrice(std::vector<OrderBookEntry>& entries); // double computePriceSpread(std::vector<OrderBookEntry>& entries); }; double OrderBookEntry::computeAveragePrice(std::vector<OrderBookEntry> &entries) { return 5.5; // Just trying to test a for an output here } int main() { // Declaring vector entries std::vector<OrderBookEntry> entries; // Adding entries into entries entries.push_back(OrderBookEntry{ 10000, 0.001, "2020/03/17 17:01:24.88492", "BTC/USDT", OrderBookType::bid }); entries.push_back(OrderBookEntry{ 20000, 0.002, "2020/03/17 17:01:24.88492", "BTC/USDT", OrderBookType::bid }); // Prints prices of all entries for (OrderBookEntry& entry : entries) { std::cout << "The price entry " << &entry << " is " << entry.price << std::endl; } std::cout << "The lower price is " << entries.computeAveragePrice() << std::endl; return 0; } There are three issues I am having here. Firstly I am unable to call the computeAveragePrice() function to obtain the value that it is returning–in this case just a value of 5.5 for testing. The image above is the error message for the line of code below. std::cout << "The lower price is " << entries.computeAveragePrice() << std::endl; Secondly, I am getting a weird value printed when I'm trying to print the index of elements in the vector. The above is the output I got. I was expecting to get the respective indexes of the elements but got this instead. Here's the code that I used to iterate through the vector. for (OrderBookEntry& entry : entries) { std::cout << "The price entry " << &entry << " is " << entry.price << std::endl; } Lastly, I could use some reference to any article that teaches me how to perform arithmetic on values within a vector such as averages, comparisons and finding differences. Thank you in advance!
computeAveragePrice is a member function in OrderBookEntry but entries is a std::vector<OrderBookEntry>, not a OrderBookEntry so it doesn't have such a member function. I suggest that you move computeAveragePrice out of the class OrderBookEntry, which only holds information about one single OrderBookEntry. You could create another class to hold a collection of OrderBookEntry and put it there instead. This class can be a simple wrapper around a std::vector<OrderBookEntry>: Example: class OrderBook { // A class to store a collection of OrderBookEntry:s public: // A function to add an `OrderBookEntry`. You'll have to make this in // in the way you want. This is just an example: template<class... Args> decltype(auto) add(Args&&... args) { return entries.emplace_back(std::forward<Args>(args)...); } double computeAveragePrice() const; // move it here // some member functions that just call the vector's member functions: size_t size() const { return entries.size(); } OrderBookEntry& operator[](size_t idx) { return entries[idx]; } const OrderBookEntry& operator[](size_t idx) const { return entries[idx]; } auto cbegin() const { return entries.cbegin(); } auto cend() const { return entries.cend(); } auto begin() const { return entries.cbegin(); } auto end() const { return entries.cend(); } auto begin() { return entries.begin(); } auto end() { return entries.end(); } private: std::vector<OrderBookEntry> entries; // put the vector in here }; double OrderBook::computeAveragePrice() const { // you need to #include <numeric> to use the accumulate function: if(entries.empty()) return NAN; // not-a-number return std::accumulate(entries.begin(), entries.end(), 0., [](double tot, const OrderBookEntry& e ) { return tot + e.price; }) / entries.size(); } With that, your main would look like below: int main() { OrderBook entries; // use the new collection class // Adding entries into entries entries.add( // using the add() member function 10000, 0.001, "2020/03/17 17:01:24.88492", "BTC/USDT", OrderBookType::bid ); entries.add( 20000, 0.002, "2020/03/17 17:01:24.88492", "BTC/USDT", OrderBookType::bid ); // Prints prices of all entries for (OrderBookEntry& entry : entries) { std::cout << "The price entry " << &entry << " is " << entry.price << '\n'; } std::cout << "The average price is " << entries.computeAveragePrice() << '\n'; return 0; } Note though that printing &entry will print the address of the OrderBookEntry. If you want to print something meaningful you need to add an overload for operator<< that takes an OrderBookEntry as input. Example: std::ostream& operator<<(std::ostream& os, const OrderBookEntry& e) { return os << e.product; } You could then print the entry, but not by taking its address: for (const auto& entry : entries) { std::cout << "The price entry " << entry << " is " << entry.price << '\n'; // ^^^^^ }
69,703,231
69,703,296
How to write in a buffer at specific byte in c++?
I have a char buffer of length 50 bytes. In this buffer, at 20-21 bytes, I want to write a short number, of size 2 bytes, say -1234, specifically at those bytes only? How can I do that?
Looks trivial. Not sure whether this is what you want. #include <cstring> char* pc = ...; short num = ...; std::memcpy(pc + 20, &num, 2);
69,704,747
69,704,937
How to access IP address of HTTP requests using uWS?
I am using uWebSockets to do a project. What I need to do is get the sender IP address out of incoming HTTP Requests. In the documentation I can see IP address can be taken out from the WebSockets. Do anybody have an idea to cast uWS to WebSockets to get the data or is there an other way to get it? #include <iostream> #include "App.h" int main() { /* Overly simple hello world app */ uWS::App().get("/*", [](auto *res, auto *req) { // **this is the place i need to access the ip address of the incoming HttpRequest** res->end("Hello world!"); }).listen(3000, [](auto *listen_socket) { if (listen_socket) { std::cout << "Listening on port " << 3000 << std::endl; } }). run(); std::cout << "Failed to listen on port 3000" << std::endl; } Link of the library: https://unetworking.github.io/uWebSockets.js/generated/interfaces/WebSocketBehavior.html
According to the documentation, the remote address is an attribute of the response. Ergo: std::string_view remote_ip = res->getRemoteAddressAsText();
69,704,929
69,704,977
How to reverse a std::list at a given position?
I am trying to figure out how to reverse for example,grades{1, 2, 3, 4, 5, 6} starting at the third element. I know for lists we cannot do (grades.begin() + 2) to obtain the position, but I'm not sure how to go about it. This is what I have so far, where I'm just reversing the entire list: reverse(firstList.begin(), firstList.end()); I want it to be reverse so that the list becomes: grades{1, 2, 6, 5, 4, 3}
I know for lists we cannot do (grades.begin() + 2) to obtain the position, but [...] You are right about this. Providing the flexibility of list.begin() + pos means, it is cheap to do that. The std::list iterators(i.e. BidirectionalIterator) can not be randomly-accessed efficiently (i.e. it is expensive). Therefore, as per the conventional, it must be verbose. You need to be explicit to iterate via its element. That means, you can make use of std::next from <iterator> header to provide the starting point for std::reverse. #include <iterator> // std::next #include <algorithm> // std::reverse std::list<int> grades{ 1, 2, 3, 4, 5, 6 }; std::reverse(std::next(grades.begin(), 2), grades.end()); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Live Demo
69,705,223
69,705,565
How can I read a file from a C++ file launched in a Python subprocess?
I'm trying to launch a C++ file using the python function "subprocess". I can begin the execution of the program, but it does not manage to read the data file I put in parameter. However, when I lauch the C++ file directly with the same path to the same data the program works perfectly. Do you have any ideas on why it does not work using a subprocess ? The command line I'm using in my python file looks like this: datafilePath="/home/*...*/dataFile.txt" subprocess.run(["./programName", "-f "+datafilePath, (OtherOptionsWorkingFine) ], cwd="./pathToMyProgram")
I think you are adding the datafilePath argument wrongly. Try to add all args as separate list items instead of concatenating (some of) them together as a string. e.g. subprocess.run(["./programName", "-f", datafilePath, (OtherOptionsWorkingFine) ], cwd="./pathToMyProgram")
69,705,494
69,708,672
Translate (Move) the center of TopoDS_Shape to origin
I am working on a step file reader where I load the file and look at its features. What I want to achieve is to move the step file towards the origin meaning that I want the center of the part to be on the origin. By the center of the part I mean the center of the bounding box around the part. However I am having a bit of problem understanding how to do it in OpenCascade. Here is the piece of code that I think should do the trick for me STEPControl_Reader reader; IFSelect_ReturnStatus stat = reader.ReadFile(inputFilename.c_str()); reader.NbRootsForTransfer(); reader.TransferRoots(); Handle(TColStd_HSequenceOfTransient) list = reader.GiveList(); reader.TransferList(list) TopoDS_Shape Old_Original_Solid = reader.OneShape(); // Translate this shape to center gp_Trsf trsf; // TODO: How to fill this? How do I get the bounding box for Old_Original_Solid gp_Vec translation; trsf.SetTranslation(translation); BRepBuilderAPI_Transform aBRepTrsf (Old_Original_Solid, aTrsf, Standard_False); TopoDS_Shape Original_Solid = aBRepTrsf.Shape(); I have removed all the checks and logs from this code. My question specifically is if my approach (the last 5 lines) is correct at all and if it is how should I fill the translation vector. Thank you.
I figured out the way so here is the answer Bnd_Box box; BRepBndLib::Add(Old_Original_Solid, box); Standard_Real theXmin, theYmin, theZmin, theXmax, theYmax, theZmax; box.Get(theXmin, theYmin, theZmin, theXmax, theYmax, theZmax); // Translate this shape to center gp_Trsf trsf; trsf.SetTranslation(gp_Vec(-(theXmax + theXmin)*0.5, -(theYmax + theYmin)*0.5, -(theZmax + theZmin)*0.5)); Bnd_Box figures out the bounding box for a shape that is passed to it, then we get the max and min values of the bounding box in each direction and move towards the center.
69,706,366
69,706,434
Function pointer to class method as argument
As you can see by my code, I'm trying to create a onClick event for a button that invoke a function from another class (I'm trying to make my custom button class instead of using win32 default ones for testing). But even if this does not throw any error, it just doesn't invoke the given method. This is the function signature inside Button.hpp void onClick(POINT pt, void (ButtonsHandler::*clicked)(void)); This is the implementation inside Button.cpp (Using clicked() throws C++ expression preceding parentheses of apparent call must have pointer-to function type) void Button::onClick(POINT pt, void (ButtonsHandler::*clicked)(void)) { if (PtInRect(&textRect, pt) != 0) { clicked; } } And this is where I actually call it mainMenu.getPlay().onClick(pt, &ButtonsHandler::onPlay); EDIT: solved thank you guys I was just not creating a ButtonsHandler object to execute the non-static function Here's the correct code I was missing. void Button::onClick(POINT pt, void (ButtonsHandler::*clicked)(void)) { if (PtInRect(&textRect, pt) != 0) { ButtonsHandler bh; (bh.*clicked)(); } }
It just doesn't invoke the given method! The passed pointer to member function has to be called to get in effect. I assume that the Button is inherited from the ButtonsHandler. Then, for instance, you can call with the pointer to member function with this pointer as follows: void Button::onClick(POINT pt, void (ButtonsHandler::*clicked)(void)) { if (PtInRect(&textRect, pt) != 0) { (this->*clicked)(); //^^^^^^^^^^^^^^^^^^ // or // std::invoke(clicked, this) // need to include <functional> header(Since C++17) } } If both classes are unrelated, you required an instance of ButtonsHandler to call the member function. For example: ButtonsHandler obj; (obj.*clicked)(); // or // std::invoke(clicked, obj) // need to include <functional> header
69,706,413
69,706,796
How to disable long double in boost::math?
I have c++ source file, example.cpp, using some boost::math functions. My boost library is also built. To disable long double in boost::math, I did the following: g++ -DBOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS example.cpp -I<boost_header> -L<boost.*.so> My question is whether do I need to rebuild boost library with -DBOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS? Or, in other words, did the boost library differ with and without macro BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS?
Yes, there might be a difference. However, in practice, there will usually not be: Boot Math docs: Building a Library The first thing you need to ask yourself is "Do I need to build anything at all?" as the bulk of this library is header only: meaning you can use it just by #including the necessary header(s). For most simple uses, including a header (or few) is best for compile time and program size. Refer to C99 and C++ TR1 C-style Functions for pros and cons of using the TR1 components as opposed to the header only ones. The only time you need to build the library is if you want to use the extern "C" functions declared in <boost/math/tr1.hpp>. Since tr1.hpp does in fact use the BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS macro, so yes there will probably be a relevant difference. In fact from a quick scan it looks like auto-linking (on MSVC) is only caused when the preprocessor condition is not defined. Which implies that building the library is completely unnecessary when the symbol is defined. Try not linking to the library to check that assumption: g++ -DBOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS example.cpp -I<boost_header> Post Scriptum The only use of the define in libs/math/src is in boost_nexttoward and boost_nexttowardf. So unless you use these, there should be no issue. In all of Boost 1.77 the only libraries that mention these boost/math/tr1.hpp are Multiprecision and Units - but it looks like they took great care to NOT expand macros and never explicitly call the boost_* symbols. All in all, you're only looking for direct calls to [boost_]nexttoward[f] in your own code.
69,706,542
69,708,556
Please update includepath error at #include <string_view>
I have the following configuration in c_cpp_properties.json: { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "browse": { "path": [ "C:/MinGW/lib/gcc/mingw32/6.3.0/include", "C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed", "C:/MinGW/include/*", "${workspaceRoot}" ], "limitSymbolsToIncludedHeaders": true, "databaseFilename": "" }, "compilerPath": "C:/MinGW/bin/g++.exe", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "gcc-x64" } ], "version": 4 } My C++ code is: #include <string_view> using namespace::std; However, I get "There is #include error. Please update includePath". But I don't know how can I update it. I am running this on VS Code. GCC Version - 6.3.0 C++ Standard - c++17 Project structure:
This is for conclusion for this error! * Only GCC 7+ version can use <string_view> https://sourceforge.net/projects/mingw-w64/files/Multilib%20Toolchains%28Targetting%20Win32%20and%20Win64%29/ray_linn/gcc-9.x-with-ada/ does not support 7+ version gcc. However, if you search "MinGW gcc 9 version", you can find upgraded version mingw. After replace it with the old version mingw, you can use it. Really thank you for your comments! :-)
69,707,032
69,707,310
C++ async and deferred show no difference in time compared to only async
I am creating a C++ program that uses 100 random number generators. The number generators are split into two groups: ones that create 100 numbers and ones that create 10 000 000 numbers. I am trying to see the difference between: Using deferred launching for the 100 numbers and async for the 10 000 000 numbers. Using only async for both types of number generators. There's no difference in time, so my code has something wrong with it, but so far I haven't been able to find it because I am a beginner with C++. Below is the code. I've commented the part that uses only async. #include <iostream> #include <chrono> #include <future> #include <list> /* Using both deferred and async launchings: 5119 ms Using only async launching: 5139 ms */ using namespace std; class RandomNumberGenerator { public: enum class task { LIGHT, HEAVY }; task taskType; RandomNumberGenerator(): taskType(task::LIGHT) { int rnd = rand() % 2; if (rnd == 0) { taskType = task::LIGHT; } else { taskType = task::HEAVY; } } bool generateNumbers() { int number; if(taskType == task::LIGHT) { for (int i = 0; i < 100; i++) { number = rand(); } } else { for (int i = 0; i < 1000000; i++) { number = rand(); } } return true; } }; int main() { cout << "Starting to generate numbers\n"; RandomNumberGenerator objects[100]; auto start = chrono::system_clock::now(); for (int i = 0; i < 100; i++) { objects[i].generateNumbers(); future<bool> gotNumbers; if (objects[i].taskType == RandomNumberGenerator::task::LIGHT) { gotNumbers = async(launch::deferred, &RandomNumberGenerator::generateNumbers, &objects[i]); } else { gotNumbers = async(launch::async, &RandomNumberGenerator::generateNumbers, &objects[i]); } bool result = gotNumbers.get(); //future<bool> gotNumbers = async(launch::async, &RandomNumberGenerator::generateNumbers, &objects[i]); //bool result = gotNumbers.get(); } auto end = chrono::system_clock::now(); cout << "Total time = " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " seconds\n"; }
using launch::deferred or launch::async the same amount of work still needs to be done the only difference is whether it is done on another thread and the current thread blocks waiting for that thread to finish when you call gotNumbers.get() or whether the result is calculated directly in the current thread when you call gotNumbers.get(). Either way you aren't gaining any performance by using additional threads as only one thread is ever executing at a time. If you start executing the async work before calling objects[i].generateNumbers() you might see more difference (though the overhead of std::async might still outweigh the performance increase). #if 1 future<bool> gotNumbers; if ( objects[ i ].taskType == RandomNumberGenerator::task::LIGHT ) { gotNumbers = async( launch::deferred, &RandomNumberGenerator::generateNumbers, &objects[ i ] ); } else { gotNumbers = async( launch::async, &RandomNumberGenerator::generateNumbers, &objects[ i ] ); } #else future<bool> gotNumbers = async(launch::async, &RandomNumberGenerator::generateNumbers, &objects[i]); #endif objects[ i ].generateNumbers(); bool result = gotNumbers.get();
69,707,767
69,707,882
How to make a conversion from std::string_view to std::string
How is it possible that this code below with conversion from std::string_view to std::string compiles: struct S { std::string str; S(std::string_view str_view) : str{ str_view } { } }; but this one does not compile? void foo(std::string) { } int main() { std::string_view str_view{ "text" }; foo(str_view); } The second one gives an error: cannot convert argument 1 from std::string_view to std::string and no sutiable user-defined conversion from std::string_view to std::string exists. How should I call foo() properly?
The constrcutor you are trying to call is // C++11-17 template< class T > explicit basic_string( const T& t, const Allocator& alloc = Allocator() ); // C++20+ template< class T > explicit constexpr basic_string( const T& t, const Allocator& alloc = Allocator() ); and as you can see, it is marked as explicit, meaning no implicit conversion is allowed to call that constructor. With str{ str_view } you are explicitly initializing the string with the string view, so it is allowed. With foo(str_view) you are relying on the compiler to implicitly convert the string_view into a string, and because of the explicit constructor you will get a compiler error. To fix it you need to be explicit like foo(std::string{str_view});
69,707,960
69,708,337
How to stop crashes in a recursion loop
I made this simple function, but it crashes at p=29. It makes a stopped working error window. Please Help Me #include <iostream> using namespace std; char *primality(unsigned long,unsigned long i=0); int main() { for(int i=0;i<1000;i++) cout<<i<<": "<<primality(i)<<endl; }; char *primality(unsigned long p,unsigned long i) { if(i==0) { if(p<=1) return "NEITHER PRIME NOR COMPOSITE"; else if(p==2||p==3) return "\tPRIME"; else if(p%2==0||p%3==0) return "\tCOMPOSITE"; } i=5; if(i*i<=p) if(p%i==0||p%(i+2)==0) return "\tCOMPOSITE"; else return primality(p,i+6); else return "\tPRIME"; } The output after 29 is stopped and causes a crash Output: 0: NEITHER PRIME NOR COMPOSITE 1: NEITHER PRIME NOR COMPOSITE 2: PRIME 3: PRIME 4: COMPOSITE 5: PRIME 6: COMPOSITE 7: PRIME 8: COMPOSITE 9: COMPOSITE 10: COMPOSITE 11: PRIME 12: COMPOSITE 13: PRIME 14: COMPOSITE 15: COMPOSITE 16: COMPOSITE 17: PRIME 18: COMPOSITE 19: PRIME 20: COMPOSITE 21: COMPOSITE 22: COMPOSITE 23: PRIME 24: COMPOSITE 25: COMPOSITE 26: COMPOSITE 27: COMPOSITE 28: COMPOSITE 29: -------------------------------- Process exited after 2.855 seconds with return value 3221225725 Press any key to continue . . . Also, note that I got a return value. Please tell the meaning of this error message I'm also instructed to use char arrays instead of strings.
In your primality() function, char *primality(unsigned long p,unsigned long i) { if(i==0) { if(p<=1) return "NEITHER PRIME NOR COMPOSITE"; else if(p==2||p==3) return "\tPRIME"; else if(p%2==0||p%3==0) return "\tCOMPOSITE"; } i=5; if(i*i<=p) if(p%i==0||p%(i+2)==0) return "\tCOMPOSITE"; else return primality(p,i+6); else return "\tPRIME"; } You're assigning the value 5 to i every time primality() runs. So the recursion has no stop. Eventually, your stack is too tired to hold all the different primality() calls, it will cause a stack overflow. Change that to: char *primality(unsigned long p,unsigned long i = 5); char *primality(unsigned long p,unsigned long i) { if(p<=1) return "NEITHER PRIME NOR COMPOSITE"; else if(p==2||p==3) return "\tPRIME"; else if(p%2==0||p%3==0) return "\tCOMPOSITE"; if(i*i<=p) if(p%i==0||p%(i+2)==0) return "\tCOMPOSITE"; else return primality(p,i+6); else return "\tPRIME"; }