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
71,121,818
71,121,982
How to write partition for quicksort with C++
I am writing an algorithm in C++ where the user types how many numbers they want to be sorted, then the program generates an array of random numbers, and sorts them. It also displays how much time it took to sort. It only works for some of the trials, even if I use the same input. For example, if I ask the program to sort an array of 20 numbers, one of three things will happen: It will sort the array with no problems. The algorithm will time out and the terminal will print "Segmentation fault: 11". The algorithm will sort the numbers in the correct order, but one number will be replaced with a random negative number. Here is my partition algorithm (the thing giving me trouble). I am choosing the first/left item as my pivot: int partition(int arr[], int leftIndex, int rightIndex) { int i = leftIndex; int j = rightIndex; int pivotValue = arr[leftIndex]; while(i < j){ while(arr[i] <= pivotValue){ i++; } while(arr[j] > pivotValue && i < j){ j--; } if(i < j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i - 1]; arr[i - 1] = arr[leftIndex]; arr[leftIndex] = temp; return i - 1; } Here is my quicksort algorithm: void quickSort(int arr[], int left, int right) { if (left < right) { int pivot = partition(arr, left, right); quickSort(arr, left, pivot - 1); quickSort(arr, pivot + 1, right); } return; } Here is where I call everything in main(): int main() { clock_t sTime, eTime; int n; cout << "Enter an array size: " << endl; cin >> n; cout << endl; int originalArray[n]; cout << "Start generating random numbers..." << endl; for(int index=0; index<n; index++){ originalArray[index] = (rand()%100)+1; } cout << "Original array values: "; printArray(originalArray, n); cout<<"\n\n"; //Makes a copy of the original array to preserve its original order int quickArray[sizeof(originalArray)]; for(int i = 0; i < sizeof(originalArray); i++){ quickArray[i] = originalArray[i]; } //Perform quicksort sTime = clock(); quickSort(quickArray, 0, n-1); eTime = clock(); printf("Sorted array by quickSort: "); printArray(quickArray, n); cout << "\nTotal CPU time used in quickSort: " << (double)(eTime-sTime) / CLOCKS_PER_SEC * 1000.0 << " ms" << endl; cout << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int partition(int arr[], int leftIndex, int rightIndex) { int pivotIndex = leftIndex; int pivotValue = arr[pivotIndex]; int i = leftIndex; int j = rightIndex; while(i < j){ while(arr[i] <= pivotValue){ i++; if(i >= rightIndex) break; } while(arr[j] >= pivotValue){ j--; if(j <= leftIndex) break; } if(i < j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[pivotIndex] = arr[j]; arr[j] = pivotValue; return j; } void quickSort(int arr[], int left, int right) { if (left < right) { int pivot = partition(arr, left, right); quickSort(arr, left, pivot - 1); quickSort(arr, pivot + 1, right); } return; } int main() { clock_t sTime, eTime; int n; cout << "Enter an array size: " << endl; cin >> n; cout << endl; int originalArray[n]; cout << "Start generating random numbers..." << endl; for(int index=0; index<n; index++){ originalArray[index] = (rand()%100)+1; } cout << "Original array values: "; for(auto c: originalArray) { cout << c << " "; } cout<<"\n\n"; //Makes a copy of the original array to preserve its original order int quickArray[n]; for(int i = 0; i < n; i++){ quickArray[i] = originalArray[i]; } //Perform quicksort sTime = clock(); quickSort(quickArray, 0, n-1); eTime = clock(); printf("Sorted array by quickSort: "); for(auto c: quickArray) { cout << c << " "; } cout << endl; cout << "\nTotal CPU time used in quickSort: " << (double)(eTime-sTime) / CLOCKS_PER_SEC * 1000.0 << " ms" << endl; cout << endl; return 0; } There were several mistakes I've encountered. Firstly, I have added break statements in the while loops of partititon() method so that it breaks incrementing i or decrementing j if they exceeds the boundaries of the array. That was probably why you get segmentation fault sometimes. Then I've changed the swapping part at the end of the partition and returned j. Probably this part was not erroneous, but I find this solution to be more readable. Then I changed the part where you create the new array to int quickArray[n], you were creating the quickArray with sizeof(originalArray), which was wrong because it used to create an array with more elements. sizeof() returns (number of elements) * 4 since each int takes 4 bytes of memory. Now, it should be working properly. In addition, picking the first element as pivot can make your program work in O(n^2) time complexity in the worst case, try shuffling your array before sending it to the quicksort() function. By doing so, you can eliminate the worst case scenario.
71,122,029
71,230,480
Missing C++20 headers on Ubuntu 20.04 with Clang 13
I have installed clang-13, but when I try to compile a program that uses C++20 headers, I get missing header errors. #include <numeric> #include <numbers> // missing It seems that CMake uses the system headers (from the old GCC headers shipped with ubuntu). How do I convince it to use the Clang's headers instead? Numbers header is part of C++20 https://en.cppreference.com/w/cpp/header/numbers
Installing the latest version of g++ fixed the issue for me. For example, g++-11 is the latest version at the moment. To install it on Ubuntu: Add the toolchain ppa to ensure that the latest version is available: sudo add-apt-repository --update -y ppa:ubuntu-toolchain-r/test sudo apt-get update -y Then install sudo apt-get -y --fix-broken install gcc-11 g++-11 You can check for the latest version here: https://launchpad.net/~ubuntu-toolchain-r/+archive/ubuntu/test
71,122,472
71,122,558
Can I make the data of an entire C++ class be std::atomic<>
I havea class, used for data storage, of which there is only a single instance. The caller is message driven and has become too large and is a prime candidate for refactoring, such that each message is handled by a separate thread. However, these could then compete to read/write the data. If I were using mutexes (mutices?), I would only use them on write operations. I don't think that matters here, as the data are atomic, not the functions which access the data. Is there any easy way to make all of the data atomic? Currently it consists of simple types, vectors and objects of other classes. If I have to add std::atomic<> to every sub-field, I may as well use mutexes.
std::atomic requires the type to be trivially copyable. Since you are saying std::vector is involved, that makes it impossible to use it, either on the whole structure or the std::vector itself. The purpose of std::atomic is to be able to atomically replace the whole value of the object. You cannot do something like access individual members or so on. From the limited context you gave in your question, I think std::mutex is the correct approach. Each object that should be independently accessible should have its own mutex protecting it. Also note that the mutex generally needs to protect writes and reads, since a read happening unsynchronized with a write is a data race and causes undefined behavior, not only unsynchronized writes.
71,123,142
71,123,238
What causes compiling error with templated class?
I have simple codes for templated and non-templated versions of the same class. Each class has the same data structure (Point). The compiling problem happens for the templated class when defining the function with the structure Point externally. I compiled the codes with Visual Studio. //non-templated class is defined without a compiling error. class Geometry1 { public: struct Point { double x = 1, y = 2, z = 3; }; public: Point GetAPoint()//Function is defined internally { Point test; return test; } Point GetAnotherPoint();//Function will be defined externally }; Geometry1::Point Geometry1::GetAnotherPoint()//This externally defined function is fine with Point { Point test; return test; } //Now a templated version of Geometry1 is defined. Compiling error happens!!! template<typename type> class Geometry2{ public: struct Point { type x=1, y=2, z=3; }; public: Point GetAPoint()//No compiling error { Point test; return test; } Point GetAnotherPoint();//Function will be defined externally WITH compiling error }; template<class type> Geometry2<type>::Point Geometry2<type>::GetAnotherPoint()//This externally defined function causes compiling error with Point: Error C2061 syntax error: identifier 'Point' { Point test; return test; } int main() { Geometry1 geo1;//There is compiling error for this class Geometry1::Point p1 = geo1.GetAnotherPoint(); Geometry2<double> geo2;//Compiling error happens for this class Geometry2<double>::Point p2 = geo2.GetAPoint(); } Complete error messages are: Severity Code Description Project File Line Suppression State Error C2061 syntax error: identifier 'Point' TestClasstypedef TestClasstypedef.cpp 51 Error C2143 syntax error: missing ';' before '{' TestClasstypedef TestClasstypedef.cpp 52 Error C2447 '{': missing function header (old-style formal list?) TestClasstypedef TestClasstypedef.cpp 52 Error C2065 'geo1': undeclared identifier TestClasstypedef TestClasstypedef.cpp 60 Error C2065 'geo2': undeclared identifier TestClasstypedef TestClasstypedef.cpp 63 I found that if Geometry2::GetAnotherPoint() is defined internally like Geometry2::GetAPoint(), the problem will be completely solved. Could anyone help me to figure out my mistake? Thank you in advance!
The problem is that Geometry2<type>::Point is a dependent qualified name. Moreover, this dependent name is a type so you need to tell this to the compiler which you can do by adding the keyword typename before Geometry2<type>::Point. So the modified code looks like: template<class type> typename Geometry2<type>::Point Geometry2<type>::GetAnotherPoint()//note the keyword typename here { Point test; return test; }
71,123,291
71,123,376
C++, why does std::set allow lower_bound() on a type different than that of the set elements, but only if I add less<> in the set declaration?
I have this class with an overloaded comparator: struct Foo { int x; bool operator < (Foo other) const { return x < other.x; } bool operator < (int val) const { return x < val; } }; and I make a set on it: set<Foo> s; I'm allowed to call lower_bound() on a Foo, but not on an int (as you would expect). s.lower_bound(Foo{3}); // works s.lower_bound(3); //"no matching member function for call to 'lower_bound' But if instead I declare s with a less<> : set<Foo,less<>> Both calls work: s.lower_bound({3}); s.lower_bound(3); Why?
why does std::set allow lower_bound() on a type different than that of the set elements Because it is useful, and potentially more efficient. Consider for example a set of std::strings. Creating (large) strings is expensive. If you have a string view, you can use std::less<> to compare the view to the strings of the set without having to construct a string from that view. but only if I add less<> in the set declaration? Because the second type parameter, to which you passed std::less<> as the argument is the functor that the set uses to compare the elements. std::less<> is what is able to compare objects of different types. The default comparator is std::less<T> which can only compare objects of type T. std::less<> isn't the default because it didn't exist when std::set was standardised.
71,123,367
71,123,883
Encapsulation along with constructors
I want the int Medals which I put private to be unable to have negative values, but I don't know how to implement that encapsulation along with constructors. I made it so that each athlete type inherits the Athlete constructor but I don't know where to call the setMedals function for it to work. #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> using namespace std; class Athlete { private: int Medals; public: string Name; void setMedals(int newMedals) { if (newMedals >= 0) Medals = newMedals; } int getMedals() const{ return Medals; } virtual string getDescription() = 0; Athlete(string _Name, int _Medals) : Name(_Name), Medals(_Medals) {} }; class Footballer : public Athlete { public: string getDescription() { return "Footballer "; } Footballer(string Name, int Medals) : Athlete(Name, Medals) {} }; class Basketballer : public Athlete { public: string getDescription() { return "Basketballer "; } Basketballer(string Name, int Medals) : Athlete(Name, Medals) {} }; ostream& operator <<(ostream& output, vector<Athlete*> athletes) { for (int i = 0; i < athletes.size(); i++) { output << athletes[i]->getDescription() << " " << athletes[i]->Name << ": " << athletes[i]->getMedals() << " Medals" << endl; } return output; } void printAthletes(vector<Athlete*> athletes) { sort(athletes.begin(), athletes.end(), [](Athlete* a, Athlete* b) { return a->getMedals() > b->getMedals(); }); cout << athletes; } int main() { Footballer Andrew("Andrew", 3), Jack("Jack", 4); Basketballer David("David", 5), Rob("Rob", 1); vector<Athlete*> Athlete = { &Andrew, &Jack, &David, &Rob }; printAthletes(Athlete); return 0; } I hope you understand my question cause I don't know how else to phrase it.
tl;dr: Calling non-virtual function inside a constructor is generally fine, although I'd pay attention to it when dealing with larger objects. So, sth like this should do: class Athlete { private: unsigned medals{0}; public: string name; void setMedals(int m) //or just use unsigned... { if (m >= 0) medals = m; } unsigned getMedals() const{return medals;} virtual string getDescription() = 0; //should be const maybe? Athlete(string n, int m) : name(move(n)) { setMedals(m); } }; As for the extended answer: Firstly, a short disclaimer. I wonder if I should be answering that here, or maybe flag it to the moderator to move the topic topic to software engineering or some other, similar SE site, as the discussion is likely to steer away into a general "architectural" one. If either moderators, users or the OP him/herself feel like it, please do so. Having said that, on topic: the first answer, i.e. to use unsigned int is good enough. However, one may wonder what the whole purpose of getters and setters is, if they are literally a pass-through to access the variable, thus no real encapsulation is there. For that reason, one may simply consider sth like this (interface is simplified for brevity): struct Athlete { unsigned medals; }; If some sort of input validation/processing is needed, e.g. medals cannot exceed 10, one can consider using a setter and getter, e.g. class Athlete { public: explicit Athlete(unsigned m) : medals {clamp(m, 0, 10)} //or throw from constructor //depedns what one wants really {} unsigned getMedals() const { return medals; } void setMedals(unsigned m) { medals = clamp(m, 0, 10); } //again, you may throw or do anything else //clamping is just an example private: unsigned medals; }; However, a question about object's responsibility arises here. Maybe it's not the Athlete that should care about the number of medals (or whatever the value represents), but the Medals variable iself should be distinct type maintaining its own invariance. Should one decide to chase this approach, it can look like this: template <typename T, T LO, T HI> class LimitedInt { //all the needed operations }; struct Athlete { using Medals = LimitedInt<unsigned, 0, 10>; Medals medals; }; Unfortunately, no easy answers here which one is better or worse, it depends on various factors, let alone code style and frameworks used are one of them, e.g. QT uses getters and setters extensively by convention.
71,123,838
71,124,448
Pass vector of objects of derived class to function which takes vector of objects of base class
I'm new to c++ but I have experience with OOP in other languages such as java. I have three classes: class Sortable {...};, class Letter: Sortable {...};, and class Sorter {...};. Sorter has a public function vector<Sortable> sort(vector<Sortable> items_). In main, I make a vector, vector<Letter> letters; which I give some Letter objects. I then create a Sorter object and use its sort function: Sorter sorter = Sorter(); vector<Sortable> sortedLetters = sorter.sort(letters); On that second line I get two errors: No viable conversion from 'vector<Letter>' to 'vector<Sortable>' and No viable conversion from 'vector<Sortable>' to 'vector<Letter>'. That error makes sense but it leaves me with no idea how to make a function which accepts any derived class of a base class. minimum reproducible example: #include <iostream> #include <vector> using namespace std; class Sortable { public: virtual int getSortValue() = 0; }; class Letter: Sortable { int sortValue; public: Letter(int f); int getSortValue(); }; Letter::Letter(int f) { sortValue = f; } int Letter::getSortValue(){ return sortValue; } class Sorter { public: Sorter(); vector<Sortable> sort(vector<Sortable> items_); }; Sorter::Sorter() = default; vector<Sortable> sort(vector<Sortable> items_) { return items_; } int main(int argc, const char * argv[]) { Letter a = Letter(1); Letter b = Letter(4); Letter c = Letter(3); Letter d = Letter(2); vector<Letter> letters {a,b,c,d}; Sorter sorter = Sorter(); vector<Letter> sortedLetters = sorter.sort(letters); return 0; }
The idiomatic way that this would be done in C++ is to discard class Sortable and class Sorter, and have a free function template sort. Letter could either have an operator <, or you would use a function that defined "less than" for a particular context. Since C++20 things have gotten slightly nicer, as you can define operator <=> which synthesizes each of < > <= >=, and you can = default a comparison to have it compare each base and member. template <typename T, typename Pred = std::less<T>> // default comparison is < /* since C++20 */ requires std::strict_weak_order<Pred, T, T> std::vector<T> sort(std::vector<T> items, Pred less) { // items is a copy, so we aren't mutating the source object std::sort(items.begin(), items.end(), less); // or whatever return items; } class Letter { friend bool operator<(const Letter &, const Letter &); // pre C++20 this is sufficient to sort, but doesn't define >, <=, >= friend auto operator <=>(const Letter &, const Letter &) = default; // post C++20, defines < > <= >= too } bool someSpecificLetterOrder(const Letter &, const Letter &); // for sorting by a different criteria
71,123,884
71,124,076
Using r-value references outside of constructors/assignment operators
I'm currently learning about R-value references by reading tutorials. Many tutorials mention move constructors/assignment operators as the main use case of R-value references. So I'm wondering whether/how they should be used outside of the "Rule of 5". Say I have a function std::string foo(); which returns a potentially large string, and want to pass its output to int bar (const std::string& s); . Consider 3 options of doing this. 1. const std::string my_string = foo(); const int x = bar(my_string); std::string&& my_string = foo(); const int x = bar(my_string); const int x = bar(foo()); My understanding is that 2. and 3. are essentially the same (in both cases, there's never an l-value holding my_string), but 2. may be more readable (the string can be given a name, and the statement can be broken up into multiple lines). None of the 3 options does any unnecessary copies. The difference between 2. and 1. is that in 1., my_string will live till it goes out of scope, while in 2., I tell the compiler that I don't need my_string any more after passing it to bar, allowing to free its memory earlier. Is the above correct? If so, is 2. the best option to use here?
My understanding is that 2. and 3. are essentially the same No, in fact 1. and 2. are essentially the same, but 3. is different. In both 1. and 2. my_string is an lvalue, since names of variables are always lvalues. In both cases the string object lives until the end of the scope. In case of 1. because that is the scope of the object and in 2. because of the lifetime extension rules on reference binding. In 3. foo() is a prvalue (a kind of rvalue). The temporary object materialized from it and to which the reference parameter of the function binds lives until the end of the initialization of x. So if bar had different overloads taking lvalue references or rvalue references, in 1. and 2. the lvalue reference overload would be chosen and in 3. the rvalue reference overload. Since C++17, none of the three methods make unnecessary copies. There will be only one std::string object, either the temporary one in case of 2. and 3. or the named one in case of 1. Before C++17, there could be an additional copy in case of 1. to copy from the return value of foo into my_string. However the compiler was allowed to elide this copy and that probably almost always happened in practice. Since C++17 this elision is mandatory. while in 2., I tell the compiler that I don't need my_string any more after passing it to bar, Aside from this applying to 3., not 2., the compiler actually doesn't care about this at all, the lifetime of the object is not affected. It is the function you are passing to that cares. If a function takes an rvalue reference, by convention, that means that the function is allowed to use and modify the object's state in whatever way it suits it. Your function doesn't have a rvalue overload, so it doesn't matter how you pass the string to it. bar should never modify the state of the object. So to make the distinction relevant to your case, you would either add an overload int bar(std::string&&); that will be called instead of the first overload for 3. and somehow makes use of the implied permission to put the string object into an unspecified state, or you would use a single overload int bar(std::string); in which case before C++17 the parameter will be constructed through the copy constructor for 1. and 2. or the move constructor for 3. The move constructor makes use of the rvalue convention and will reuse the passed string's allocations. Or in case of 3., since C++17 definitively and optionally before that, the copy/move is elided and the parameter is directly constructed by the function foo().
71,124,571
71,124,626
How can I extern classes in a namespace?
I want to extern classes in a namespace, without defining the entire class again. For example, I have class A: class A { private: int value; public: A(int value); int get_value(); }; and class B: class B { private: int value; public: B(int value); int get_value(); }; But I want to extern the A and B classes, without defining all of them in the namespace again, like: #include "a.hpp" #include "b.hpp" namespace kc { extern class A; extern class B; } and I don't want to do: namespace kc { class A { private: int value; public: A(int value); int get_value(); }; class B { private: int value; public: B(int value); int get_value(); }; }
If you want to refer to the same classes as though they were members of the namespace, then you can do that with a pair of using declarations. namespace kc { using ::A; using ::B; }; Note however, that this does not make the classes into members of the namespace, and language features like ADL won't be affected by it.
71,124,629
71,127,783
Wrap python argument for pybind11 overloaded methods
I'm trying to create python bindings for some legacy C++ code which implemented its own 'extended' string class aString which it uses extensively. This works fine for .def(py::init<const std::string &, int>()), but once I start trying to wrap overloaded methods pybind11 does not appear to automatically cast std::string to aString. MWE adapted from the pybind11 docs: src/example.cpp: #include <pybind11/pybind11.h> // Extended string class and struct in legacy library class aString : public std::string { public: aString() : std::string() {} aString(const char *str) : std::string(str) {} aString(const std::string &str) : std::string(str) {} }; struct Pet { Pet(const aString &name, int age) : name(name), age(age) {} void set(int age_) { age = age_; } void set(const aString &name_) { name = name_; } aString name; int age; }; // Python bindings namespace py = pybind11; PYBIND11_MODULE(example, m) { py::class_<aString>(m, "aString") .def(py::init<const std::string &>()) .def("__repr__", [](const aString &a) { return "<aString ('" + a + "')>"; }); py::class_<Pet>(m, "Pet") .def(py::init<const std::string &, int>()) .def("set", static_cast<void (Pet::*)(int)>(&Pet::set), "Set the pet's age") .def("set", static_cast<void (Pet::*)(const aString &)>(&Pet::set), "Set the pet's name") .def("__repr__", [](const Pet &a) { return "<Pet ('" + a.name + "')>"; }); ; } CMakeLists.txt: cmake_minimum_required(VERSION 3.4) project(example) add_subdirectory(pybind11) pybind11_add_module(example src/example.cpp) In python, the following works fine: import example p = example.Pet("Penny", 1) p.set(3) a = example.aString("Anne") p.set(a) However, the following fails with the message: #> p.set("Jenny") --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-c5b0ff7c5315> in <module> ----> 1 p.set("Jenny") TypeError: set(): incompatible function arguments. The following argument types are supported: 1. (self: example.Pet, arg0: int) -> None 2. (self: example.Pet, arg0: example.aString) -> None Invoked with: <Pet ('Anne')>, 'Jenny' I've tried changing my pybinding to be .def("set", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), "Set the pet's name") instead of aString, but this will not compile as std::string is not one of the overload instances. I cannot add an additional overload instance for std:string in the C++ library. I would like to be able to call p.set("Jenny") and let pybind11 convert "Jenny" into aString("Jenny"), rather than p.set(example.aString("Jenny")). This is my first project with pybind11 so any help would be appreciated, thanks!
You can enable an implicit conversion between types by adding the following statement: py::implicitly_convertible<std::string, aString>(); In general py::implicitly_convertible<A, B>() works only if (as in your case) B has a constructor that takes A as its only argument.
71,124,650
71,124,738
Why do I get a WM_CHAR message with char code 3 when I press Ctrl + C?
I have a simple Win32 desktop application listening the keyboard message. When I press Ctrl + C, I got the following message sequence: WM_DOWN Ctrl WM_DOWN C WM_CHAR wParam=3 WM_UP Ctrl WM_UP C Why do I get a WM_CHAR message whose char code is 3?
Historical. "C" is the third letter of the alphabet. Ctrl-B is 2.
71,124,824
71,127,060
create a matrix with condition in C++
I want to create a matrix B from a matrix A, in C++. First column of A is distance D1, second column is distance D2. Matrix B copies the same columns (and rows) of A, except when in A it happens that D2-D1=delta exceeds a threshold. In this case, the row of A is break in two rows in B. I wrote an algorithm, but the problem is that it gives segmentation fault. Someone can help, why it happens? std::vector<float> newD1(10), newD2(10); float box=5.; int j=0; for(auto i=0;i<D1.size();i++){ float delta=D2[i]-D1[i]; if (delta>box){ //break row i in two rows: j and j+1 //first half of row i goes in row j newD1[j]=D1[i]; newD2[j]=(D1[i]+D2[i])/2.; //second half of row i goes in j+1 D1[j+1]=(D1[i]+D2[i])/2.; D2[j+1]=D2[i]; j=j+2; //we skip two row because we break up the original row in 2 rows } else{ newD1[j]=(D1[i]); newD2[j]=D2[i]; j=j+1; //we skip one row because the original row is unchanged } } Here I give you an example of matrix A and B; I also specify delta beside each line of the matrix. Matrix A: #D1 D2 delta |0 5 | 5 A= |5 15 | 10 }--> exceed the threshold, delta>5. Must break in 2 rows in `B` |15 17 | 2 B is created breaking the second line in two lines, because delta>5 : #D1 D2 delta |0 5 | 5 B= |5 10 | 5 }--> created from row #2 of `A`. `D2` is midpoint between`D1` and `D2` in row #2 in `A` |10 15 | 5 }--> created from row #2 of `A`. `D1` is midpoint between`D1` and `D2` in row #2 in `A` |15 17 | 2 EDIT: What if I want to recursively break up the rows (e.g. suppose that at row #2 in A, delta>3*box, meaning that I need to break up that row in 3 rows in B). Any suggestions?
1.You can use push_back to avoid the size definition 2.You updated D1 and D2 instead of newD1 and newD2 #include <vector> #include <iostream> using namespace std; int main() { std::vector<float> D1 = { 0,5,15 }; std::vector<float> D2 = { 5,15,17 }; std::vector<float> newD1, newD2; float box = 5.; for (auto i = 0; i < D1.size(); i++) { float delta = D2[i] - D1[i]; if (delta > box) { //break row i in two rows: j and j+1 //first half of row i goes in row j newD1.push_back(D1[i]); newD2.push_back((D1[i] + D2[i]) / 2.); //second half of row i goes in j+1 newD1.push_back ((D1[i] + D2[i]) / 2.); newD2.push_back (D2[i]); } else { newD1.push_back(D1[i]); newD2.push_back(D2[i]); } } }
71,125,138
71,131,487
SWIG - C++ to python - enum that has ULL values being converted to 0
I have a legacy C++ code base that I am using SWIG to generate python bindings for. In this code base there are enums all over that have specific values that are then used for binary operations. A typical header file used looks something like this: namespace doom { class Bar { public: struct FooIdent { enum Ident { UnknownFoo = 0, KnownFoo = 1, MainFoo = 2, SecondaryFoo = 3 }; }; enum FooPresence { Boo = 0x0, Foo1 = 0x8000000000ULL, Foo2 = 0x4000000000ULL, Foo3 = 0x2000000000ULL, FooWithA1 = 0x1000000000ULL, FooWithA2 = 0x0800000000ULL, FooWithA3 = 0x0400000000ULL, FooWithA4 = 0x0200000000ULL, FooWithB1 = 0x0100000000ULL, FooWithB2 = 0x0080000000, FooWithB3 = 0x0040000000 }; Bar(); void setVesODee( int ves, doom::Bar::FooPresence pr ); void setVesOGoo( int goo, doom::Bar::FooIdent::Ident ide ); int doSomething(); private: int m_vdee; int m_vgoo; }; } // namespace doom The corresponding .cpp file would then be: #include "bar.h" #include <iostream> namespace doom { Bar::Bar() { m_vdee = 0; m_vgoo = 0; } void Bar::setVesODee( int ves, doom::Bar::FooPresence pr ) { m_vdee = static_cast< doom::Bar::FooPresence >( ves | pr ); } void Bar::setVesOGoo( int goo, doom::Bar::FooIdent::Ident ide ) { m_vgoo = static_cast< doom::Bar::FooIdent::Ident >( goo | ide ); } int Bar::doSomething() { return m_vgoo + m_vdee; } } // namespace doom int main() { doom::Bar b = doom::Bar(); b.setVesODee(3, doom::Bar::FooWithB2); b.setVesOGoo(4, doom::Bar::FooIdent::MainFoo); int c = b.doSomething(); std::cout << c << std::endl; return 0; } The .i file would look something like this: %feature ("flatnested"); %module bar %{ #include "bar.h"; %} %rename("Bar_%s", %$isnested) ""; %include "bar.h" I build using the following commands: swig -python -c++ -py3 bar.i g++ -fPIC -c $(pkg-config --cflags --libs python3) bar.cpp bar_wrap.cxx g++ -shared -o _bar.so bar.o bar_wrap.o And I then test the code using: import bar for i in dir(bar.Bar_FooIdent): if i[0].isupper(): print(f'{i} = 0x{getattr(bar.Bar_FooIdent, i):X}') print() for i in dir(bar.Bar): if i[0].isupper(): print(f'{i} = 0x{getattr(bar.Bar, i):X}') This outputs: KnownFoo = 0x1 MainFoo = 0x2 SecondaryFoo = 0x3 UnknownFoo = 0x0 Boo = 0x0 Foo1 = 0x0 Foo2 = 0x0 Foo3 = 0x0 FooWithA1 = 0x0 FooWithA2 = 0x0 FooWithA3 = 0x0 FooWithA4 = 0x0 FooWithB1 = 0x0 FooWithB2 = 0x-80000000 FooWithB3 = 0x40000000 It seems to be that SWIG does not convert the ULL literals correctly, and I cannot figure out how to tell SWIG to interpret these as larger types. I am not very comfortable using SWIG but I have been able to make do for a while now and am able to generate most of the code I need. I searched the documentation and questions online, but I have not been able to make this work. Any pointers for making this conversion happen?
SWIG by default treats enum constants as int, even if you override with: enum FooPresence : unsigned long long { ... } This generates code in the test_wrap.cxx file like: SWIG_Python_SetConstant(d, "Foo1",SWIG_From_int(static_cast< int >(Foo1))); SWIG_Python_SetConstant(d, "Foo2",SWIG_From_int(static_cast< int >(Foo2))); I was able to get correct results by overriding the constcode typemap to assume 64-bit integers instead. test.i %module test %typemap(constcode) int %{SWIG_Python_SetConstant(d, "$1",PyLong_FromLongLong(static_cast<long long>($1)));%} %inline %{ enum FooPresence : unsigned long long { Foo1 = 0x8000000000ULL, Foo2 = 0x4000000000ULL, Foo3 = 0x2000000000ULL, FooWithA1 = 0x1000000000ULL, FooWithA2 = 0x0800000000ULL, FooWithA3 = 0x0400000000ULL, FooWithA4 = 0x0200000000ULL, FooWithB1 = 0x0100000000ULL, FooWithB2 = 0x0080000000, FooWithB3 = 0x0040000000 }; %} You can see the SWIG typemap matching search by using the -debug-tmsearch flag when building. Note that it is searching for int Foo1 and not enum FooPresence or long long Foo1: C:\test>swig -c++ -python -debug-tmsearch test.i test.i(8) : Searching for a suitable 'consttab' typemap for: int Foo1 Looking for: int Foo1 Looking for: int Looking for: SWIGTYPE Foo1 Looking for: SWIGTYPE None found test.i(8) : Searching for a suitable 'constcode' typemap for: int Foo1 Looking for: int Foo1 Looking for: int Using: %typemap(constcode) int ... Demo: >>> import test >>> hex(test.Foo1) '0x8000000000' >>> hex(test.FooWithA1) '0x1000000000'
71,125,547
71,125,832
How to use signals in C++ and How they react?
I am trying to learn all interactions about signals and I discovered a funny interaction in it I can't understand. Here's an abstract of the program, Im instructed to do execvp with grandchild, while child needs to wait for grandchild to finish. It runs correctly when without any signal interactions. void say_Hi(int num) { printf("Finished\n"); } int main() { int i = 2; char *command1[] = {"sleep", "5", NULL}; char *command2[] = {"sleep", "10", NULL}; signal(SIGCHLD, SIG_IGN); signal(SIGUSR1, say_Hi); while(i > 0) { pid_t pid = fork(); if (pid == 0) { pid_t pidChild = fork(); if (pidChild == 0) { if (i == 2) { execvp(command1[0], command1); } else { execvp(command2[0], command2); } } else if (pidChild > 0) { waitpid(pidChild, 0, 0); // kill(pid, SIGUSR1); printf("pid finished: %d\n", pidChild); exit(EXIT_FAILURE); } exit(EXIT_FAILURE); } else { //parent immediately goes to next loop i--; } } cin >> i; //just for me to pause and observate answers above return 0; } As shown above, kill(pid, SIGUSR1); is commented, the program runs correctly. Output: pid finished: 638532 //after 5 sec pid finished: 638533 //after 10 sec However, when it is uncommented. Output becomes: Finished pid finished: 638610 //after 5 sec Finished Finished Finished Finished pid finished: 638611 //after 5 sec too, why? Finished I would like to ask: The whole program finished at once after 5 secs and a total of 6 "Finished" is printed out. Why is so? Is there a way for me to modify it so that say_Hi function run in a total of two times only, in a correct time interval? Please forgive me if my code looks stupid or bulky, I'm a newbie in programming. Any Comments about my code and help are appreciated!
Answer: kill(getpid(), SIG_USR1);
71,127,515
71,128,221
How to link WinInet using msys bash shell
I am having hard time figuring out how to link WinInet when compiling from bash shell in windows (msys) 'Makefile' main: g++ -s -static -static-libgcc -static-libstdc++ -lwininet main.cpp -o main 'main.cpp' #include <Windows.h> #include <wininet.h> #define MAX 4096 #pragma comment (lib, "Wininet.lib") void Request() { HINTERNET hSession = InternetOpen("", INTERNET_OPEN_TYPE_PRECONFIG, NULL,NULL,0); } int main() { Request(); return 0; } The error I got C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\cc1m5iEc.o:main.cpp:(.text+0xfa6): undefined reference to `__imp_InternetOpenA' Things I tried : looked the path where WinInet.lib was and tried to use it with -L like so g++ -L"path\\to\\WinInet.lib" main.cpp changed #pragma comment (lib, "Wininet.lib") to #pragma comment (lib, "WinInet.lib") Tried using -m64 Tried th -L method without WinInet.lib How to properly link wininet from bash shell in msys MSYS download link
The problem is in your make file, you should move -lwininet after main.cpp g++ -s main.cpp -static -static-libgcc -static-libstdc++ -lwininet -Os -o main
71,127,814
71,128,090
MSVC 2019 _fxrstor64 and _fxsave64 intrinsics availability
What are the minimum preprocessor checks I need to make to be sure the compiler is MSVC2019 and that the _fxrstor64 and _fxsave64 intrinsics are available for use?
To check that you have (at least) the MSVC 2019 compiler, you should use the following: #if !defined(_MSC_VER) || (_MSC_VER < 1900) #error "Not MSVC or MSVC is too old" #endif For the _fxrstor64 and _fxsave64 intrinsics to be available to MSVC, you need to check that the "immintrin.h" header has been included: #ifndef _INCLUDED_IMM #error "Haven't included immintrin.h" #endif You also (perhaps obviously) need to be compiling for the x64 architecture: #ifndef _M_X64 #error "Wrong target architetcture!" #endif You could put all those checks into one test, as follows: #if defined(_MSC_VER) && (_MSC_VER >= 1900) && defined(_INCLUDED_IMM) && defined(_M_X64) // OK #else #error "Wrong compiler or target architecture, or missing header file." #endif Note that the _INCLUDED_IMM token is specific to the MSVC compiler; for example, clang-cl uses __IMMINTRIN_H. So, if you also want to enable other, MSVC-compatible compilers, you'll need to add optional checks for each of their own tokens (by looking in the "immintrin.h" header each one uses). As noted in the comments, it would likely be more sensible to explicitly #include <immintrin.h> once the other three checks have been made and passed (the include guards in that header would handle any multiple inclusions). So: #if defined(_MSC_VER) && (_MSC_VER >= 1900) && defined(_M_X64) #include <immintrin.h> // All good! #else // TODO: allow GCC / clang / ICC which also provide _fxsave64 in immintrin.h #error "Wrong compiler/version, or not x86-64." #endif (This also gets round the issue of different implementations using different tokens to signal inclusion of that header file.)
71,128,152
71,128,208
Duplication of concept requirement checks. Should we care about them?
When functions nest, the concept requirement checks often duplicate. Look at the example below, template<typename I> requires std::forward_iterator<I> auto fun1(I i){ ... }; template<typename I> requires std::forward_iterator<I> auto fun2(I i){ fun1(i); .... } fun1 is called inside fun2, thus std::forward_iterator<I> is checked twice. I want to know whether this kind of duplication of requirement checks negatively affects compile time or not. Or Do you think we should endeavor to reduce duplication of requirement checks? Addition : We can some what avoid the duplication of requirement checks like below, template<typename I> auto fun1_unchecked(I i) { ... } template<typename I> requires std::forward_iterator<I> auto fun1(I i) { return fun1_unchecked(i); } template<typename I> requires std::forward_iterator<I> auto fun2(I i) { fun1_unchecked(i); ... } But I don't know this worth the effort.
If fun1 is called by someone other than fun2, then the presence of the concept is not duplication. Code which calls just fun1 needs a conceptualized interface for it as well. They're two independent functions; one of them just so happens to call the other. If fun1 is only called by fun2, then the concept could be removed. But otherwise, it's a meaningful part of your system and should have a proper interface. As for the compile-time costs of "duplication", the standard gives C++ implementations all the leeway they need to minimize any costs. For any given type T, if a compiler (of one file) sees concept_name<T>, the compiler can freely assume that every subsequent use of concept_name<T> will produce the same value. So it can effectively cache it. So any costs of "duplication" should be minimized. Do you think we should endeavor to reduce duplication of requirement checks? No. Not unless you have actual performance metrics from actual compilers which tell you that there is an actual performance problem.
71,128,171
71,132,346
Design of data storage C++ application (maybe relational database)
I need to store and load some data in a C++ application. This data is basically going to end up as a set of tables as per a relational database. I write the data to tables using something like csv format, then parse them myself and apply the database logic I need in my C++ code. But it seems stupid to reinvent the wheel with this and end up effectively writing my own database engine. However, using something like a MySQL database seems like massive overkill for what is going to be a single user local system. I have tried setting up a MySQL daemon on my Windows system and I found it rather complex and possibly even impossible without admin privileges. It would be a serious obstacle to deployment as it would need each user's system to have MySQL set up and running. Is there a reasonable middle ground solution? Something that can provide me with a simple database, accessible from C++, without all the complexities of setting up a full MySQL install? NB. I have edited this question such that I hope it satisfies those who have voted to close the question. I am not asking for a recommendation for a tool, or someone's favourite tool or the best tools. That would be asking which database engine should I use. I am asking for what tools and design patterns are available to solve a specific programming problem - i.e. how can I get access to database like functionality from a C++ program, without writing my own database engine, nor setting up a full database server. This is conceptually no different to asking e.g. How do I print out the contents of a vector? - it's just a bigger problem. I have described the problem and what has been done so far to solve it. My understanding from the On Topic Page is that this is within scope.
You can try sqlite. Here are some simple code examples: https://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm
71,128,326
71,128,618
shader in C++ opengl2.1 doesn't compile in arch linux
I am trying to create a red triangle in C++ using graphics api opengl 2.1 like below: it will still compile but my code says that there is a error and is in white shown below: opengl 2.1 is supported! error! my code is: #include <GL/gl.h> #include <GL/glew.h> #include <GL/glu.h> #include <GLFW/glfw3.h> #include <iostream> void error_check() { GLenum error = glGetError(); if (error != NULL) { std::cout << "error!" << std::endl; } } static unsigned int CompileShader(unsigned int type, const std::string& source) { unsigned int id = glCreateShader(type); const char* src = source.c_str(); glShaderSource(id, 1, &src, nullptr); glCompileShader(id); return id; } static unsigned int CreateShader(const std::string& vertexshader, const std::string& fragmentshader) { unsigned int program = glCreateProgram(); unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexshader); unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentshader); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); return program; } int main() { glfwInit(); GLFWwindow* engine_window = glfwCreateWindow(600, 600, "Senku-Engine 2", NULL, NULL); if (engine_window == NULL) { printf("window not opening!.."); glfwTerminate(); return -1; } glfwMakeContextCurrent(engine_window); glewExperimental = GL_TRUE; glewInit(); if (GLEW_VERSION_2_1 == GL_TRUE) { std::cout << "opengl 2.1 is supported!" << std::endl; } float vertices[6] = {-0.5f, -0.5f, 0.0f, 0.5f, 0.5f, -0.5f}; unsigned int buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr); std::string vertexShader = "#version 120 core\n" "layout(location = 0) in vec4 position;\n" "void main()\n" "{\n" " gl_Position = position;\n" "}\n"; std::string fragmentShader = "#version 120 core\n" "layout(location = 0) out vec4 color;\n" "void main()\n" "{\n" " color = vec4(1.0,0.0,0.0,1.0);\n" "}\n"; unsigned int shader = CreateShader(vertexShader, fragmentShader); glUseProgram(shader); error_check(); glViewport(0, 0, 600, 600); while (!glfwWindowShouldClose(engine_window)) { glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(engine_window); glfwPollEvents(); } glfwTerminate(); return 0; } it seems my code shows the red color when using just one line of code in shader source code but doesn't work if i use more than one string.
The profile string core might not be supported by a pure GLSL 120 implementation, use #version 120 in and out are GLSL 130, layout qualifiers are GLSL 330. You need attribute vec4 position; In the fragment shader, remove the out variable and do gl_FragColor = vec4(1.0,0.0,0.0,1.0); These are the most obvious problems. If you have further errors, use glGetShaderInfoLog to query the compilation output which tells you about the problems. See Shader error handling.
71,129,442
71,129,731
cppcheck suggests to reduce scope of variable, should I?
So I have something like this int age; for (auto person : persons) { age = std::stoi(person[0]); /* Do other stuff with age in this loop*/ } Other than style, are there any performance benefits to declaring int age = std::stoi(person[0]); inside the loop?
are there any performance benefits Because of the "as-if" rule, it's reasonable to assume that there is no performance difference between two equivalent ways of declaring the same variable.
71,129,489
71,129,692
Why having both default destructor and vector member prevents class to be "nothrow movable constructible"?
Given the following code: #include <iostream> #include <vector> #include <type_traits> class Test { public: ~Test() = default; std::vector<int> m_vector; }; int main() { std::cout << std::is_nothrow_move_constructible_v<Test> << std::endl; return 0; } It outputs 0, meaning the Test class can't be "nothrow moved". However, if I remove either ~Test() or m_vector then it returns 1. How to explain this please? For reference, I'm using clang++-7 with C++17.
See [class.copy.ctor]/8: If the definition of a class X does not explicitly declare a move constructor, a non-explicit one will be implicitly declared as defaulted if and only if [other conditions omitted, and] X does not have a user-declared destructor. Thus, the Test class only has a copy constructor, not a move constructor. Any code that uses a Test rvalue to initialize a new Test object will use the copy constructor, which is not noexcept because of the vector member. If the vector member is removed, the copy constructor of Test will become trivial.
71,129,840
71,141,900
Thrust : how could i fill an array by range with index and range
I try to fill an array by range using index and values thrust::device_vector<int> vec(12) vec[1] = 2; vec[6] = 3; vec[10] = 1; the result should be vec { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0} instead i have vec { 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0} does some could tell where i'm wrong ? Thanks Here my code : #include <thrust/device_vector.h> #include <thrust/scan.h> #include <iterator> template<class T> struct FillRange { __host__ __device__ T operator()(const T& res, const T& dat) { return dat >= T(0) ? dat : 1; } }; int main() { thrust::device_vector<int> vec(12); vec[1] = 2; vec[6] = 3; vec[10] = 2; thrust::inclusive_scan( vec.rbegin(), vec.rend(), vec.rbegin(), FillRange<int>()); thrust::copy( vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; }
Here the code for the expected result. The array give index and the number of flag to be set: so for thrust::device_vector<int> vec(12) vec[1] = 2; vec[6] = 3; vec[10] = 1; the result will be vec { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0} #include <thrust/device_vector.h> #include <thrust/scan.h> #include <iterator> struct clean_ { __host__ __device__ int operator()(const int &p1) const { return (p1>0)?1:p1; } }; template<class T> struct FillRange { __host__ __device__ T operator()(const T& res, const T& dat) { return ((res-1)>0)? res-1 : dat ; } }; int main() { thrust::device_vector<int> vec(12); vec[1] = 2; vec[6] = 3; vec[11] = 2; thrust::inclusive_scan( vec.begin(), vec.end(), vec.begin(), FillRange<int>()); thrust::transform( vec.begin(), vec.end(), vec.begin(), clean_()); thrust::copy( vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; }
71,130,219
71,131,723
CMake: How to compile with different library versions of Qt?
How do you get CMake to compile conditionally with Qt4.8 or Qt5? In other words, if Qt5 is available then compile with Qt5. Otherwise if Qt4.8 is available use that. In my CMake, I have: find_package(Qt5 COMPONENTS Core Gui Widgets...) This works fine with my Qt5 builds, but how do I get the same software to build with Qt4.8? I need something that contains the major version number, eg.: find_package(Qt $QT_VERSION_MAJOR...) or to use a condition, such as: result = find_package(Qt 5...) if (!result) then find_package(Qt4 ...) or somehow detect the currently install Qt version. The error I get for the machine with Qt4.8 installed is (unsurprisingly): CMake Error at CMakeLists.txt:54 (find_package): By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "Qt5", but CMake did not find one. Could not find a package configuration file provided by "Qt5" with any of the following names: Qt5Config.cmake What is the best approach here?
Automatically selecting an available version of Qt is fairly easy with the NAME option of the find_package command. The problem is that Qt4 and Qt5 have different names for the same modules. # We first try to find the main module of Qt4, Qt5 or Qt6 find_package(QT NAMES Qt4 Qt5 Qt6 REQUIRED) set(QT Qt${QT_VERSION_MAJOR}) # We prepare lists of modules and libraries for different # versions of Qt if (QT_VERSION_MAJOR EQUAL 4) set(APP_QT_MODULES QtCore QtNetwork QtGui QtXml) set(APP_QT_TARGETS Qt4::QtCore Qt4::QtNetwork Qt4::QtGui Qt4::QtXml) else () set(APP_QT_MODULES Core Network PrintSupport Widgets Xml) set(APP_QT_TARGETS ${QT}::Core ${QT}::Network ${QT}::PrintSupport ${QT}::Widgets ${QT}::Xml) endif () # Here everything is simple - find the modules we need. find_package(${QT} REQUIRED ${APP_QT_MODULES}) . . . . . . # And at last don't forget to add libraries. add_executable(my_app app.cpp main.cpp window.cpp) target_link_libraries(my_app ${APP_QT_TARGETS}) Another problem is that Qt functions have different names too, for example qt4_add_resources and qt5_add_resources. And this is a good reason to wonder whether or not you really need Qt4 support in your project. Update We can make Qt function aliases (as is done in Qt since version 5.15). if (QT_VERSION VERSION_LESS 5.15) macro(qt_wrap_cpp) ${QT}_wrap_cpp(${ARGV}) endmacro() macro(qt_add_resources) ${QT}_add_resources(${ARGV}) endmacro() macro(qt_generate_moc) ${QT}_generate_moc(${ARGV}) endmacro() endif ()
71,130,323
71,130,766
Function to explicitly istantiate a given template function with more standard types?
I have the following question. Supposing I have a header file header.hpp with this template function declaration: template <typename T> extern T func(); And in the header.cpp file I have the function definition: template <typename T> T func() { \* do something */ }; //Following lines are for explicit istantiation of the template for some types: template double func <double> (); //1 template int func <int>(); //2 //And others... Does exists a function / class or something else which allows me to explicitly istantiate a template class definition for more templated types without the needing of writing something like lines 1 or 2 of the previous code everytime? I am searching for something like, for example: void function ( template_function list_of_types ) { //explicit istantiations of the template_function for the types given in the list_of_types container... } The signature doesn't have to be as the one above, but also similar, the important thing is that it works as I said before. Thanks.
There is no function like that. The explicit template instantiation must appear at namespace scope, so a "function" like that would have to be some sort of compiler magic (that doesn't exist), or use the preprocessor to expand into the required declarations. Something like Boost.PP has machinery to approximate what you are after. As an example: #include <boost/preprocessor/seq/for_each.hpp> #include <boost/preprocessor/tuple/to_seq.hpp> #define ARGS(...) BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)) template <typename T> void func(T) { }; #define EXPANSION(r, data, elem) template void func<elem>(elem); BOOST_PP_SEQ_FOR_EACH(EXPANSION, _, ARGS(int,double,char)) See the preprcoessor output live. It may irritate those with a preprocessor allergy, but it is one of the few legitimate uses for preprocessing remaining. At least until the C++ standard's committee chooses to give us better tools.
71,130,388
71,130,866
How to exactly invoke a function by using a member function pointer(and generics)?
Im having troubles invoking a function by using function pointer declared as a member of a struct inside of a class In the master.cpp: #include "headers/master.hh" #include "headers/bus.hh" #include <memory.h> #include <stdint.h> #include <iostream> int main() { int size = 4; Bus prova; int su = (prova.BIOS_ROM.*read_ptr)(prova.BIOS_ROM, size); printf("%p\n", (void *)prova.BIOS_ROM.read_ptr); } In the bus.hh file: #ifndef BUS_H #define BUS_H #include <stdint.h> #include <stdio.h> #include <iostream> #include <vector> #include <array> class Bus { public: template <typename T> // T is the bit width of the bus struct bus_t { T bitfield; char r_perm : 3; // 8/16/32 bit read char w_perm : 3; // 8/16/32 bit read T (Bus::*read_ptr)(struct bus_t<T> bus, int size); void (Bus::*write_ptr)(struct bus_t<T> bus, int size, T data); }; template <typename T> T read(struct bus_t<T> bus, int size); template <typename T> void write(struct bus_t<T> bus, int size, T data); struct bus_t<uint32_t> BIOS_ROM; public: Bus(); ~Bus(); }; #include "bus.tpp" #endif /* !BUS_H */ bus.tpp file: #pragma once template <typename T> T Bus::read(struct bus_t<T> bus, int size) { printf("Bus.bitfield is %d\n", bus.bitfield); printf("Size is %d\n", size); return bus.bitfield >> size; // 10 0001 = 33 } template uint32_t Bus::read(struct bus_t<uint32_t> bus, int size); template <typename T> void Bus::write(struct bus_t<T> bus, int size, T data) { //read<uint32_t>(bus, size); bus.bitfield = data; } And in the bus.cpp file: #include "headers/bus.hh" Bus::Bus() { BIOS_ROM.bitfield = 0; BIOS_ROM.r_perm = 7; BIOS_ROM.read_ptr = &Bus::read<uint32_t>; BIOS_ROM.write_ptr = &Bus::write<uint32_t>; } Bus::~Bus() { } I really cant find where the problem lies. Im new to C++(Ive been mostly programming in java/c) so I dont exactly know how generics syntax work in C++ I've also tried taking a look at this thread Why can templates only be implemented in the header file? but I didnt actually understand what should I fix in my code in order to make it run EDIT: While compiling with g++, it gives me the following error: master.cpp:11:31: error: ‘read_ptr’ was not declared in this scope 11 | int su = (prova.BIOS_ROM.*read_ptr)(prova.BIOS_ROM, size);
I have no idea why this was repeatedly closed as a duplicate to the C++ template-header question. You seem to be misunderstanding pointer-to-member syntax. I think what you're seeking is: int su = (prova.*prova.BIOS_ROM.read_ptr)(prova.BIOS_ROM, size); The general syntax for concrete objects or references to fire members there in is (obj.*memfnptr)(arguments...) If using a pointer-to-object calling a pointer-to-member, then the syntax becomes: (ptr->*memfnptr)(arguments...) You can read more about it here: Member access operators.
71,130,626
71,130,767
Base class constructor automatic call
I have troubles understanding the output of the following code when it comes to the first printed number. #include <iostream> #include <string> using namespace std; class A{ public: int x; A(){ x = 5; } }; class B: public A{ public: static int x; B(){ x++; } B(int i){ x = x+i; } B(string s){ x--; } }; int B::x=10; int main() { B b1; B b2(2008); B b3("Random string"); cout << b1.x << " : " << b2.x << " : " << b3.x << endl; return 0; } output (the first "2018" is the one I'm having troubles with) 2018 : 2018 : 2018
The first thing to note is that A::x is different from B::x. B does inherit A::x, but it introduces a new B::x which is static. Hence x in the scope of Brefers to B::x (not to A::x). Ergo, you can remove the base class without changing the output: #include <iostream> #include <string> using namespace std; class B { public: static int x; B(){ x++; } B(int i){ x = x+i; } B(string s){ x--; } }; int B::x=10; int main() { B b1; B b2(2008); B b3("Random string"); cout << b1.x << " : " << b2.x << " : " << b3.x << endl; } same output:: 2018 : 2018 : 2018 Now, B::x starts out as 10 because thats what you initialize it to. Then B b1; increments it (in the default constructor), then B b2(2008); adds 2008 to B::x, it is 2019 now. Eventually B b3("Random string"); decrements it to arrive at the value 2018. Because B::x is static you see 3 times the same output. The confusion seems to be caused by B::x being a static member and A::x being hidden by B::x. To reiterate the above: static int x; declares x to be a static member. There is only 1 for all instances. When one instance increments it then any other instance will see the incremented value as well. B::x hides A::x because they have the same name. I suppose this is not intentional. If your intention was to let B inherit x from B and use that, then you should remvoe the delcaration and definition of B::x. It's not that I don't understand a static variable, it's more like me not getting why b1 that (seemingly) call b(),outputs 2018 instead of incrementing the static x to 11 The line B b1; does increment A::x from 10 to 11. Though the constructor does not produce any output. The values are only printed after all constructors finished.
71,130,727
71,130,951
What Win32 message is sent to window at the beginning of resize?
I need Win32 analog of C#'s ResizeBegin to store some data before receiving the first WM_SIZE. I believe I used it very long ago, but cannot find any reference. For some weird reason, Spy++ on my computer is not operational (both 64- and 32-bit versions, I will deal with them later). I hope, somebody can help me out, thanks in advance! It looks like it is WM_WINDOWPOSCHANGING, at least, it is sent at the right moment. Please correct me if I am wrong!
You're looking for the WM_SIZING message.
71,131,095
71,131,170
Are default memory allocations in class declaration considered a good practice?
I have a class the members of which are allocated on heap // client.h #include <QString> #include <QTcpSocket> #include <QTextEdit> #include <QLineEdit> #include <QWidget> class Client : public QWidget { Q_OBJECT public: Client(const QString &computerName, int portNumber, QWidget *parent = nullptr); ~Client() = default; // ... private: QTcpSocket *_tcpSocket = new QTcpSocket(this); QTextEdit *_textInfo = new QTextEdit; QLineEdit *_textInput = new QLineEdit; quint16 _nextBlockSize = 0; }; // client.cpp Client::Client(const QString &computerName, int portNumber, QWidget *parent) : QWidget(parent) { // ... } I never seen default initialization done this way - whether it was done in the ctor or at the best case in the initialization section of it (e.g. _tcpSocket(new QTcpSocket(this))). I can think of multiple reasons against it: because we invoke the ctors of the objects we allocate using new, we can't use forward declaration now seeing these allocations in the class definition might suggest the user that the class has a non-trivial dtor and the objects must be freed when in fact they don't, because Qt will manage them itself seeing this in _tcpSocket = new QTcpSocket(this) is just strange to me So what's the best way to default assign objects on heap?
A default member initialiser that allocates memory is not a bad practice. However, not deleting such dynamic allocations in the destructor is a bad practice. Owning bare pointers in the first place are a bad practice. Furthermore, unnecessary dynamic allocation is a bad practice. But that's apparently a problem with the design of Qt. we can't use forward declaration now Sure you can. But I think that you mean that a forward declaration won't be sufficient. That's a good point. If you need to avoid defining those member types, then default member initialisers are not an option in such case.
71,131,187
71,133,248
CMake, edit fields visible with ccmake
I have searched online, but I haven't found anything because I don't know the correct keywords to express what I need. I am in a the build/ directory of a repository; if I run ccmake ../ there is a list of "flags (?)" that I can turn ON/OFF in order to decide what stuff do I want to build. If I want to turn ON the BUILD_THIS: ccmake ../ #press Enter to turn that flag ON #press c to configure #press e to exit #press g to generate cmake --build . --target install I am in a computer that has only cmake, and no ccmake. How can I do the same with cmake? Turn ON/OFF these flags, configure, and generate?
ccmake is a graphical interface around cmake. With access to command line, you just type what options you want to set. You do not need to have ccmake. cmake ../ -DBUILD_THIS=ON
71,132,242
71,136,020
Unable find real root for Cubic Equation in C++
I am writing a C++ program for finding the real root, x for a cubic equation 〖ax〗^3+〖bx〗^2+ cx+d=0 where a≠0 and b=0. Unfortunately, I could not output the "test case 1 & 4" (ps. sample output provided below link). Perhaps any logic syntax in my coding? Greatly appreciated if anyone could show me the correct way to do it. #include <iostream> #include <cmath> #include <iomanip> using namespace std; int main (){ int a , b, c , d; double x , y; double interval1, interval2; bool stop; b = 0; x = 0; stop = true; cin >> a; cin >> c; cin >> d; interval1 = a * pow(x , 3) + b * pow(x , 2) + c * x + d; if (interval1 < 0){ interval2 = interval1 *-1; }else{ interval2 = interval1; interval1 = interval2 * -1; } while (stop=true){ x = interval1; y = a * pow(x , 3) + b * pow(x , 2) + c * x + d; if(y>0 && y<0.001){ break; }else{ if (x<interval2) { interval1 = x + 0.000001; }else{ stop = false; } } } if (x==-0){ x = 0; } if(a==0){ cout << "NOT VALID" << endl; }else{ std::cout << std::fixed << std::setprecision(3) << x; } return 0; } The sample output Pseudocode for the program
Your code is almost done. You need to improve some points. Change int a , b, c , d; to double a , b, c , d; Change condition while (stop=true) to while (stop==true) I tested and it works as your example.
71,132,612
71,134,019
Program is not accessing correct index of array.. Why?
I come to this site in need of help, after struggling with this problem for a few days now. I am trying to program a poem that accepts some data from standard input and then outputs a poem based on that data. The code seems to be working, but it is not correct! It is giving me the wrong index of the array I am using. I would love extra eyes to help me with my code and let me know what I am doing wrong. ALSO! For some reason, I am not able to access the third array of the char array... I tried to place "SIZE - 1" in there but it prints nothing... Would love to understand why this is. Does this look right? // Program that accepts some data from standard input, #include <iostream> #include <cstring> //here... extracted. for (int sign = 0; sign < poem[line]; sign++) { if (line > word_count) { std::cout << " "; print_poem(seed); } else { print_poem(seed); }
You haven't mentioned what exactly the task is but I can at least explain to you parts of the problem. Are the correct syllables being printed? Let's assess if the correct syllables are being printed. I ran your code on my machine (with the input you provided that is "100 3 1 5 7 5") and got: nahoewachi tetsunnunoyasa munahohuke The syllable count of each line is fine (5,7,5) so that's not a problem. The first syllable you have a problem with is chi in nahoewachi. I'm only illustrating why this syllable is being printed. You can apply the same logic to the rest. Initially, the seed is 100. Before processing the first row, you apply generate_prnd, which gives 223. Before calculating chi, you print 4 other syllables (na, ho, e and wa). This means that you have applied generate_prnd 8 times before calculating the fifth syllable. Applying generate_prnd 8 times on 223 gives 711. Applying one more time (to get row) gives 822. 822%9 = 3rd row (0 indexed). Applying one more time (to get column) gives 361. 361%5 = 1st column. Therefore the index for the fifth syllable is (3,1). The string at the (3,1)th index is "chi". Therefore, the correct syllable is being printed. The indexing is correct. There's a problem with your logic if you want a different syllable to be printed. Now, let's assess why there aren't any spaces in your output. In the example you provided, num_lines=3. The word_counts (actually syllable counts) are 5, 7 and 5. You are applying a space when line (which is always less than num_lines) is greater than word_count. However, line is always less than word_count since the maximum value of line is 2 (num_lines - 1). Therefore, a space will never be printed. P.S. If you are allocating memory using new, don't forget to deallocate using delete later.
71,133,730
71,135,010
How to clear VTK points
I am new to vtk and I am writing an app to draw multiple shapes. The shapes are drawn using point picking event as follow: void Visualizer::pointPickingEventOccurred (const pcl::visualization::PointPickingEvent &event) { std::cout << "[INOF] Point picking event occurred." << std::endl; float x, y, z; if (event.getPointIndex () == -1) { return; } event.getPoint(x, y, z); std::cout << "[INOF] Point coordinate ( " << x << ", " << y << ", " << z << ")" << std::endl; points->InsertNextPoint(x, y, z); } points here is a vtk point list: vtkNew<vtkPoints> points; I am trying to clear points so I can resize it and get new points for each shape but I have not found a way to clear the list.
A simple call to points->Reset() will do the trick. It will make the object look empty without actually releasing the memory.
71,133,807
71,146,220
Issue when using property_tree for a ini file
Strange error when compiling with property tree to write and read a ini (text) file. Simple standalone program(MSVP) works fine. But when i include it in my main code, I get this error. What could this mean ? It looks like it is not happy with me including #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> When I comment them out, this error goes away. I have -lboost_system in my LD_LIBS. Would ptree come under boost_system library or could it be any other library that I should include ? In file included from /home/badri/usr/include/boost/property_tree/ptree.hpp:516, from recorder_apis.h:15, from recorder_apis.cpp:1: /home/badri/usr/include/boost/property_tree/detail/ptree_implementation.hpp: In member function ‘boost::property_tree::basic_ptree<K, D, C>& boost::property_tree::basic_ptree<Key, Data, KeyCompare>::get_child(const path_type&)’: /home/badri/usr/include/boost/property_tree/detail/ptree_implementation.hpp:571:58: error: declaration of ‘path’ shadows a global declaration [-Werror=shadow] 571 | basic_ptree<K, D, C>::get_child(const path_type &path) | ~~~~~~~~~~~~~~~~~^~~~ In file included from /home/badri/usr/include/boost/property_tree/ptree.hpp:15, from recorder_apis.h:15, from recorder_apis.cpp:1: /home/badri/usr/include/boost/property_tree/ptree_fwd.hpp:89:67: note: shadowed declaration is here 89 | typedef string_path<std::string, id_translator<std::string> > path; | ^~~~ I am only using the boost library. So I don't deal with the files ptree_fwd.hpp or ptree_implementation.hpp directly in anyway. MSVP that works fine #include<iostream> #include<boost/property_tree/ptree.hpp> #include<boost/property_tree/ini_parser.hpp> using namespace std; int main() { using boost::property_tree::ptree; ptree pt; std::string jobToken1="123"; std::string jobToken2="234"; std::string jobToken3="345"; pt.put("General.Token", "rec1"); pt.put("General.Location", "/media/sd1/abc_1"); pt.put(jobToken1+".startTime", 123456); pt.put(jobToken1+".endTime", 345678); pt.put(jobToken2+".startTime", 123456); pt.put(jobToken2+".endTime", 345678); pt.put(jobToken3+".startTime", 123456); pt.put(jobToken3+".endTime", 345678); write_ini("input.txt", pt); read_ini("input.txt", pt); for(auto& section : pt) { cout << "[" << section.first << "]\n"; for (auto& key: section.second) cout << key.first << "=" << key.second.get_value<string>() <<"\n"; } } ~
Something defines path in the surrounding scope. The error message tells you this: ptree_implementation:57.hpp: In member function ‘basic_ptree<...>& basic_ptree<...>::get_child(const path_type& path)’: error: declaration of ‘path’ shadows a global declaration [-Werror=shadow] A simple repro would be e.g. Live On Coliru namespace boost::property_tree { int path() { return 0; } } #include <boost/property_tree/ptree.hpp> What Gives? The weird thing is that the definition seems to be fine, and appears for me on line 89 of ptree_fwd as well, so something else must be afoot. Perhaps there is a rare compiler issue (only likely if your compiler is very old). Otherwise, there is likely another preprocessor issue interfering. Find out by viewing the preprocessed source (cmake -build test.cpp.i or g++ .... -E). You can upload that to a pastebin site if you want me to look at it to understand the problem. Simplify Apropos of nothing, here's a simplified version of your code: Live On Coliru #include <boost/property_tree/ini_parser.hpp> #include <iostream> int main() { using boost::property_tree::ptree; ptree pt; pt.put("General.Token", "rec1"); pt.put("General.Location", "/media/sd1/abc_1"); for (ptree::path_type p : {"123", "234", "345"}) { pt.put(p / "startTime", 123456); pt.put(p / "endTime", 345678); } write_ini(std::cout, pt); } Prints [General] Token=rec1 Location=/media/sd1/abc_1 [123] startTime=123456 endTime=345678 [234] startTime=123456 endTime=345678 [345] startTime=123456 endTime=345678
71,133,891
71,134,005
Why does GetKeyState work properly when it is on the stack, but when it is on the heap it causes a silent exit?
I might be missing something obvious, and forgive me if I am. Anyways, I have a class Keys which has method SPrintScreen as follows: class Keys{ uint32_t sentQM; // create array to be passed to SendInput function INPUT printscreen[2]; // set both types to keyboard events printscreen[0].type = INPUT_KEYBOARD; printscreen[1].type = INPUT_KEYBOARD; // assign printscreen key printscreen[0].ki.wVk = VK_SNAPSHOT; printscreen[1].ki.wVk = VK_SNAPSHOT; // add key up flag to second input printscreen[1].ki.dwFlags = KEYEVENTF_KEYUP; void SPrintScreen(){ sentQM = SendInput(2, printscreen, sizeof(INPUT)); if (sentQM != ARRAYSIZE(printscreen)){ std::cout << "could not simulate print screen" << std::endl; } } } When I create the Keys object on the stack (Keys keys;) then call SPrintScreen ( keys.SPrintScreen() ), things work as expected, and the pressing of the print screen key is simulated and the program can continue running. However when I create the Keys object on the heap (Keys* keys;), and call SPrintScreen ( keys->SPrintScreen() )the program just silently exits without any indication of why, not even a message in the console. How is this working only sometimes?
Keys* keys; does not create a Keys object. It creates a pointer to a keys object. In order do something you have to do 2 more things create a Keys objects point keys at it Like this Keys *keyObj = new Keys(); keys = keyObj; obviously you would actually do Keys *keys = new Keys(); This makes a Keys object on the heap. Alternatively, you could have one on the stack Keys mykeys; Keys *keys = &mykeys; Which works for you depends on what you are trying to do. Also try not to have naked pointers for heap objects, use shared_ptr or unique_ptr
71,133,972
71,134,136
Is there a way to detect command line arguments not running tests?
Using the googletest framework I want to write my own main function. Basically some custom initialization step needs to happen before RUN_ALL_TESTS is called. I'd like to skip this step, if the command line parameters for googletest indicate, no tests should be run (e.g. if --gtest_list_tests is passed). Is it possible to retrieve this kind of information from the test framework without the need to parse the parameters myself? What I'd like to accomplish: #include <gtest/gtest.h> bool RunAllTestsDoesNotRunTests() { // should return false, if and only if RUN_ALL_TESTS() runs any test cases // implementation? } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); if (!RunAllTestsDoesNotRunTests()) { DoExpensiveInitialization(); } return RUN_ALL_TESTS(); } Is this even possible? I've tried to identify members of ::testing::UnitTest, that would allow me to retrieve this kind of information, without any success so far though. Am I going at this the wrong way? Preferrably I'd like to avoid lazily doing the initialization via fixture or similar logic requiring me to adjust every test case.
command line arguments are detected using the GTEST_FLAG macro. An example of what you're trying to do might look like: #include <gtest/gtest.h> TEST(equality, always_passes) { EXPECT_TRUE(true); } bool RunAllTestsDoesNotRunTests() { return ::testing::GTEST_FLAG(list_tests); } void DoExpensiveInitialization() { std::cout << "Boop Boop, Beep Beep" << std::endl; } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); if (!RunAllTestsDoesNotRunTests()) { DoExpensiveInitialization(); } return RUN_ALL_TESTS(); } When compiled and linked appropriately, it can be run as: $ ./a.out Boop Boop, Beep Beep [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from equality [ RUN ] equality.always_passes [ OK ] equality.always_passes (0 ms) [----------] 1 test from equality (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test. $ ./a.out --gtest_list_tests equality. always_passes i.e. you don't see the Boop Boop, Beep Beep as the function was not called. Now if you have something that you want to have run once, if you're running tests, then adding it to the testing::Environment would also do the trick: #include <gtest/gtest.h> class MyEnvironment: public ::testing::Environment { public: virtual ~MyEnvironment() = default; // Override this to define how to set up the environment. virtual void SetUp() { std::cout << "Env Beep Beep" << std::endl; } // Override this to define how to tear down the environment. virtual void TearDown() {} }; TEST(equality, always_passes) { EXPECT_TRUE(true); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); auto* env = new MyEnvironment(); ::testing::AddGlobalTestEnvironment(env); return RUN_ALL_TESTS(); } When executed, it will also cope with filters (the previous example would not be able to cope in that case): $ ./a.out --gtest_filter=equality\* Note: Google Test filter = equality* [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. Env Beep Beep [----------] 1 test from equality [ RUN ] equality.always_passes [ OK ] equality.always_passes (0 ms) [----------] 1 test from equality (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test. $ ./a.out --gtest_filter=equality\* --gtest_list_tests equality. always_passes Again, not that the Env Beep Beep does not appear if you don't run any tests (you can check with a filter like --gtest_filter=equality, and you won't see the Env output in that case.
71,134,328
71,134,385
int32_t and int64_t Conversion Issues
In the following line of code, positive is a vector of int32_t elements. int32_t pos_accum = accumulate(positive.begin(), positive.end(), std::multiplies<int32_t>()); The compiler generates the following error that seems to make no sense: No suitable conversion function from "std::multiplies<int32_t>" to "int32_t" exists as well as 'initializing': cannot convert from '_Ty' to 'int32_t' The ultimate goal is to store the answer in an int64_t, but attempts to static_cast<int64_t> the result ends up in similar errors. Any idea what the problem is here?
The signature of std::accumulate that accepts a binary operator is template< class InputIt, class T, class BinaryOperation > constexpr T accumulate( InputIt first, InputIt last, T init, BinaryOperation op ); You're missing the init argument, which represents the initial value of the accumulation. Try accumulate(positive.begin(), positive.end(), 1, std::multiplies<int32_t>());
71,134,920
71,135,023
Pass parameter pack to function repeatedly
I need to pass a parameter pack to a function repeatedly in a loop, like this: void printString(string str) { cout << "The string is: \"" << str << "\"" << endl; } template <typename FunctionType, typename ...Args> void RunWithArgs(FunctionType functionToCall, Args...args) { for (int i = 0; i < 3; i++) functionToCall(forward <Args>(args)...); } int main() { string arg("something"); RunWithArgs (printString, arg); return 0; } The compiler gives me a hint that I'm using a moved-from object, and sure enough, the string is only passed the first time: The string is: "something" The string is: "" The string is: "" How do I pass the parameter pack to the function on every iteration of the loop?
In this line: functionToCall(forward <Args>(args)...); You are forwarding the argument, which in this case, moves it. If you don't want to move, but instead want to copy, then do that: functionToCall(args...); Here is a live example.
71,135,243
71,135,358
passing one image from batch to function in c++
I'm trying to change a code in this repo from 2D to 3D; https://github.com/sadeepj/crfasrnn_keras However, my C++ is super rusty and I'm having a hard time with one problem. I'm trying to pass the Tensor& out to this function; void ModifiedPermutohedral::compute(Tensor& out, const Tensor& in, int value_size, bool reverse, bool add) const with this line ModifiedPermutohedral mp; const Tensor& input_tensor = context->input(0); Tensor* output_tensor = NULL; OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(), &output_tensor)); mp.compute(output_tensor->SubSlice(b), input_tensor.SubSlice(b), channels, backwards_); where b is the batch index I want to pass to this compute function. However, it gives me an error that error: cannot bind non-const lvalue reference of type ‘tensorflow::Tensor&’ to an rvalue of type ‘tensorflow::Tensor’ I believe it's because output_tensor is a pointer, but how am I supposed to pass it then? Shouldn't the SubSlice function return a tensor? I've tried &(output_tensor->SubSlice(b)) *(output_tensor->SubSlice(b)) too but all creates a different error. Can anyone provide insights on how I should pass this? Thank you!
Although I am not familiar with tensorflow C++, I noticed that in mp.compute(output_tensor->SubSlice(b), input_tensor.SubSlice(b), channels, backwards_);, first argument is a rvalue such that which cannot be used for value assigning purpose. I suggest: auto sliced_putput = output_tensor->SubSlice(b); mp.compute(sliced_output, input_tensor.SubSlice(b), channels, backwards_); //Assign sliced output to the output_tensor's appropriate dimensiton
71,135,323
71,135,490
How to properly constrain an iterator based function using concepts
I have trouble understanding the concepts defined in the <iterator> header. I couldn't find good examples using them. I tried to use the concepts in a simple function to provide better error messages. I don't understand why the output_iterator takes a type but input_iterator doesn't any. Furthermore I don't know how to make the random_assign_working function more generic. template<typename T, std::input_iterator InputIter, std::output_iterator<T> OutputIter> requires std::random_access_iterator<InputIter> auto random_assign(InputIter inputBegin, InputIter inputEnd, OutputIter outBegin) { auto inputSize = std::distance(inputBegin, inputEnd); for (size_t it = 0; it < inputSize; it++) { auto randomIndex = rand()%inputSize; auto selectedInput = inputBegin[randomIndex]; // read input *outBegin = selectedInput; // write output outBegin++; } } template<std::input_iterator InputIter, std::output_iterator<uint32_t> OutputIter> requires std::random_access_iterator<InputIter> auto random_assign_working(InputIter inputBegin, InputIter inputEnd, OutputIter outBegin) { auto inputSize = std::distance(inputBegin, inputEnd); for (size_t it = 0; it < inputSize; it++) { auto randomIndex = rand()%inputSize; auto selectedInput = inputBegin[randomIndex]; // read input *outBegin = selectedInput; // write output outBegin++; } } int main() { { std::array<uint32_t, 9> input = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; std::forward_list<uint32_t> output; random_assign(input.begin(), input.end(), std::front_insert_iterator(output)); // how can I make this work random_assign_working(input.begin(), input.end(), std::front_insert_iterator(output)); // working std::stringstream buf {}; buf << "Out "; for (auto item : output) buf << " " << item; std::cout << buf.str() << std::endl; } { std::array<std::string, 9> input = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; std::vector<std::string> output; output.reserve(input.size()); random_assign(input.begin(), input.end(), output.begin()); // how can I make this work random_assign_working(input.begin(), input.end(), std::front_insert_iterator(output)); // how can I make this work } } So my questions are: How to make use of the concepts defined in <iterator> when writing functions. How do the iterator_tags tie into this? How do I check for iterator_tags? I would appreciate learning resources and pointing me in the right direction.
I don't understand why the output_iterator takes a type but input_iterator doesn't any. Because input iterators have concrete type: it's the type you get from *it. That's the iterator's reference type (iter_reference_t<I>). But output iterators don't - they just have a set of types that you can write into them. It doesn't matter what *out gives you, it matters what types you can put into *out = x; You can't ask for something broad like... give me all possible types you can write into my prospective output iterator type, O. But you can ask O if it accepts a specific type T. For instance, int* is an input iterator whose reference type is int&. But int* can also be used a an output iterator - but for a wide variety of types. int of course, but also int16_t, or uint64_t, or char, or any other type convertible to int. Hence, you can ask if I is an input_iterator, but you can only ask if O is an output_iterator for some type you're writing into it T. Let's go through your random_assign: template<typename T, std::input_iterator InputIter, std::output_iterator<T> OutputIter> requires std::random_access_iterator<InputIter> auto random_assign(InputIter inputBegin, InputIter inputEnd, OutputIter outBegin); First up, random_access_iterator refines input_iterator, so you don't need to write both. Just pick the most specific constraint. Once you do that, the type you're writing into outBegin is your input iterator's refernece type, so that's the constraint you need: template <std::random_access_iterator I, std::output_iterator<std::iter_reference_t<I>> O> void random_assign(I first, I last, O out); Next, you want to return useful information. In this case, we're advancing out a bunch of times, so we should return its new value. Full thing: template <std::random_access_iterator I, std::output_iterator<std::iter_reference_t<I>> O> auto random_assign(I first, I last, O out) -> O { // you can use distance, but we know it's random access size_t const dist = last - first; for (size_t i = 0; i != dist; ++i) { // output_iterator requires this work *out++ = first[rand() % dist]; } // law of useful return return out; }
71,135,432
71,135,518
Trying to validate double as only numbers
I just started C++ and need some help. Basically, my code is working the way I want. However, as you can see below, when I type a number and a letter, the code still counts the variable as only a number. I want the same error message that displays when someone types a letter then a number the same way for this. I know it has something to do with my function, but when I tried doing isNaN(Not-a-Number) the same problem occurred. What am I doing wrong? I have included my code for the functions validation where the problem is: #include "functions.h" #include <iostream> using namespace std; double getNumber(){ double temperature = 0; while (cout << "Please enter a temperature between -40 and 40 degrees Celsius: " && !(cin>>temperature)) { cin.clear(); cin.ignore(1000, '\n'); cin.fail(); cout << "Bad value, try again..." << endl; cout <<"\n"; } return temperature; } double validRange(double min, double max){ double temperature = 0; while(true){ temperature = getNumber(); if(temperature >= min && temperature <= max) break; else { cout << "Out of range, value must be between " << min << " and " << max << endl; } } return temperature; }
To check the validity of the input, I would suggest utilizing stod() and exception handling. Because cin takes as many expressions that can be interpreted to number as possible, and returns nonzero value if that happened. However, stod() can check the number of characters that was parsed, and if we check whether whole expression is parsed, and if not, throw, we can perform the validity check. Here's the modified getnumber(): double getNumber() { double temperature; bool got_the_value = false; while (!got_the_value) { try { cout << "Please enter a temperature between -40 and 40 degrees Celsius: "; string tmpstring; cin >> tmpstring; size_t pos; temperature = stod(tmpstring,&pos); if (tmpstring.size() != pos) { cerr << "Bad value, try again..." << endl; continue; } got_the_value = true; } catch (exception& e) { cerr << "Bad value, try again..." << endl; } } return temperature; }
71,135,484
71,135,591
I'm trying to link hdf5 to c++ code (Mac)
I have the files: main.cpp, tools.cpp, tools.h, integrator.cpp, and integrator.h. I have tried to link HDF5 to this code (it compiles/links just fine without hdf5 stuff). Here's what I am using to compile: g++ -Wall -Werror -pedantic -std=c++1y -I /usr/local/include -L/usr/local/lib -lhdf5 -lhdf5_hl -lhdf5_cpp main.cpp tools.cpp integrator.cpp The error I get is complete nonsense to me: "__ZN2H56H5FileC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjRKNS_17FileCreatPropListERKNS_15FileAccPropListE", referenced from: _main in cc76aLiD.o ld: symbol(s) not found for architecture x86_64 collect2: error: ld returned 1 exit status However, sure enough, if I take out all the HDF5 commands in my code but keep the #include "H5Cpp.h" at the top of main.cpp it works. This seems odd to me because I would assume it would fail here too? Anyone have any suggestions to try? I'm using a Mac if that is relevant. Thanks!
Maybe you want also link with -lhdf5_hl_cpp. If you had used cmake, as I suggested today, you would not have such issues.
71,135,584
71,136,043
C++ parse a file and store contents into a map
I am new, I parsed this text file and I am trying to store its contents into a map and print them out. I can't seem to get the itr to work. this is the text file addq Src,Dest subq Src,Dest imulq Src,Dest salq Src,Dest sarq Src,Dest shrq Src,Dest xorq Src,Dest andq Src,Dest orq Src,Dest incq Dest decq Dest negq Dest notq Dest #include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <iomanip> using namespace std; class CPU { map<int, int, long> registers; }; class ALU{ int add, sub, mul, divide; }; int main(int argc, const char * argv[]) { string line; string ins, src, dest; ifstream myfile("/Users/feliperivas/Documents/CPUProject/CPUProject/instrunction.txt"); map<string, string> registers; while(getline(myfile, line)){ stringstream ss(line); getline(ss, ins,','); getline(ss, src,','); registers.insert(pair<string, string>(ins, src)); cout << line << endl; // for (auto itr = registers.begin(); // itr != registers.end(); ++itr) { // cout << itr->first << '\t' // << itr->second << '\n'; } return 0; }
This works: map<string, string>::iterator itr; for (itr = registers.begin(); itr != registers.end(); ++itr) { // " : " separates itr->first and itr->second. Can be changed. std::cout << itr->first << " : " << itr->second << std::endl; } Final code: #include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <iomanip> class CPU { //std::map<int, int, long> registers; }; class ALU { int add, sub, mul, divide; }; int main(int argc, const char* argv[]) { std::string line; std::string ins, src, dest; std::ifstream myfile("input.txt"); std::map<std::string, std::string> registers; while (getline(myfile, line)) { std::stringstream ss(line); std::getline(ss, ins, ','); std::getline(ss, src, ','); registers.insert(std::pair<std::string, std::string>(ins, src)); } std::map<std::string, std::string>::iterator itr; for (itr = registers.begin(); itr != registers.end(); ++itr) { std::cout << itr->first << " : " << itr->second << std::endl; } return 0; } Also std::map<int, int, long> registers; does not make sense as maps can only store 2 values. So remove it. Also, you should not use the following line in your code: using namespace std; ...as it's considered as bad practice.
71,135,589
71,135,656
Changing variable in c++
I started learning C++ and I made a simple thing like printing variables etc, but I wanted to make a new value on a variable like in Python: test = "hello world" print(test) test = 5 print(test + 6) So I had this: string test = "hello world"; cout << test << "\n"; And now I wanted to assign a number to test, so I used int test = 5;, but I got an error: redefinition of 'test' with a different type Is it possible to assign a new type to a variable somehow?
is it possible to assign a new type to a variable somehow? A new type, no. C++ is a statically typed language. Variable types are specified at compile-time and cannot change at runtime. For what you are asking, the closest thing available is std::variant in C++17 and later, which is a fixed class type that can hold different kinds of values at runtime, eg: #include <iostream> #include <string> #include <variant> using myVariant = std::variant<int, std::string>; void print(const myVariant &v) { std::visit([](const auto &x) { std::cout << x; }, v); std::cout << "\n"; } int main() { myVariant test; test = "hello world"; print(test); test = 5; print(test); return 0; } Online Demo
71,135,634
71,135,799
display list is only displaying the head of the node
I wrote a code that asks the user to enter a custom list, and I want to display it, but it's only displaying the head node. I want to know if the problem is from the display function or the input function. I want to remove the display function later, but I want my list to be created. Here is my code: #pragma once #include <cstddef> #include <iostream> using namespace std; struct node { char data; node* next; }; node* inputList(); void displayList(node*); int exercice1() { node* head; head = inputList(); displayList(head); return 0; } node* inputList() { node* tmp; node* cur, *head; int n; do { cout << "enter the number of nodes: "; cin >> n; } while (n <= 0); tmp = new node; cout << "enter the values inside each node: "; cin >> tmp->data; head = tmp; cur = tmp; for (int i = 1; i < n; i++) { tmp = new node; cur = cur->next; cout << "enter a node: "; cin >> tmp->data; cur = tmp; } cur->next = NULL; return head; } void displayList(node* head) { if (head != NULL) { cout << head->data; displayList(head->next); } }
inputList fails to link the nodes together. We could probably get away with something like tmp = new node; cur->next = tmp; // point current node's next at new node cur = cur->next; but here's a cleaner approach: node* inputList() { node * head; // storage for the start of the list. Keeps track so we // know what to return when we're done. node ** insert = &head; // store where we're going to insert a node rather than // tracking the current node with another variable. // this is both tmp and cur by always pointing at where // the next node is going to go. int n; do { cout << "enter the number of nodes: "; cin >> n; } while (n <= 0); *insert = new node; //node goes right into head cout << "enter the values inside each node: "; cin >> (*insert)->data; insert = &(*insert)->next; // now the insertion point points at head's next for (int i = 1; i < n; i++) { *insert = new node; // new node gets linked right in next cout << "enter a node: "; cin >> (*insert)->data; insert = &(*insert)->next; // advance to next of the node we just added } *insert = NULL; // terminate list by pointing the insertion point at NULL return head; } And now that he have abstracted head into just another insertion point like next, we can eliminate some duplicated code: node* inputList() { node * head; node ** insert = &head; // head is no different from a next. It just // has a different name int n; do { cout << "enter the number of nodes: "; cin >> n; } while (n <= 0); // no special handling for head. for (int i = 0; i < n; i++) { // iteration now starts at 0. The loop // builds all of the nodes. *insert = new node; cout << "enter a node: "; cin >> (*insert)->data; insert = &(*insert)->next; } *insert = NULL; return head; }
71,135,887
71,136,233
Does arithmetic overflow overwrite data?
std::uint8_t x = 256; //Implicitly converts to 0 std::uint8_t y = 255; y++; For x, I assume everything is handled because 100000000 gets converted to 00000000 using some defined conversion from int to uint8_t. x's memory should be 0 00000000 not 1 00000000. However with y I believe the overflow stays in memory. y is initially 11111111. After adding 1, it becomes 1 00000000. This wraps around back to 0 because y only looks at the 8 LSB. Does the 1 after y++; stay in memory, or is it discarded when the addition is done? If it is there, could it corrupt data before y?
Does arithmetic overflow overwrite data? The behaviour of signed arithmetic overflow is undefined. It's neither guaranteed to overwrite data, nor guaranteed to not overwrite data. std::uint8_t y = 255; y++; Unsigned overflow is well defined. y will be 0, and there are no other side-effects. Citation from the C++ standard (latest draft): [basic.fundamental] ... The range of representable values for the unsigned type is 0 to 2N−1 (inclusive); arithmetic for the unsigned type is performed modulo 2N. [Note 2: Unsigned arithmetic does not overflow. Overflow for signed arithmetic yields undefined behavior ([expr.pre]). — end note] [expr.pre] If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. Since unsigned arithmetic is modular, the result can never be outside of representable values.
71,135,955
71,135,986
problem of using const when passing a pointer
Visual studio shows a error saying "the object has type quantifiers that are not compatible with the member function 'somfunc' " class T_ship { public: ... float ship_run(int ship_len); // function ship_run doesn't change any class member values }; There is a function in main() with *T_ship pointer passed as input. void draw_ship(const T_ship * a_shp){ float dist = a_ship-> ship_run(100); // there is a red wavy line under a_ship } Many thanks if someone can help.
If you want the actual pointer to be const and not the object pointed to, put the const in front of the type, so like this: T_ship * const However in your case if the function ship_run doesn't modify anything you should mark it as const at the end of the function as well so like this: float ship_run(int v) const { /* your code here */ }
71,136,128
71,136,224
c++ qt can i fill a QVariant with multiple struct objects
I have the following struct: struct FileInfo { QString fileName; QString fileSize; QString md5Sum; }; is it possible to put approximately 30 such objects into a QVariant and then be able to iterate through the QVariant to retrieve one of the structs based on index and then cast the object back into a struct and query the struct for say fileSize of a specific file? Is there a better approach to my issue?
You can consider QVariantList to store object as QVariant. Of course, you can convert back into your custom struct. Example. struct FileInfo { QString fileName; QString fileSize; QString md5sum; }; int main() { QVariantList variantList; for(int i = 0; i < 30; i++) { FileInfo info{QString("File %1").arg(i), QString("size %1").arg(i), QString("md5sum %1").arg(i)}; QVariant var; var.setValue(info); variantList.append(var); } for (auto v: variantList) { FileInfo f = v.value<FileInfo>(); qDebug() << "File name: " << f.fileName << "\tfile size: " << f.fileSize; } return 0; }
71,136,439
71,137,444
C++ regex_replace not substituting Latex like expression
Looks like regex_replace is only replacing the left parenthesis. And that too is not without a backslash: #include <iostream> #include <regex> #include <string> using namespace std; int main(int argc, char* argv[]) { string text = "\\left( 0 + 1 \\right)"; text = regex_replace(text, regex("\\left\\("), "("); text = regex_replace(text, regex("\\right\\)"), ")"); cout << text; return 0; } The output is: \( 0 + 1 \right) The expected output is: ( 0 + 1 )
It seems \\\\ is required instead of \\. And also for round braces, I used [(] and [)]. #include <iostream> #include <regex> #include <string> using namespace std; int main(int argc, char* argv[]) { string text = "\\left( 0 + 1 \\right)"; text = regex_replace(text, regex("\\\\left[(]"), "("); cout << text << endl; text = regex_replace(text, regex("\\\\right[)]"), ")"); cout << text; return 0; } https://godbolt.org/z/51fhvxYjT
71,136,451
71,136,740
Return value of (std::cin >> variable)
I am a C++ beginner, #include <iostream> int main() { char v1; // valid no warning std::cout << (std::cin >> v1) << std::endl; // return value of the expression expected return 0; } // output: 1 // return value of the expression is 1? Is the return value of (std::cin >> v1) really 1? Why?
I don't know of a current compiler that will accept your code as it stands right now. g++, clang and Microsoft all reject it, saying they can't find an overload to match the arguments (i.e., an operator<< for ostream that takes an istream as an operand). It's possible to get the result you've posited with code on this order: std::cout << !!(std::cin >> v1) << "\n";. Depending on the age of the compiler and standard with which it complies, this does one of two things. With a reasonably current compiler, this will use the Boolean conversion on the istream to get it to match the ! operator, then apply that (twice) to the result, so you write out the result of that operator. With old enough compilers, there won't be a Boolean conversion operator, but there will be an overload of operator!, which also does a conversion to Boolean (but negated in sense, of course). The result of that will then be negated by the second !. Either way, you end up writing out a Boolean value (or int containing zero or one on an old enough compiler) that indicates whether the stream is in a failed or successful state. This is done to allow you to check input as you're reading it, so you can process input data sanely. For example, when/if you want to read all the values in a file, stopping at the end of the file, or when you encounter something that can't be interpreted as the desired type, you can write code on this general order: // read integers from a file and print out their sum int temp; int total = 0; while (std::cin >> temp) { total += temp; } std::cout << total << "\n"; The while loop uses the conversion to Boolean to determine whether an attempt at reading a value was successful or not, so it continues reading values as long as that happens successfully, and quits immediately when reading is unsuccessful. One common source of errors is to write a loop on this order instead: while (std::cin.good()) { // or almost equivalently, check for end of file. std::cin >> temp; total += temp; } But loops like this get the sequence incorrect. One common symptom of the problem with this is that the last number in the file will be added to the total twice instead of once.
71,136,464
71,136,615
why cannot we initialize a node without using a pointer?
I have recently started learning data structure and as a beginner, I have a query while implementing linked list nodes, why do we have to initialize node using a pointer only? class node{ public: int data; node* next; node(int val){ data = val; next = NULL; } }; int main(){ node* head = NULL; node head = NULL; // this throws an error which i cannot understand }
Actually you can initialize the node by value. If you want to initialize a node with value, according to your constructor node(int val), you have to code like below: class node{ public: int data; node* next; explicit node(int val){ data = val; next = NULL; } }; int main(){ int value = 777; //node* head = NULL; // Initialize head pointers to null node head(value); // By your constructor definition } EDIT: By the way, marking a constructor as explicit is a very good habit to have, as it prevents unexpected conversion, as Duthomhas commented.
71,136,617
71,143,165
char passed into function that receives char. yet char& is in error
error: no match for call to ‘(std::_Mem_fn<void (CNC::CGUI::*)(float, char)>) (float, char&)’ void CGUI::null(float numP, char dir){} void CGUI::Function() { auto function_X_axis = std::mem_fn(&CGUI::null); } void Move_X_axis(float numP, char dir){} void CGUI::Function2() { function_X_axis = std::mem_fn(&CGUI::Move_X_axis); char sign = 'e'; function_X_axis(1.0f, sign); } dir and sign, are both char, not char reference. Where did the char reference come from? I am not using templates. i have searched for different parts of the error, but nothing close.
Probably because the argument could be passed as lvalue reference to char. Passing by value would be as good. It doesn't really matter as your problem is lack of the CGUI object: #include <functional> struct CGUI { void null(float, char); }; void CGUI::null(float numP, char dir){} int main() { CGUI gui; auto function_X_axis = std::mem_fn(&CGUI::null); char sign = 'e'; function_X_axis(gui, 1.0f, sign); } Haven't you confused mem_fn with bind or lambda of some sort?
71,136,842
71,146,211
Why unique_ptr's Deleter need an argument of type unique_ptr<T, Deleter>::pointer?
I see the describtion about unique_ptr on cppreference, it says Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of type unique_ptr<T, Deleter>::pointer, I don't understand why there is such a requirement that FunctionObject must have an argument and if I want to implement the requirement,How shoud I do?
That requirement is expressing that unique_ptr more or less looks like this: class unique_ptr { pointer ptr; [[no_unique_address]] deleter_type del; public: /* other members */ ~unique_ptr() { del(ptr); } }; That is, it ensures that the pointed-to value is "freed" when the pointer is destroyed, whatever "freed" means. std::default_delete is similarly more or less: struct default_delete { void operator()(pointer ptr) const { delete ptr; } }; So if you want to write a custom deleter, it should have a member function void operator()(pointer ptr) const, in which you do whatever cleanup.
71,137,509
71,138,045
Unable to overload '[ ]' in here. C++ Noob here
I am trying to implement a linkedlist in C++ and trying to incorporate array like data access using '[]'. First I declared a Node class as the following. class Node{ public: int data; Node *next, *prev; Node(int val){ this -> data = val; this -> next = NULL; this -> prev = NULL; } }; Then I implemented the Linkedlist class as the following where I have overloaded the '[]' operator like the following class LinkedList{ public: Node *head; LinkedList(){ this -> head = NULL; } LinkedList(Node *h){ this -> head = h; } int operator [] (int index){ if(index < 0 || index >= getsize(this -> head)){ cout << "List out of bounds" << endl; return -1; }else{ Node *cur = this -> getnode(index); return cur -> data; } } Node* getnode(int index){ int count = 0; Node *cur = this -> head; while(cur != NULL){ if(count == index) break; count++; cur = cur -> next; } return cur; } }; In the main function I have tried to print the 'l[0]'. It shows error as no operator "<<" matches these operandsC/C++(349) linklist_sort.cpp(173, 10): operand types are: std::ostream << LinkedList Please help me out. Am I missing some concept here ? The main function : int main(){ srand(time(0)); LinkedList *l = new LinkedList(); for(int i = 0; i<10; i++){ int num = rand() % 50 + 1; l -> head = l -> insert(l->head,num); } l->printlist(l->head); int n1, n2; cout << "\n"; cin >> n1 >> n2; l->swap(l->head,n1,n2); l->printlist(l->head); cout << "\n"; cout << l[0]; //Error here return 0; } The getsize function : int getsize(Node *head){ if(head == NULL) return 0; else return 1 + getsize(head->next); }
Since l is a pointer which is created by LinkedList *l = new LinkedList(); it needs to be dereferenced to be able to use operator first. This would solve your problem: cout << (*l)[0]; But I suggest you to not create LinkedList with new keyword so you can avoid using raw pointers and memory leaks in the application code. You could use LinkedList l; instead.
71,137,994
71,138,034
Define a friend function for a static class method?
Does someone know how to let outside world access private static methods? The only way I could think of is via friend function, but that doesn't seem to work. Header file here: #pragma once #include <iostream> class MyClass { public: friend void AtFork(); private: static void Disp() { std::cout << "hello world" << std::endl; } }; impl file here: #include "test.h" namespace { void AtFork() { MyClass::Disp(); } } int main() { AtFork(); } The error message is: test.cc:6:11: error: 'Disp' is a private member of 'MyClass' MyClass::Disp(); ^ ./test.h:10:15: note: declared private here static void Disp() { std::cout << "hello world" << std::endl; } context: to get fork-safe (due to a bunch of legacy code), I have a reinitialize a 3rd library by binding a fork hook, and I don't think it should be exposed to public. For the above example, it's let AtFork being able to call MyClass::Disp.
The issue in your code is the anonymous namespace. The AtFork in main.cpp can only be accessed within main.cpp. The AtFork you declared as friend is a different one. Do not use an anonymous namespace and the code compiles fine: #include <iostream> class MyClass { public: friend void AtFork(); private: static void Disp() { std::cout << "hello world" << std::endl; } }; //namespace { void AtFork() { MyClass::Disp(); } //} int main() { AtFork(); } Though you can place AtFork in a (named) namespace if you like: #include <iostream> namespace foo { void AtFork();} class MyClass { public: friend void foo::AtFork(); private: static void Disp() { std::cout << "hello world" << std::endl; } }; namespace foo{ void AtFork() { MyClass::Disp(); } } int main() { foo::AtFork(); }
71,138,072
71,138,358
FLIPCOIN problem solution using SegmentTree has high runtime
I've been trying to solve the FLIPCOIN question of CodeChef (https://www.codechef.com/problems/FLIPCOIN) but I always received the message Time Limit Exceeded. The input is as follows: First comes a number n, the length of a row of coins, all turned tails up initially, and a number q, the number of tasks. After that follow q tasks: updates, which have the form 0 A B and and should flip all coins in the range (inclusive) from A to B, and queries of the form 1 A B, where one should ouput the number of coins turned heads in the range from A to B. I've already seen some solutions but I still don't know what is the problem with my code, is it because of the class? I would like to know why my code is so slow. #include <bits/stdc++.h> #include <iostream> #include <vector> class SegmentTree{ int leftmost,rightmost,n_heads; SegmentTree* leftChild; SegmentTree* rightChild; public: SegmentTree(int x,int y, std::vector<int> arr){ leftmost=x; rightmost=y; if(leftmost==rightmost){ n_heads=arr[leftmost]; } else{ int mid=(leftmost+rightmost)/2; leftChild=new SegmentTree(leftmost, mid, arr); rightChild=new SegmentTree(mid+1, rightmost, arr); recalc(); } } void recalc(){ if(leftmost==rightmost) return; n_heads=leftChild->n_heads+rightChild->n_heads; } void rangeUpdate(int left,int right){ if(left>rightmost||right<leftmost) return; if(leftmost==rightmost){ if(n_heads){ n_heads=0; } else{ n_heads=1; } return; } leftChild->rangeUpdate(left, right); rightChild->rangeUpdate(left, right); recalc(); } int rangeSum(int l,int r){ if(l>rightmost||r<leftmost) return 0; if(l<=leftmost&&r>=rightmost) return n_heads; return leftChild->rangeSum(l, r)+rightChild->rangeSum(l, r); } }; int main(){ int n, q; std::cin>>n>>q; std::vector<int> vec(n); fill(vec.begin(), vec.end(), 0); SegmentTree st=SegmentTree(0,n-1,vec); while(q--){ int a, l, r; std::cin>>a>>l>>r; if(!a) st.rangeUpdate(l,r); if(a) std::cout<<st.rangeSum(l,r)<<std::endl; } return 0; }
The reason why your code is slow is that while your range queries take logarithmic time, your range updates take linear time. When updating a range of length n, you don't want to look at all n elements in that range. Instead, you want to make your updates lazy. What does that mean? If the range of a SegTree node is fully inside you queried range (left <= leftmost && rightmost <= right), you can just remember that you will need to update the coins in that range and recalculate the number of coins turned to heads (n_heads = rightmost - leftmost + 1 - n_heads) after the flip, but don't actually do anything else (especially not doing a recursive call) Now when do you do the update? Always before doing a recursive call to the children, you will need to push the stored update in the current node to them. You can do this with an apply() method (this will flip all the coins in a SegTree node) and a push() method, which will apply a lazy update, if we need one. This will reduce your runtime for a query from O(n) to O(log n) So you need to do the following. add a bool update = false field to your SegTree add an apply and a push method void apply() { // flip all coins in this range n_heads = rightmost - leftmost + 1 - n_heads; // if we did not need to update our children before, now we do // if however we did, then flipping again just undos that update, so just do no update at all update = !update; } void push() { if (!update) return; leftChild->apply(); rightChild->apply(); // update done update = false; } update your update and query methods do call push before doing recursive calls (and reuse the apply function for applying updates) void rangeUpdate(int left,int right){ if(left>rightmost||right<leftmost) return; if(left<=leftmost&&rightmost<=right) { apply(); return; } // IMPORTANT: push possible lazy update to children before updating them push(); leftChild->rangeUpdate(left, right); rightChild->rangeUpdate(left, right); recalc(); } int rangeSum(int l,int r){ if(l>rightmost||r<leftmost) return 0; if(l<=leftmost&&rightmost<=r) return n_heads; // IMPORTANT: push possible lazy update to children before querying push(); return leftChild->rangeSum(l, r)+rightChild->rangeSum(l, r); } Thats it! Further improvements would be to not use individual nodes but the array representation of a binary tree (https://www.geeksforgeeks.org/binary-tree-array-implementation/) and (as has already been said) passing the vector by reference instead of by value
71,138,247
71,138,563
Can we have multiple c files to define functions for one header file?
Newbie to C and C++. I have one .h file in which some functions are declared. I'm trying to implement the functions in two separate .c files, but when compiling I got a linker error. Is it not allowed?
Yes it is allowed. Here is a very simple example: foobar.h: declares foo and bar void foo(void); void bar(void); foo.c: implements foo #include <stdio.h> #include "foobar.h" void foo(void) { printf("foo\n"); } bar.c: implements bar #include <stdio.h> #include "foobar.h" void bar(void) { printf("bar\n"); } main.c: uses foo and bar #include <stdio.h> #include "foobar.h" int main(void) { foo(); bar(); return 0; } Compiling, linking and running with gcc: $ gcc foo.c $ gcc bar.c $ gcc main.c $ gcc -o someprog foo.o bar.o main.o $ ./someprog foo bar $ or $ gcc -o someprog foo.c bar.c main.c $ ./someprog foo bar $
71,138,291
71,138,732
`std::cout << FooStuff::Foo();` chooses completely unrelated overload instead of exactly matching one
I have this code: #include <iostream> namespace FooStuff { struct Foo { }; } decltype(std::cout)& operator << (decltype(std::cout)& left, const FooStuff::Foo& right) { return left; } void test1() { // This works fine std::cout << FooStuff::Foo(); } As far as I can tell, this is the best operator << that one could possibly write down to match the call in test1, and it works as you would expect. Now add this code below the code above: namespace BarStuff { struct Bar { }; // Danger zone void test2() { // This works too, for now std::cout << FooStuff::Foo(); } } The call in test2 works too, as you would expect. But if I insert the following operator right below the "Danger zone" comment, everything breaks: Bar operator << (Bar left, Bar right) { return left; } Now the call in test2 won't compile because the compiler chooses the completely inappropriate overload that takes a bunch of Bars, even though the operator from the first snippet should be a perfect match: main.cpp:33: error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'FooStuff::Foo') (A ton of unrelated overloads omitted for brevity) main.cpp:25: candidate function not viable: no known conversion from 'std::ostream' (aka 'basic_ostream<char>') to 'BarStuff::Bar' for 1st argument What the poop is going on? Why does the compiler choose that overload instead of the one I want it to choose? And why does the error disappear, if Foo is moved outside FooStuff?
When you write std::cout << FooStuff::Foo(); name lookup is done to determine the candidates for << to use in overload resolution. For overload resolution of operators there are two parts to this lookup: unqualified name lookup of operator<< and argument-dependent lookup of operator<<. For unqualified name lookup, as is always the case, lookup traverses from inner to outer scope and stops as soon as a match is found. So if you put an overload at // Danger zone, the one outside BarStuff will be hidden. For argument-dependent name lookup, all overloads in the class types of the operands and their immediately enclosing namespace will be considered. In your case that means that overloads inside struct Foo and namespace FooStuff will be found as well, no matter where the std::cout << FooStuff::Foo(); is placed. For the above reasons, operator overloads should be placed in the namespace containing the class for which they overload the operator. This assures that the overload is always found via argument-dependent lookup.
71,138,329
71,138,572
std::initializer_list and std::make_shared: too many arguments ... 3 expected 0 provided
I am not really getting any smarter from these error messages. Minimal (not) Working Example on godbolt #include <initializer_list> #include <memory> #include <vector> struct S { int j; double y; std::vector<int> data; S(int i, double x, std::initializer_list<int> list) : j(i) , y(x) , data(list) { } }; int main() { auto ptr = std::make_shared<S>(1, 1.2, {1,2,3}); // I want this to work // auto ptr = std::make_shared<S>(1, 1.2, std::initializer_list<int>({1,2,3})); // works } Errors: <source>:22:35: error: too many arguments to function 'std::shared_ptr<_Tp> std::make_shared(_Args&& ...) [with _Tp = S; _Args = {}]' 22 | auto ptr = std::make_shared<S>(1, 1.2, {1,2,3}); <source>:11:5: note: candidate: 'S::S(int, double, std::initializer_list<int>)' 11 | S(int i, double x, std::initializer_list<int> list) | ^ <source>:11:5: note: candidate expects 3 arguments, 0 provided It compiles fine, when I call the explicit constructor for std::initializer_list<int> in front of {1,2,3}. Is there a way to circumvent this, so my std::make_shared does not bloat so much?
{1,2,3} can be multiple things, and make_shared has no possibility of knowing what it is at the time parameter pack is expanded. If you don't want to state the long std::initializer_list<int>{1,2,3} explicitly, the easiest solutions would be: a. shortening the type's name: using ints=std::initializer_list<int>; b. wrapping the call: auto make_shared_S(int x, double y, std::initializer_list<int> l) { return std::make_shared<S>(x, y, l); } Demo: https://godbolt.org/z/WErz87Ks4
71,138,600
71,139,766
Permutations of an int array, using recursion
Exercise is as follows: Generate every possible sequence whose elements are from the set {0, 1, 2} where 0 occurs m times, 1 occurs p times, and 2 occurs q times. The input file contains three natural numbers separated by spaces, with a maximum value of 100. The solution must be written to the output file line by line in lexicographic order. Each line should contain the elements of the series separated by spaces. If input is: 1 0 2 Output should be: 0 2 2 2 0 2 2 2 0 It's also stated, that I have to use recursion, and the input and output should be to .txt files. So, I found a popular recursion for permutations which occurred on multiple sites (like this), but for some weird reason, it's not working properly for me.. The way I tried doing this exercise (there might be a smarter way) is by generating a vector from the input, and the using the permutation function with it. But my output is like this: 0 2 2 0 2 2 2 0 2 2 2 0 2 2 0 2 0 2 As you can see, every result appears twice, which is obviously not good.. Code is here below: #include <iostream> #include <vector> #include <fstream> using namespace std; void input(int& m, int& p, int& q) { ifstream fin("input.txt"); fin >> m >> p >> q; fin.close(); } void fillVec(vector <int>& elements, int m, int p, int q) { fill_n(elements.begin() + m, p, 1); // filling the vectors with correct amount of numbers. The 0's all already there, so I only put the 1's, and the 2's in. fill_n(elements.begin() + m + p, q, 2); } void print(const vector<int>& nums, ofstream& fout) { for (int a : nums) { fout << a << ' '; } fout << endl; } void permute(vector<int>& nums, int n, ofstream& fout) { if (n == nums.size()) { print(nums, fout); } else { for (int i = n; i < nums.size(); i++) { swap(nums[n], nums[i]); permute(nums, n + 1, fout); swap(nums[n], nums[i]); } } } int main() { int m, p, q; input(m, p, q); vector <int> elements(m + p + q); fillVec(elements, m, p, q); ofstream fout("output.txt"); permute(elements, 0, fout); fout.close(); return 0; } I tried debugging, also looked at it multiple times to check that I copied the algorithm correctly, but can't find out what's the problem. It might be something pretty simple, I'm not sure..
Here's what I came up with. Each recursive step will attempt to append "0", "1", or "2" to the string being built until there's no available digits to add. #include <iostream> #include <string> using namespace std; void GeneratePermutations(int zeros, int ones, int twos, const string& leading) { if ((zeros <= 0) && (ones <= 0) && (twos <= 0)) { // use "substr" to skip the leading space if (leading.size() > 0) { std::cout << leading.substr(1) << endl; } return; } if (zeros > 0) { GeneratePermutations(zeros - 1, ones, twos, leading + " 0"); } if (ones > 0) { GeneratePermutations(zeros, ones-1, twos, leading + " 1"); } if (twos > 0) { GeneratePermutations(zeros, ones, twos-1, leading + " 2"); } } int main() { int zeros, ones, twos; cin >> zeros; cin >> ones; cin >> twos; GeneratePermutations(zeros, ones, twos, ""); return 0; } A couple of sample runs: input : 1 0 2 output: 0 2 2 2 0 2 2 2 0 Another input: 3 1 1 output: 0 0 0 1 2 0 0 0 2 1 0 0 1 0 2 0 0 1 2 0 0 0 2 0 1 0 0 2 1 0 0 1 0 0 2 0 1 0 2 0 0 1 2 0 0 0 2 0 0 1 0 2 0 1 0 0 2 1 0 0 1 0 0 0 2 1 0 0 2 0 1 0 2 0 0 1 2 0 0 0 2 0 0 0 1 2 0 0 1 0 2 0 1 0 0 2 1 0 0 0
71,138,955
71,140,203
C++ alternative to singleton design when a function-only class needs to be initialize at least once?
#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <random> #include <map> #include <math.h> #include <cstring> using namespace std; class MathClass { private: size_t current_capacity; double* logfact; bool inited = false; MathClass() { current_capacity = 0; logfact = new double[1]; logfact[0] = 0; } void calculateLogFact(int n) { if (current_capacity >= n) return; double* newLogfact = new double[n+1]; for (int i=0; i<=current_capacity; i++) newLogfact[i] = logfact[i]; for (int i=current_capacity+1; i<=n; i++) newLogfact[i] = newLogfact[i-1] + log(double(i)); delete[] logfact; logfact = newLogfact; } double factorial(int n) { cout << "n = " << n << "\n"; calculateLogFact(n); for (int i=0; i<=n; i++) cout << int64_t(round(exp(logfact[i]))) << " "; cout << "\n"; return exp(logfact[n]); } public: static double factorial2n(int n) { static MathClass singleton; return singleton.factorial(2*n); } }; int main(int argc, char** argv) { cout << MathClass::factorial2n(10) << "\n"; return 0; } My library need to use an expensive function that needs to be initialized once before use (to pre-calculate some expensive values so that we don't have to calculate them every time). Currently, I use the singleton method above for this. However, there are 2 problems: Multi-threading: this will cause race conditions if 2 different threads call this function. People don't like singleton Other problems that I'm not aware of What other design can I use to solve this problem? Pre-computing values is a must since this function needs to be fast.
I agree with comments: Why hide the fact that MathClass caches results from the user? I, as a potential user, see no real benefit, rather potential confusion. If I want to reuse previously cached results stored in an instance I can do that. You need not wrap the whole class in a singleton for me to enable that. Also there is no need to manually manage a dynamic array when you can use std::vector. In short: The alternative to using a singleton is to not use a singleton. #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <random> #include <map> #include <math.h> #include <cstring> using namespace std; class MathClass { private: size_t current_capacity; std::vector<double> logfact; bool inited = false; void calculateLogFact(int n) { if (logfact.size() >= n) return; auto old_size= logfact.size(); logfact.resize(n); for (int i=old_size; i<n; i++) logfact.push_back(logfact.back() + log(double(i))); } double factorial(int n) { cout << "n = " << n << "\n"; calculateLogFact(n); for (int i=0; i<=n; i++) cout << int64_t(round(exp(logfact[i]))) << " "; cout << "\n"; return exp(logfact[n]); } public: MathClass() { logfact.push_back(0); } double factorial2n(int n) { return factorial(2*n); } }; void foo(MathClass& mc) { // some function using previously calculated results std::cout << mc.factorial2n(2); } int main(int argc, char** argv) { MathClass mc; cout << mc.factorial2n(10) << "\n"; foo(mc); } I am not sure if the maths is correct, I didn't bother to check. Also inited and most of the includes seem to be unused. Concerning "Multi-threading: this will cause race conditions if 2 different threads call this function." I would also not bother too much to bake the thread-safety into the type itself. When I want to use it single-threaded I do not need thread-safety, and I don't want to pay for it. When I want to use it multi-threaded, I can do that by using my own std::mutex to protect access to the mc instance. PS: Frankly, I think the whole issue is caused by a misconception. Your MathClass is not a "function only" class. It is a class with state and member functions, just like any other class too. The "misconception" is to hide the state from the user and pretend that there is no state when in fact there is state. When using this class I would want to be in conctrol what results I can query because they are already cached and which results need to be computed first. In other words, I would provide more access to the class state, rather than less.
71,139,220
71,140,583
How can ignore bazel features like `treat_warnings_as_errors` only on some files?
I have a library like the following in my bazel build file for C++: cc_library( name = "mylib", srcs = [ "main.cpp", "file1.cpp", "file2.cpp", ... ], hdrs = [ "main.h", "file1.h", "file2.h", ... ], features = [ "treat_warnings_as_errors", "strict_warnings", "additional_warnings", ], deps = [ "my_dependency1", "my_dependency2", "third_party_dependency", ... ], ) I need the constraints specified in features to be applied to all source files, except to third_party_dependency which is used by file1. What I tried was removing file1 from mylib, putting it in a new library (i.e. mylib2) and then adding that lib to mylib as a dependency. The only problem is that I don't want the whole file1 to scape from the constraints, only third_party_dependency. Is there any way to do that?
My solution for this was creating a new library as a wrapper for third_party_dependency not to mess up with third party code and on that second library I just had to add #pragma GCC system_header on the header file so that my gcc compiler ignores that file. redits for How to eliminate external lib/third party warnings in GCC
71,139,251
71,142,509
How to add a server certificate to WebView2
Assume we are going to visit the website that is only known by our little circle, and we want to protect the connections so HTTPS will be used. Because this is a small circle, we don't want to send a X.509 request to a CA and wait for the certificate. We want to use a self-signed X.509 certificate. Now, the problem is how to add our self-signed X.509 certificate to WebView2 ecosystem, so that the embedded browser is able to visit the website? Thanks.
WebView2 uses the computer's certificate store, just like the Edge browser. So you simply install your self-signed certificate in the certificate store, under 'Trusted root certificates'. Now the computer accepts the certificate and so will WebView2. Actually I recommend you create two certificates, on root certificate, which can only be used for signing (That's the one you install in 'Root certificate store'), and then you use that certificate to sign your server certificate, which you install on the web server. Since this certificate is signed by a trusted certificate, the browser/WebView2 will accept it. The root certificate must be installed on all computers, where you use WebView2. The server cerficate should only be installed on your server.
71,140,123
71,140,446
How to inherit from an abstract class properly in C++?
I couldn't find a proper topic for this question as I haven't got a proper error message. I'm trying to create a management system for a restaurant which mainly provides pizza as well as other foods(pasta, wings, etc). I want this system to be used by the staff. I have created an abstract class named Foods that can be used to inherit by other foods. So far I have created a class that inherits from Foods named Pizza. Below are my code. PS: I have used namespaces for organize foods and staff members separately. As far as I know some people doesn't recommend namespace and my apologies if you're one of them. interfaces.h #include <vector> #include <string> namespace foods{ class Food{ double price; // since the sauces and drinks are given with foods. static const std::vector<std::string> sauces; static const std::vector<std::string> drinks; public: virtual int retPrice() = 0; virtual void ask() = 0; // ask user what to add virtual ~Food() = default; }; const std::vector<std::string> Food::sauces = {"Blue cheese", "Garlic", "Honey BBQ", "Marinara"}; const std::vector<std::string> Food::drinks = {"Pepsi", "Mountain Dew", "Coca Cola"}; class Pizza: public Food{ const double price; const std::string pizzaType; // whether it is chicken, beef, etc. const std::string size; // small, medium or large int crust = 1; // how crust it is from 1-5 std::vector<std::string> toppings; // to store toppings public: Pizza(): price(15), pizzaType(" "), size(" "){} int retPrice() override; // the price should change according to the type void ask() override; // ask the customer for a pizza void createACustom(); // create a custom pizza with desired toppings }; }; functions.cpp #include <iostream> #include "interfaces.h" namespace foods{ int Pizza::retPrice(){ return (price+5); } void Pizza::ask(){ std::cout << "Hello World!"; } } test.cpp #include "interfaces.h" int main(){ foods::Pizza* pizza = new foods::Pizza(); } And I'm getting following error. /usr/bin/ld: /tmp/ccQRR5B8.o: warning: relocation against `_ZTVN5foods5PizzaE' in read-only section `.text._ZN5foods5PizzaC2Ev[_ZN5foods5PizzaC5Ev]' /usr/bin/ld: /tmp/ccQRR5B8.o: in function `foods::Pizza::Pizza()': test.cpp:(.text._ZN5foods5PizzaC2Ev[_ZN5foods5PizzaC5Ev]+0x2b): undefined reference to `vtable for foods::Pizza' /usr/bin/ld: warning: creating DT_TEXTREL in a PIE collect2: error: ld returned 1 exit status I tried using the keyword override and also made a default deconstructor, yet nothing seems working. I want to know what this error message means and a solution for this. In addition to that what is vtable? Appreciate your time and answers. EDIT 1 I have compiled it with g++ -Wall -Wextra test.cpp functions.cpp -o test, which is wrong and then I did g++ -Wall -Wextra test.cpp functions.cpp -o test and I'm getting following error. /usr/bin/ld: /tmp/ccmv2G17.o:(.bss+0x0): multiple definition of `foods::Food::sauces[abi:cxx11]'; /tmp/ccuBNQjX.o:(.bss+0x0): first defined here /usr/bin/ld: /tmp/ccmv2G17.o:(.bss+0x20): multiple definition of `foods::Food::drinks[abi:cxx11]'; /tmp/ccuBNQjX.o:(.bss+0x20): first defined here collect2: error: ld returned 1 exit status Why is it saying that it has multiple definitions?
You need to implement the static member variables sauces and drinks in functions.cpp and not in interfaces.h. functions.cpp namespace foods { int Pizza::retPrice() { return (price + 5); } void Pizza::ask() { std::cout << "Hello World!"; } // implement the static variables here. const std::vector<std::string> Food::sauces = { "Blue cheese", "Garlic", "Honey BBQ", "Marinara" }; const std::vector<std::string> Food::drinks = { "Pepsi", "Mountain Dew", "Coca Cola" }; } And remove them from interfaces.h. If you implement them in interfaces.h they end up being implemented in each .cpp file that includes interfaces.h. It's basically the same problem as if you define a global variable in a .h file.
71,141,181
71,152,194
Fetch SCT list from x509 certificate
How can I fetch this SCT list from PCCERT_CONTEXT? Is there any straightforward win API?
With the following code snippet, I could able to fetch the SCT list as a string from X509 certificate std::wstring GetSCTString(PCCERT_CONTEXT certInfo) { PCERT_EXTENSION ext; ext = CertFindExtension(szOID_CT_CERT_SCTLIST, certInfo->pCertInfo->cExtension, certInfo->pCertInfo->rgExtension); if (NULL != ext) { DWORD strSz(0); if (CryptFormatObject(X509_ASN_ENCODING, 0, 0, NULL, szOID_CT_CERT_SCTLIST, ext->Value.pbData, ext->Value.cbData, NULL, &strSz)) { std::wstring Buff; Buff.resize((strSz / sizeof(wchar_t)) + 1); if (CryptFormatObject(X509_ASN_ENCODING, 0, 0, NULL, szOID_CT_CERT_SCTLIST, ext->Value.pbData, ext->Value.cbData, (void*)Buff.data(), &strSz)) { return Buff; } } } return std::wstring(); }
71,141,631
71,142,317
Initializing Texture2DArray
I'm trying to create and initialize a 2D texture array in the following way: D3D11_TEXTURE2D_DESC desc{}; desc.ArraySize = 10; // there should be 10 textures desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; desc.Usage = D3D11_USAGE_DEFAULT; desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; desc.Width = 256; desc.Height = 1; desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA subresourceData{}; subresourceData.pSysMem = data.data(); // data is a vector of 2560 elements of type XMVECTOR subresourceData.SysMemPitch = 256 * sizeof(XMVECTOR); subresourceData.SysMemSlicePitch = 256 * sizeof(XMVECTOR); Microsoft::WRL::ComPtr<ID3D11Texture2D> m_texture = nullptr; m_device->CreateTexture2D(&desc, &subresourceData, &m_texture); The problem is I'm getting an error Access violation reading location 0xFFFFFFFFFFFFFFFF on calling CreateTexture2D and m_texture in NULL. When I did not pass initialization data the problem did not occur: m_device->CreateTexture2D(&desc, nullptr, &m_texture); How can I initialize a texture array?
Problem solved: for texture array you have to pass an array of D3D11_SUBRESOURCE_DATA in CreateTexture2D function.
71,141,761
71,143,147
Reading a .dat File in C++ gives Symbols instead of Numbers
I am trying to open a .dat binary file in C++ as an exercise, however when I try to print out the contents of the file, I receive symbols instead of numbers. Here is the code on how I read the .dat file: int main() { errno_t status; std::FILE *input_file; status = fopen_s(&input_file, filename, "rb"); if (status == 0) { std::string content; std::fseek(input_file, 0, SEEK_END); content.resize(std::ftell(input_file)); std::rewind(input_file); std::fread(&content[0], 1, content.size(), input_file); std::fclose(input_file); for (int i = 0; i < 10; i++) { std::cout << content[i]; } } return 0; } I also tried it using C++ fstream. int main() { std::ifstream input_file(filename, std::ios::in | std::ios::binary); if (input_file) { std::string content; input_file.seekg(0, std::ios::end); content.resize(input_file.tellg()); input_file.seekg(0, std::ios::beg); input_file.read(&content[0], contents.size()); input_file.close(); for (int i = 0; i < 10; i++) { std::cout << content[i]; } } return 0; } When I try to print the content of content, it returns ⁿ\|Cⁿ\|Cⁿ\ (for the first 10 elements), which corresponds to the first 10 bytes of the file: fc 5c 7c 43 fc 5c 7c 43 fc 5c (according to a Hex Editor). I could easily open the file in Python by using data = numpy.fromfile(filename, "=f") and returns the following (which I expect), array([252.36322, 252.36322, 252.36322, ..., 239.38304, 239.38304, 239.38304], dtype=float32) I also looked into the number of bytes each element should have using Python, and it returned 4, which matches with the output of std::ftell(input_file) (the file should have 36 million points), but I tried changing 1 to 4 in the line std::fread(&content[0], 1, content.size(), input_file); and it returns an empty content. Also, as far as I know, the file doesn't contain any headers, so I think the data should begin at the very first bit. So, how could I open and read the .dat file in C++ so that it returns the same value as Python? Thank you in advance.
The loop for (int i = 0; i < 10; i++) { std::cout << content[i]; } is printing the data by interpreting the data as representing the character codes of invidual characters. However, this is not what the data represents. The data actually represents single-precision floating-point numbers. Therefore, you should interpret it as such: for (int i = 0; i < 10; i++) { float f; std::memcpy( &f, content.data() + i * sizeof f, sizeof f ); std::cout << f << '\n'; } Note that you must #include <cstring> in order to use std::memcpy.
71,142,195
71,198,789
can i speed up more than _mm256_i32gather_epi32
I made a gamma conversion code for 4k video /** gamma0 input range : 0 ~ 1,023 output range : 0 ~ ? */ v00 = _mm256_unpacklo_epi16(v0, _mm256_setzero_si256()); v01 = _mm256_unpackhi_epi16(v0, _mm256_setzero_si256()); v10 = _mm256_unpacklo_epi16(v1, _mm256_setzero_si256()); v11 = _mm256_unpackhi_epi16(v1, _mm256_setzero_si256()); v20 = _mm256_unpacklo_epi16(v2, _mm256_setzero_si256()); v21 = _mm256_unpackhi_epi16(v2, _mm256_setzero_si256()); v00 = _mm256_i32gather_epi32(csv->gamma0LUT, v00, 4); v01 = _mm256_i32gather_epi32(csv->gamma0LUT, v01, 4); v10 = _mm256_i32gather_epi32(csv->gamma0LUTc, v10, 4); v11 = _mm256_i32gather_epi32(csv->gamma0LUTc, v11, 4); v20 = _mm256_i32gather_epi32(csv->gamma0LUTc, v20, 4); v21 = _mm256_i32gather_epi32(csv->gamma0LUTc, v21, 4); I want to implement a "10-bit input to 10~13bit output" LUT(look-up table), but only 32-bit commands are supported by AVX2. So, it was unavoidably extended to 32bit and implemented using the _mm256_i32gather_epi32 command. The performance bottleneck in this area is the most severe, is there any way to improve this?
Since the context of your question is still a bit vague for me, just some general ideas you could try (some may be just slightly better or even worse compared to what you have at the moment, all code below is untested): LUT with 16 bit values using _mm256_i32gather_epi32 Even though it loads 32bit values, you can still use a multiplier of 2 as last argument of _mm256_i32gather_epi32. You should make sure that 2 bytes before and after your LUT are readable. static const int16_t LUT[1024+2] = { 0, val0, val1, ..., val1022, val1023, 0}; __m256i high_idx = _mm256_srli_epi32(v, 16); __m256i low_idx = _mm256_blend_epi16(v, _mm256_setzero_si256(), 0xAA); __m256i high_val = _mm256_i32gather_epi32((int const*)(LUT+0), high_idx, 2); __m256i low_val = _mm256_i32gather_epi32((int const*)(LUT+1), low_idx, 2); __m256i values = _mm256_blend_epi16(low_val, high_val, 0xAA); Join two values into one LUT-entry For small-ish LUTs, you could calculate an index from two neighboring indexes as (idx_hi << 10) + idx_low and look up the corresponding tuple directly. However, instead of 2KiB you would have a 4 MiB LUT in your case, which likely hurts caching -- but you only have half the number of gather instructions. Polynomial approximation Mathematically, all continuous functions on a finite interval can be approximated by a polynomial. You could either convert your values to float evaluate the polynomial and convert it back, or do it directly with fixed-point multiplications (note that _mm256_mulhi_epi16/_mm256_mulhi_epu16 compute (a * b) >> 16, which is convenient if one factor is actually in [0, 1). 8 bit, 16 entry LUT with linear interpolation SSE/AVX2 provides a pshufb instruction which can be used as a 8bit LUT with 16 entries (and an implicit 0 entry). Proof-of-concept implementation: __m256i idx = _mm256_srli_epi16(v, 6); // shift highest 4 bits to the right idx = _mm256_mullo_epi16(idx, _mm256_set1_epi16(0x0101)); // duplicate idx, maybe _mm256_shuffle_epi8 is better? idx = _mm256_sub_epi8(idx, _mm256_set1_epi16(0x0001)); // subtract 1 from lower idx, 0 is mapped to 0xff __m256i lut_vals = _mm256_shuffle_epi8(LUT, idx); // implicitly: LUT[-1] = 0 // get fractional part of input value: __m256i dv = _mm256_and_si256(v, _mm256_set1_epi8(0x3f)); // lowest 6 bits dv = _mm256_mullo_epi16(dv, _mm256_set1_epi16(0xff01)); // dv = [-dv, dv] dv = _mm256_add_epi8(dv, _mm256_set1_epi16(0x4000)); // dv = [0x40-(v&0x3f), (v&0x3f)]; __m256i res = _mm256_maddubs_epi16(lut_vals, dv); // switch order depending on whether LUT values are (un)signed. // probably shift res to the right, depending on the scale of your LUT values You could also combine this with first doing a linear or quadratic approximation and just calculating the difference to your target function.
71,142,279
71,142,577
What's the difference between two QHeaderView signals?
On Qt doc website in QHeaderView class i found two signals with similar descriptions: void QHeaderView::sectionDoubleClicked(int logicalIndex) and void QHeaderView::sectionHandleDoubleClicked(int logicalIndex) what's the difference between the two of these? When should I use the first, and when the other?
Although the documentation strings are exactly the same, void QHeaderView::sectionDoubleClicked(int logicalIndex) This signal is emitted when a section is double-clicked. The section's logical index is specified by logicalIndex. [signal]void QHeaderView::sectionHandleDoubleClicked(int logicalIndex) This signal is emitted when a section is double-clicked. The section's logical index is specified by logicalIndex. The signals are emitted in different cases. From KDE's copy of Qt5, void QHeaderView::mouseDoubleClickEvent(QMouseEvent *e) { ... int handle = d->sectionHandleAt(pos); if (handle > -1 && sectionResizeMode(handle) == Interactive) { emit sectionHandleDoubleClicked(handle); ... } else { emit sectionDoubleClicked(logicalIndexAt(e->position().toPoint())); } } The documentation doesn't make it particularly clear, though, when "handles" might be present and when they aren't. At a guess, if your sections are resizable you may get a handle -- for resizing -- and then you can (double) click on either the handle or the section-body.
71,142,385
71,142,540
Is it possible to pass static function as template argument without adding new function argument?
One can pass callback to other function using template to abstract from real callback type: float foo(int x, int y) {return x*y;} template<class F> void call_it(F f, int a, int b) { f(a,b); } There is a cost of passing f as an argument and calling it indirectly. I wonder if, in case f is a static function it is possible to pass it somehow to template function "directly", without adding a callable to the function argument list, so that the call could be bound statically. I see the analogy to passing an integer value as template argument. It doesn't require adding any new function arguments because it passes the integer just as immediate value into the function code: template<int X> int foo(int y) {return X+y;} Here is a non-working code presenting what I'd like to achieve: template<class F> void call_it(int a, int b) { F(a,b); // Assume that F is a static function and can be called directly } Is there any way to achieve it?
You can use a non-type template parameter. To still allow all kinds of callables you can use auto: #include <iostream> struct foo { static float bar(int a,int b){ std::cout << "foo: " << a << " " << b; return a + b; } }; template <auto f> float call_it(int a,int b){ return f(a,b); } int main() { call_it<&foo::bar>(1,2); } or without auto: template <float (*f)(int,int)> float call_it(int a,int b){ return f(a,b); }
71,142,574
71,231,921
confusion with cppyy for overloaded methods and error handling
I have a c++ class with several constructors: MyClass(const std::string& configfilename); MyClass(const MyClass& other); I have python bindings for this class that were generated with cppyy - I don't do this myself, this is all part of the framework I'm using (CERN ROOT, in case you're wondering). Now, I have a piece of python code that instantiates my class, with a nice try-except block: try: obj = MyClass(args.config) except ConfigFileNotFoundError: print("config file "+args.config+" was not found!") exit(0) Now, to test, I'm executing this with a wrong config file. But what I get is roughly this: TypeError: none of the 2 overloaded methods succeeded. Full details: MyClass(const std::string&) => ConfigFileNotFoundError MyClass::MyClass(const MyClass&) => TypeError So I'm wondering: Since cppyy seems to handle function overloading with a try/except block, is there any reasonable way to do error handling for such applications? I'd love to actually get the ConfigFileNotFoundError to handle it properly, rather than getting this TypeError. Also, what determines the actual error class I get in the end - does it depend on the order in which the overloads appear in the header file? Any help, suggestions or pointers on where to find more information on this would be highly appreciated.
cppyy doesn't use try/except for overload resolution, hence there are also no __context__ and __cause__ set. To be more precise: the C++ exception is not an error that occurs during a handler. Rather, as-yet unresolved overloads are prioritized, then tried in order, with no distinction made between a Python failure (e.g. from an argument conversion) or a C++ failure (any exception that was automatically converted into a Python exception). This is a historic artifact predating run-time template instantiation and SFINAE: it allowed for more detailed run-time type matching in pre-instantiated templates. If all overloads fail (Python or C++), the collected errors are summarized. Python still requires an exception type, however, and if the exception types across the collected types differ, a generic TypeError is raised, with a message string made up of all the collected exceptions. This is what happens here: there is ConfigFileNotFoundError raised by C++ in one overload and TypeError from argument conversion failure in the other. There's an improvement now in the cppyy repo; to be released with 2.3.0, where in clear cases such as this one (a single overload succeeding in argument match but failing in the callee), you'll get the actual ConfigFileNotFoundError instance as long as its class is publicly derived from std::exception (but I think it already does, otherwise the error report you posted would have looked quite different). (Note that CERN's ROOT contains an old fork of cppyy that has quite a bit diverged; you'll have to request them for a separate update there if that fork matters to you.)
71,142,707
71,142,964
Calling undeclared function template from inside another function template
I am learning about templates in C++ and so trying out different examples. One such example whose output i am unable to understand is given below: template<typename T> void func(T p) { g<T>(p); //ERROR g(p); //NO ERROR? } int main() { } When i try to compile the above code snippet, i get error saying: prog.cc: In function 'void func(T)': prog.cc:2:1: error: 'g' was not declared in this scope 2 | g<T>(p); //ERROR | ^ prog.cc:2:4: error: expected primary-expression before '>' token 2 | g<T>(p); //ERROR | ^ My questions are: Why i am getting this error? Why i am getting the error only for the statement g<T>(p); and not for g(p);? I thought that writing g(p); is equivalent to g<T>(p); since due to template argument deduction the template parameter for g will be deduced to T.
Case 1 Here we consider the statement: g<T>(p); template<typename T> void func(T p) { g<T>(p); //ERROR } int main() { } In the above code snippet the name g is a unqualified dependent name. And from source: two phase lookup: During the first phase, while parsing a template unqualified dependent names are looked up using the ordinary lookup rules. For unqualified dependent names, the initial ordinary lookup—while not complete—is used to decide whether the name is a template. Now lets apply this to the statement g<T>(p);. When parsing the function template func, the statement g<T>(p); is encountered. Since g is a dependent qualified name, according to the above quoted statement, the name g is looked up using ordinary lookup rules. This is so that the compiler can decide whether the name g is a template. But since there is no declaration for a function template named g before this point, the first angle bracket < is treated as a less than symbol and hence produces the error you mentioned. Also, note that ADL is done in second phase. But for that to happen we must first successfully parse the generic definition of function func.[source: C++ Templates: The Complete guide: Page 250 second last paragraph] Note that compilers are allowed to delay error until instantiation which is why some compilers compiles your code without any error. Demo. Case 2 Here we consider the statement g(p);. template<typename T> void func(T p) { g(p); // NO ERROR } int main() { } In this case also, the name g is an unqualified dependent name. So according to the quoted statement from the beginning of my answer, the name g is looked up using ordinary lookup rules. But since there is no g visible at this point we have an error. There are two things to note here: Since this time you have not explicitly(by using the angle brackets) called g, there is no syntax error. And since there are no syntax error in this case and there are no POI for func in your program, so here there are no errors to delay and the program compiles fine. However, if you instantiate func then you'll get error at instantiation time saying g was not declared.
71,143,129
71,144,161
Is there a way to convert a base 2^64 number to its base10 value in string form or display it in standard out in C or C++ without using big num libs?
Let's say I have a very large number represented using an array of unsigned long(int64), and I want to see its base10 form either stored in a string and/or display it to the standard out directly, how would I do that in C or C++ without using libraries like gmp or boost?, what algorithm or method should I know? below is an example base2^64 number, with its base10 value in the comment // base2^64 unsigned long big_num[3] = [77478, 656713, 872]; // base10 = 26364397224300470284329554475476558257587048 I don't exactly know if this is the correct way to convert another number base to base 10, but this is what I did: To get the base10 value 26364397224300470284329554475476558257587048, I summed up all the digits of the base2^64 number that is multiplied to its base and raised by the index of the digit. base10 = ((77478 * ((2^64)^2)) + ((656713 * ((2^64)^1))) + ((872 * ((2^64)^0)))) = 26364397224300470284329554475476558257587048 the only problem with this is that there is no primitive data type that can hold this super large sum... I was just thinking if libraries like boost cpp_int and gmp represents their number like this, and if yes how do they convert it to it's base10 value in string form or display the base10 value in standard out? Or do they just use half of the bits of the data types that they use like for example in unsigned long and maybe use something like base 10000?
Repeatedly "mod 10" the array to find the next least significant decimal digit, then "divide by 10". Repeat as needed. Avoid unsigned long to encode 64-bit values as it may be only 32-bit. If code can encode the number not using the widest type and use uin32_t, then doing the repeated "mod 10" of the array is not so hard. Below illustrative code still needs to reverse the string - something left for OP. Potential other warts too - hence the advantage of using big number libraries for this sort of thing. #include <stdlib.h> #include <stdint.h> #include <stdio.h> // Form reverse decimal string void convert(char dec[], size_t n, uint32_t b32[]) { // TBD code to handle 0 while (n > 0 && b32[0] == 0) { b32++; n--; } while (n > 0) { unsigned char rem = 0; // Divide by 10. for (size_t i = 0; i < n; i++) { uint64_t sum = rem * (1ULL << 32) + b32[i]; b32[i] = (uint32_t) (sum / 10u); rem = (unsigned char) (sum % 10u); } *dec++ = (char) (rem + '0'); if (b32[0] == 0) { b32++; n--; } } *dec = 0; } Sample int main() { // unsigned long big_num[3] = [77478, 656713, 872]; uint32_t big_num[6] = {0, 77478, 0, 656713, 0, 872}; size_t n = sizeof big_num / sizeof big_num[0]; char s[sizeof big_num * 10 + 1]; convert(s, n, big_num); printf("<%s>\n", s); // <84078575285567457445592348207400342279346362> // 26364397224300470284329554475476558257587048 }
71,143,176
71,524,778
How to create a shared library using object library in CMake
I have two shared libraries each one having its own CMakeLists.txt. The directory structure is like this. main_dir |--- subdir | |--- src1.cpp | |--- src2.cpp | |--- src3.cpp | |--- CMakeLists.txt |--- src11.cpp |--- CMakeLists.txt Currently, I am able to build both main library and sub library (say main.so and sub.so). The CMakeLists.txt for both looks as below. main_dir/CMakeLists.txt option(BUILD_SHARED_LIBS "Build the shared library" ON) if(BUILD_SHARED_LIBS) add_library(mainlib SHARED) endif() target_sources(mainlib PRIVATE src11.cpp ) add_subdirectory(subdir) subdir/CMakeLists.txt option(BUILD_SHARED_LIBS "Build the shared library" ON) if(BUILD_SHARED_LIBS) add_library(sublib SHARED) endif() target_sources(sublib PRIVATE src1.cpp src2.cpp src3.cpp) Now I want the object file or symbols of sub library to be included in the main library as well, so that users can still use the main library alone even if they don't link their application to the sub library. I'm new to CMake and I was trying to create an object library out of all source files in the sub_dir and link this to my mainlib. add_library(subarchive OBJECT src1.cpp src2.cpp src3.cpp) target_sources(mainlib INTERFACE $<TARGET_OBJECTS:subarchive>) But It gives me error. (add_library) No SOURCES given to target: mainlib How can I create an object library in sub_dir and add it to both sublib and mainlib. Is there any better way to do this. Thanks.
I was able to get it working by setting PARENT_SCOPE for the object library in the suddirectory. The modifications to the original code look like this. main_dir/CMakeLists.txt set(SUBARCHIVE_OBJECTS) add_subdirectory(subdir) target_link_libraries(mainlib private ${SUBARCHIVE_OBJECTS} subdir/CMakeLists.txt add_library(subarchive OBJECT src1.cpp src2.cpp src3.cpp) list(APPEND SUBARCHIVE_OBJECTS ${TARGET_OBJECTS:subarchive>) set(SUBARCHIVE_OBJECTS ${SUBARCHIVE_OBJECTS} PARENT_SCOPE) Thanks for the responses.
71,143,460
71,143,614
how to set filter from another view?
std::vector v1 {4,2,7,6,4,1}; std::vector v2 {3,0,0,0,0,3}; I want to get the values in v1 with the condition v2=3 my desired result [4,1] I tried with filter but it seems to work only with a specified value. auto rng = v1 | ranges::views::filter([](int x){return ...;}); How can I do this without using for-loop?
Should be something along these lines: zip v1 and v2, filter based on the .second of each element with the condition you like transform to only retain the .first of the survived elements Here's a working demo: #include <iostream> #include <range/v3/view/filter.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/view/zip.hpp> using namespace ranges::views; int main() { std::vector v1 {4,2,7,6,4,1}; std::vector v2 {3,0,0,0,0,3}; auto result = zip(v1, v2) | filter([](auto pair){ return pair.second == 3; }) | transform([](auto pair){ return pair.first; }); std::cout << result << std::endl; // prints [4,1] } Some improvement Notice that [](auto pair){ return pair.first; } is simply a lambda that runs std::get<0> on its input std::pair. Unfortunately std::get<0> can't stand on its own, because there are several overlods of it (for std::pair, std::tuple, std::array, std::variant). One way to streamline the code would be to #include <boost/hof/lift.hpp> and then define template<std::size_t N> auto constexpr get = BOOST_HOF_LIFT(std::get<N>); so that you can pass get<0> around easily. Given this, and with the help of boost::hana::compose and boost::hana::curry one can write this a curried version of std::equal_to<>{} auto constexpr equal_to = curry<2>(std::equal_to<>{}); and come up with this: auto result = zip(v1, v2) | filter(compose(equal_to(3), get<1>)) | transform(get<0>); Barry pointed out in a comment that transform(get<0>) is actually ranges::views::keys, so the code can be further simplified: auto result = zip(v1, v2) | filter(compose(equal_to(3), get<1>)) | keys; In another comment was pointed out something that I never think about: filter takes a projection function too, so filter(compose(equal_to(3), get<1>)) does the same job as filter(equal_to(3), get<1>): auto result = zip(v1, v2) | filter(equal_to(3), get<1>) | keys; And finally, get<1> is elements<1> (wherever that is, I haven't found it yet :D), so we can do without Boost.Hof's BOOST_HOF_LIFT macro.
71,143,920
71,144,906
std::ranges::find_if - no type in std::common_reference
I'm using the SG14 flat_map as a container. As per a standard map, it takes Key and Value template parameters. Unlike a standard map, however, it doesn't store std::pair<Key, Value> in a binary search tree, but rather stores the keys and values in two separate containers (additional template arguments which default to std::vector) template< class Key, class Mapped, class Compare = std::less<Key>, class KeyContainer = std::vector<Key>, class MappedContainer = std::vector<Mapped> > class flat_map It then defines a number of types as follows: using key_type = Key; using mapped_type = Mapped; using value_type = std::pair<const Key, Mapped>; using key_compare = Compare; using const_key_reference = typename KeyContainer::const_reference; using mapped_reference = typename MappedContainer::reference; using const_mapped_reference = typename MappedContainer::const_reference; using reference = std::pair<const_key_reference, mapped_reference>; using const_reference = std::pair<const_key_reference, const_mapped_reference>; If I attempt to use std::ranges::find_if on the flat_map, I get an error: error: no type named ‘type’ in ‘struct std::common_reference<std::pair<const Key&, const Value&>&&, std::pair<const Key, Value>&>’ 121 | auto it = std::ranges::find_if(map, [](auto& kv) { return kv.second.name == "foo"; }); | ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If I use a non-range find_if, everything "just works" auto it = std::find_if(map.begin(), map.end(), [](auto& kv) { return kv.second.name == "foo"; }); Why does the std::ranges::find_if not work? Example on godbolt: https://godbolt.org/z/r93f7qozr Edit: @Brian provided an exemplar which successfully compiles - albeit with slight differences to mine - notably my map is const, and I take the lambda argument as a const ref... This begs the questions: Why does the combination of const range and const auto& lambda argument fail to compile, while pasing a mutable range works and taking the lambda argument by value works? I believe it would be considered somewhat of an anti-pattern to take the non-range std::find_if algorithm's lambda arguments by value (auto as opposed to const auto&) as this will cause every element to be copied - and therefore using const auto& should be preferred... principle of least surprose means I assumed the same would be the case with std::ranges - is this not the case?
Why does the combination of const range and const auto& lambda argument fail to compile, while pasing a mutable range works and taking the lambda argument by value works? First, the operator*() of the iterator of flat_map is defined as follows: reference operator*() const { return reference{*kit_, *vit_}; } And the type of reference is pair, this means that operator*() will return a prvalue of pair, so the parameter type of the lambda cannot be auto&, that is, an lvalue reference, because it cannot bind rvalue. Second, const flat_map does not model the input_range concept, that is, its iterator does not model input_iterator which requires indirectly_readable which requires common_reference_with<iter_reference_t<In>&&, iter_value_t<In>&>, the former is pair<const int&, const int&>&&, and the latter is pair<const int, int>&, there is no common_reference for the two. The workaround is to just define common_reference for them, just like P2321 does (which also means that your code is well-formed in C++23): template<class T1, class T2, class U1, class U2, template<class> class TQual, template<class> class UQual> requires requires { typename pair<common_reference_t<TQual<T1>, UQual<U1>>, common_reference_t<TQual<T2>, UQual<U2>>>; } struct basic_common_reference<pair<T1, T2>, pair<U1, U2>, TQual, UQual> { using type = pair<common_reference_t<TQual<T1>, UQual<U1>>, common_reference_t<TQual<T2>, UQual<U2>>>; }; For details on common_reference, you can refer to this question.
71,143,968
71,147,781
How to get a python list that is converted to a string, assigned to attributes in a struct in C++
Okay I am editing my original post. Apologies for not being clear enough earlier. I am relatively new to the developer role, specifically C,C++,Python and Embedded Linux. There is a python list plist = [2,434] This data is sent to another program written in C++ using socket programming. plist = str(plist) sock = socket.socket(socket.AF_INET, socket.SOCK_STRREAM) sock.connect(('localhost',12345)) sock.send(plist.encode('utf-8')) sock.close() Now this data is received by the C++ program as a string. I just made a sample string as follows to give you an idea what I am getting at the C++ end. const char* construct= "[2,434]"; Now I am trying to assign the two numbers, 2 and 434, to playerType and playerID respectively, which are part of the following structure called PLAYER_HEADER. typedef enum { START, STOP, PAUSE, RECORD }PLAYER_TYPE; typedef struct { PLAYER_TYPE playerType; unsigned long playerID; }PLAYER_HEADER; So far I've tried this approach, where I am typecasting the string to a struct type. PLAYER_HEADER* p= (PLAYER_HEADER* ) construct; player = p->playerType; cout<<(char)player<<endl; But this prints only '[' which is the first character of [2,434] I would like to know why this is happening. Is there a way I can get the rest of the data? I get that I have typecasted as a character. My end goal is to assign the two numbers to playerType and playerID . Is there any other way I can do this? Or is there a concept in C++ I need too understand to solve this problem?
C++ is a powerful language but part of that power is to let you do things that aren't "correct". The way you are trying to cast a char * to a PLAYER_HEADER* just doesn't work as you are expecting it to. You need to parse the string, ignoring parts you don't want and converting the parts you keep to the correct data type. One way to do this is with std::stringstream: PLAYER_HEADER player; std::istringstream ss(construct); int temp; ss.ignore(100, '['); // Skip [ if (ss >> temp) { player.playerType = (PLAYER_TYPE)temp; ss.ignore(100, ','); // Skip , if (ss >> player.playerID) { // Success. Do something. } } Another option is regex: PLAYER_HEADER player; std::smatch match; std::regex re(R"(\[(\d+),(\d+)\])"); std::string construct_str(construct); if (std::regex_search(construct_str, match, re)) { playerType = (PLAYER_TYPE)std::stoi(match[1]); playerID = std::stoi(match[2]); // Success. Do something. } There are still other ways, but the main point is that you need to learn why your casting doesn't work. With your code: PLAYER_HEADER* p= (PLAYER_HEADER* ) construct; player = p->playerType; cout<<(char)player<<endl; p points to the first char in "[2,434]" which is a [. Then playerType most likely has an offset of 0 in the struct so player also ends up pointing to the [. Then when you print it as a char you get [.
71,144,609
71,153,708
How to set a new window into a GroupBox in QT?
I have a Window with a Group Box called Function control box I want to include this window into that group box I do that by using this code ui->functionControlBoxGroupBox->setParent(componentIdentification); Where componentIdentification in an UI object of the window above. But it seems that nothing happens. Why? This is what happening. From this: To this: Question: How can I import a complete window form into a group box in QT?
Conceptually, the group box is supposed to be the other window's parent (not the opposite), thus you should do: componentIdentification->setParent(ui->functionControlBoxGroupBox); A better way to do the same thing: set a layout to the parent (the group box) and add the child window to the layout, i.e., in construction: ui->functionControlBoxGroupBox->setLayout(new QGridLayout()); somewhere else, later: ui->functionControlBoxGroupBox->layout()->addWidget(componentIdentification); This way, the group box is automatically set as the component's parent.
71,145,570
71,193,609
Can't open thread token of NamedPipe client: "Cannot open an anonymous level security token"
I am trying to impersonate a client with SYSTEM privileges. I noticed that this client it trying to connect to the named pipe: \\.\pipe\abc. I setup a named pipe server \\.\pipe\abc and wait for it to connect. Once it was connected, it failed: [+] Creating pipe server [+] Waiting for client to connect [+] Client connected [+] Client impersonated! [+] Failed to get thread token! 1347 The error 1347 according to Microsoft: ERROR_CANT_OPEN_ANONYMOUS 1347 (0x543) Cannot open an anonymous level security token. Why did it happen? It succeeded to impersonate but then failed to open the thread. This is my code until the failure on OpenThreadToken. SECURITY_ATTRIBUTES SecurityAttrs = { sizeof(SECURITY_ATTRIBUTES), NULL, // assigned access token of calling process FALSE }; DWORD openMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | WRITE_OWNER; DWORD pipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT; std::cout << "[+] Creating pipe server\n"; for (;;) { // create the named pipe HANDLE pipe = NULL; DWORD msgSize = 1024; pipe = CreateNamedPipeA( "\\\\.\\pipe\\abc", openMode, pipeMode, 1, // max instances msgSize, // out buffer size msgSize, // in buffer size 0, // timeout. 0 ~= 50ms &SecurityAttrs); if (pipe == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); std::cout << "[!] Pipe creation failed! " << err << std::endl; return err; } // wait for client to connect std::cout << "[+] Waiting for client to connect\n"; bool connected = ConnectNamedPipe(pipe, NULL) ? true : ( GetLastError() == ERROR_PIPE_CONNECTED); if (!connected) continue; std::cout << "[+] Client connected\n"; // read from pipe char buf[msgSize]; DWORD bytesread = 0; bool status = ReadFile( pipe, &buf, msgSize, &bytesread, NULL); // impersonate the connector if (!ImpersonateNamedPipeClient(pipe)) { DWORD err = GetLastError(); std::cout << "[!] Impersonation failed! " << err << std::endl; return -1; } std::cout << "[+] Client impersonated!\n"; HANDLE hToken = {}; if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, false, &hToken)) { DWORD err = GetLastError(); std::cout << "[!] Failed to get thread token! " << err << std::endl; return err; }
based on comments, in client code - FILE_FLAG_OPEN_NO_RECALL | FILE_FLAG_OVERLAPPED; used if place dwFlagsAndAttributes in call of CreateFile however need notice that FILE_FLAG_OPEN_NO_RECALL == (SECURITY_SQOS_PRESENT|SECURITY_ANONYMOUS) and FILE_FLAG_OPEN_NO_RECALL == SECURITY_SQOS_PRESENT both this flags have the same binary value 0x00100000 (and SECURITY_ANONYMOUS == 0 ) think this is problem of design of CreateFile api. it have less parameters, compare NtCreateFile and it try combine different parameters in single. for instance in single dwFlagsAndAttributes combine FileAttributes + CreateOptions + ObjectAttributes->SecurityQualityOfService . so parameter is "overloaded"
71,147,238
71,147,390
Vector Keeps over printing output
#include <iostream> #include <stdlib.h> #include <pthread.h> #include <fstream> #include <sstream> #include <mutex> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <vector> using namespace std; #define NUM_THREADS 2 pthread_mutex_t mutexChild; pthread_cond_t condChild; vector<int> vect; void openfile(ifstream&, string); void* childthread(void *args) { ifstream inFile; openfile(inFile, "Fruits.txt"); string line; pthread_mutex_lock(&mutexChild); int countt = 0; int lines = 0; int total = 0; while (!inFile.eof()) { getline(inFile, line); countt = 0; for (int i = 0; i < line.size(); i++) if ((line[i] >= 'A' && line[i] <= 'Z') || (line[i] >= 'a' && line[i] <= 'z')) { countt++; } lines++; vect.push_back(countt); } pthread_mutex_unlock(&mutexChild); pthread_exit(NULL); } void* parentthread(void *args) { ifstream inFile; openfile(inFile, "Fruits.txt"); string line; pthread_mutex_lock(&mutexChild); int lines = 0; int total = 0; int countt = 0; while (!inFile.eof()) { getline(inFile, line); for (int i = 0; i < vect.size(); i++) cout << vect[i] << endl; } pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t threads; int thrd1; //int i; int thrd2; pthread_mutex_init(&mutexChild, NULL); thrd1 = pthread_create(&threads, NULL, childthread, NULL); if (thrd1) { cout << "Error:unable to create thread," << thrd1 << endl; exit(-1); } pthread_t threads2; thrd2 = pthread_create(&threads2, NULL, parentthread, NULL); if (thrd2) { cout << "Error:unable to create thread," << thrd2 << endl; exit(-1); } // pthread_join(threads,NULL); // pthread_join(threads2, NULL); //threads.join(); ///threads2.join(); pthread_mutex_destroy(&mutexChild); pthread_cond_destroy(&condChild); pthread_exit(NULL); } void openfile(ifstream &inFile, string fname) { inFile.open(fname); if (inFile.is_open()) { // cout << "Successfully opened File" << endl; } } My child threads keeps printing the output 8 times when I only need it to print once. There are 8 lines in my txt file so im guessing thats why its printing the output 8 times. Can anyone tell me why it's doing and how I change it. I also know there is an easier why to do this task but I am required to exchange data using posix threads. Its printing like this 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 8 times when I just need 1 2 3 4 5 6 7 8
while (!inFile.eof()) { getline(inFile, line); for (int i = 0; i < vect.size(); i++) cout << vect[i] << endl; } prints out the contents of the vector built in the child thread once for every line in the file (sort of. See Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?). This is not what you want. There doesn't seem to be any need to read the file here. The child thread already read the file and did all the vector assembly work. All you should need to solve the immediate problem, repeated printing of the data, is for (int i = 0; i < vect.size(); i++) cout << vect[i] << endl;
71,147,810
71,156,072
How to change background color in QGraphicsScene?
I want to give background color in my QGraphicsScene. For that, I have override drawBackground() method, and tried to set color but it is not working. Background color is not changing. Here is my drawBackground() method. Widget.h QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACE class Widget : public QGraphicsView { Q_OBJECT public: Widget(QWidget *parent = nullptr); ~Widget(); protected: void drawBackground(QPainter *painter, const QRectF &rect); }; Widget.cpp Widget::Widget(QWidget *parent) : QGraphicsView(parent) , ui(new Ui::Widget) { ui->setupUi(this); scene = new QGraphicsScene(this); view = new QGraphicsView(this); view->setScene(scene); view->setDragMode(QGraphicsView::RubberBandDrag); ui->verticalLayout_2->addWidget(view); } void Widget::drawBackground(QPainter *painter, const QRectF &rect) { painter->save(); painter->setBrush(QBrush(Qt::yellow)); painter->restore(); } Can anyone help me ?
Your code has a number of problems or, at least, inconsistencies. Firstly your Widget class makes use of both inheritance and composition with regard to QGraphicsView in that it derived from QGraphicsView and has a QGraphicsView member. That may be what you want but it seems unlikely. Firstly, you say... I want to set background for the ui->verticalLayout_2. So my background should be yellow. As per my comment, that can be easily done by simply using QGraphicsView::setBackgroundBrush... view->setBackgroundBrush(Qt::yellow); The other issue is with your override of drawBackground in the Widget class. Currently you have... void Widget::drawBackground(QPainter *painter, const QRectF &rect) { painter->save(); painter->setBrush(QBrush(Qt::yellow)); painter->restore(); } But all that does is save the painter's state, set its brush to a solid yellow colour and then restore the state of the painter. It's essentially a noop in that it doesn't actually draw anything. If you really want to override the drawBackground member in this way then try something like... void Widget::drawBackground(QPainter *painter, const QRectF &rect) { painter->save(); painter->setPen(Qt::NoPen); painter->setBrush(QBrush(Qt::yellow)); painter->drawRect(rect); painter->restore(); } [As an aside, when overriding a virtual member in a derived class always use the override specifier.]
71,147,822
71,148,165
opengl draw tringle with projection and view projection
I am trying to draw a tringle with OpenGL by using projection view and model matrices. this is my shader gl_Position = view * projection * model * vec4(pos, 1.0); and this is my code glm::mat4 view = glm::translate(view, glm::vec3(0.0f, -0.5f, -2.0f)); glm::mat4 proj = glm::perspective(glm::radians(45.0f), (float)width / height, 0.1f, 100.0f); float tringleVertices2[] = { 0.0f, 0.5f, 0.0f, // Vertex 1 (X, Y) 0.5f, -0.5f, 0.0f, // Vertex 2 (X, Y) -0.5f, -0.5f, 0.0f, // Vertex 3 (X, Y) }; But the weird thing is that when I remove the view and the projection matrix and my shader look like this model * vec4(pos, 1.0); the code works I would like to know if there is something wrong with my matrices or there are a problem with the other part of the code
The correct MVP matrix multiplication order should be: gl_Position = projection * view * model * vec4(pos, 1.0); Think about matrix-vector multiplication as it associates right-to-left: first you transform from model to world space, then from world to view space (via inverse camera matrix) and finally you project from view space to clip space.
71,148,130
71,151,713
How would you implement a lazy "range factory" for C++20 ranges that just calls a generator function?
I like the idea of the lazy ranges you can make with std::views::iota but was surprised to see that iota is currently the only thing like it in the standard; it is the only "range factory" besides views::single and views::empty. There is not currently, for example, the equivalent of std::generate as a range factory. I note however it is trivial to implement the semantics of generate by using a transform view on iota and just ignoring the value iota passes to transform i.e. #include <iostream> #include <ranges> #include <random> template<typename F> auto generate1(const F& func) { return std::views::iota(0) | std::views::transform([&func](int) {return func(); }); } std::random_device dev; std::mt19937 rng(dev()); int main() { auto d6 = []() { static std::uniform_int_distribution<> dist(1, 6); return dist(rng); }; for (int v : generate1(d6) | std::views::take(10)) { std::cout << v << ' '; } std::cout << '\n'; } My questions is what would be "the real way" to implement something like this? To make a range view object that is pipeable that does not just use iota. I tried inheriting from ranges::view_interface -- no idea if this is the correct approach -- and just having it return a dummy iterator that calls a generator function but my code doesn't work because of the part where it needs to pipe the range view to std::views::take in order to not cause an infinite loop. The object I define here does not end up being pipeable. #include <iostream> #include <ranges> #include <random> template<typename F> class generate2 : public std::ranges::view_interface<generate2<F>> { using value_type = decltype(std::declval<F>()()); class iterator { const F* gen_func_; public: iterator(const F* f) : gen_func_(f) {} value_type operator*() const { return (*gen_func_)(); } bool operator!=(const iterator&) { return true; } iterator& operator++() { return *this; } }; F generator_func_; public: generate2(const F& f) : generator_func_(f) { } iterator begin() { return iterator(&generator_func_); } iterator end() { return iterator(nullptr); } }; std::random_device dev; std::mt19937 rng(dev()); int main() { auto d6 = []() { static std::uniform_int_distribution<> dist(1, 6); return dist(rng); }; // the following doesnt compile because of the pipe... for (int v : generate2(d6) | std::views::take(10)) { std::cout << v << ' '; } std::cout << '\n'; }
The reason why generate2 cannot work is that it does not model the range concept, that is, the type returned by its begin() does not model input_iterator, because input_iterator requires difference_type and value_type to exist and i++ is a valid expression. In addition, your iterator does not satisfy sentinel_for<iterator>, which means that it cannot serve as its own sentinel, because sentinel_for requires semiregular which requires default_initializable, so you also need to add default constructors for it. You also need to rewrite bool operator!=(...) to bool operator==(...) const since operator!= does not reverse synthesize operator==. But it's easier to just use default_sentinel_t as sentinel in your case. if you add them to iterator you will find the code will be well-formed: class iterator { public: using value_type = decltype(std::declval<F>()()); using difference_type = std::ptrdiff_t; iterator() = default; void operator++(int); bool operator==(const iterator&) const { return false; } // ... }; However, the operator*() of iterator does not meet the requirements of equality-preserving, that is to say, the results obtained by the two calls before and after are not equal, which means that this will be undefined behavior. You can refer to the implementation of ranges::istream_view to use a member variable to cache each generated result, then you only need to return the cached value each time iterator::operator*() is called. template<typename F> class generate2 : public std::ranges::view_interface<generate2<F>> { public: auto begin() { value_ = generator_func_(); return iterator{*this}; } std::default_sentinel_t end() const noexcept { return std::default_sentinel; } class iterator { public: //... value_type operator*() const { return parent_->value_; } private: generate2* parent_; }; private: F generator_func_; std::remove_cvref_t<std::invoke_result_t<F&>> value_; };
71,148,182
71,148,259
Object reading and writing overload in C++
I know that the assignment operator can be overloaded. When writing to an object, the object's overload function is called. Obj = 10; // Obj's assignment overload function called. Is there a way to define a function to be called when an object is read? int a = Obj; In this case Obj's reading function would be called and the return value would be assigned to a.
You're looking for what's sometimes called a cast operator. example: #include <iostream> struct example { int val; operator int() const { return val; } }; int main () { example x{42}; int y = x; std::cout << y; } Will print 42.
71,150,660
71,150,981
Extracting vectors from Structure in header file
This is the header file in question: namespace osc { using namespace gdt; struct TriangleMesh { std::vector<vec3f> vertex; std::vector<vec3f> normal; std::vector<vec2f> texcoord; std::vector<vec3i> index; // material data: vec3f diffuse; }; struct Model { ~Model() { for (auto mesh : meshes) delete mesh; } std::vector<TriangleMesh *> meshes; //! bounding box of all vertices in the model box3f bounds; }; Model *loadOBJ(const std::string &objFile); } I have successfully been able to use this header file to import an .obj of the 3D model in my main C++ code using the loadOBJ() function described in the header. I now want to operate on the vertices of that model. From the looks of it, the vertex points are in the structures defined in the header file. How do I extract these vertex vectors from the structure (and display them)?
loadOBJ() gives you a pointer to a Model object. Model has a std::vector (a dynamic array) member named meshes that holds pointers to TriangleMesh objects. TriangleMesh has a std::vector member named vertex holding vec3f objects. You can iterate the various vectors like this: osc::Model *model = osc::loadOBJ(...); if (!model) ... // error handling for (auto&& mesh : model->meshes) { cout << "vertex:\n"; for (auto&& vtx : mesh->vertex) { cout << "x=" << vtx.x << ", y=" << vtx.y << "z=" << vtx.z << "\n"; } cout << "\n"; // repeat for mesh->normal, mesh->texcoord, mesh->index, etc... } delete model;
71,150,895
71,151,247
My code should render the front of a cube, but instead shows the back. Why?
I'm rendering this cube and it should show the front of the cube but instead it shows the back (green color). How do i solve this? I've been sitting for a couple of hours trying to fix this but nothing helped. I was trying various things like changing the order in which the triangles are rendered and it didn't help either. Thanks for any help. Here's my code. float vertices[] = { //front -0.5f, -0.5f, 0.0f, 1.f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 1.f, 0.0f, 0.5f, //back -0.5f/2, -0.5f/2, -0.5f, 0.0f, 1.f, 0.0f, 0.5f/2, -0.5f/2, -0.5f, 0.0f, 1.f, 0.0f, 0.5f/2, 0.5f/2, -0.5f, 0.0f, 1.f, 0.0f, -0.5f/2, 0.5f/2, -0.5f, 0.0f, 1.f, 0.0f, }; unsigned int indices[] = { //front 0, 2, 3, 0, 1, 2, //back 4, 6, 7, 4, 5, 6, //top 3, 6, 2, 3, 7, 6, //bottom 0, 1, 5, 0, 5, 4, //left 3, 0, 4, 3, 4, 7, //right 1, 2, 5, 2, 6, 5 }; int main() { if (!glfwInit()) { std::cout << "ERROR" << std::endl; return -1; } int width = 640; int height = 480; window = glfwCreateWindow(width, height, "OPENGL", NULL, NULL); if (!window) { std::cout << "ERROR: WINDOW" << std::endl; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_VERSION_MAJOR, 4); glfwWindowHint(GLFW_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwMakeContextCurrent(window); glfwSwapInterval(1); if (glewInit() != GLEW_OK) { std::cout << "ERROR: GLEW" << std::endl; } glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); std::cout << "OpenGL " << glGetString(GL_VERSION) << std::endl; VertexArray va1; VertexBuffer vb1(vertices, sizeof(vertices), GL_STATIC_DRAW); IndexBuffer ib1(indices, sizeof(indices), GL_STATIC_DRAW); va1.linkAttrib(vb1, 0, 3, GL_FLOAT, 6 * sizeof(float), 0); va1.linkAttrib(vb1, 1, 3, GL_FLOAT, 6 * sizeof(float), 3 * sizeof(float)); ShaderSources sources = parseShader("basic.shader"); unsigned int program = createShaderProgram(sources.vertexSource, sources.fragmentSource); glUseProgram(program); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(unsigned int), GL_UNSIGNED_INT, nullptr); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; } And here what the cube looks like:
You currently are using glEnable(GL_DEPTH_TEST) withglDepthFunc(GL_LESS), which means only fragments having a smaller z (or depth) component are rendered when rendering overlapped triangles. Since your vertex positions are defined with the back-face having a smaller z coordinate than the front-face, all front-face fragments are ignored (since their z coordinate is larger). Solutions are: Using glDepthFunc(GL_GREATER) instead of glDepthFunc(GL_LESS) (which may not work in your case, considering your vertices have z <= 0.0 and the depth buffer is cleared to 0.0) Modify your vertex positions to give front-face triangles a smaller z component than back-face triangles. I believe that when using matrix transforms, a smaller z component normally indicates the fragment is closer to the camera, which is why glDepthFunc(GL_LESS) is often used.
71,151,350
71,151,505
C++ Member Functions (getters)
I've seen people define a member function like this: void getValue(int& v) { v = m_value; } and also like this: int getValue() { return m_value; } I guess the first saves memory? Is that the only time you would use the first type of get-function? The second seems a lot more convenient.
I thought I would godbolt it for you source #include <iostream> struct Foof{ int m_val; Foof(int v){ m_val = v; } void woodle() { if(m_val > 42) m_val++; else m_val--; } void Get1(int &v) { v = m_val; } int Get2() { return m_val; } }; int main(int c, char**v){ int q; std::cin >> q; Foof f1(q); std::cin >> q; Foof f2(q); f1.woodle(); f2.woodle(); int k; f1.Get1(k); int j = f2.Get2(); std::cout << k << j; } the woodle function and the cin to initialize is to make the compiler think a bit I have 2 foofs otherwise the compiler goes "well I know the answer to this question" when I call Get2 after Get1 compiled with -03 - ie optimize hard. The code comes out as (gcc) pushq %rbx movl $_ZSt3cin, %edi subq $16, %rsp leaq 12(%rsp), %rsi call std::basic_istream<char, std::char_traits<char> >::operator>>(int&) movl 12(%rsp), %ebx leaq 12(%rsp), %rsi movl $_ZSt3cin, %edi call std::basic_istream<char, std::char_traits<char> >::operator>>(int&) movl 12(%rsp), %eax movl $_ZSt4cout, %edi leal 1(%rbx), %edx cmpl $43, %ebx leal -1(%rbx), %esi cmovge %edx, %esi leal -1(%rax), %ebx leal 1(%rax), %edx cmpl $43, %eax cmovge %edx, %ebx call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) movq %rax, %rdi movl %ebx, %esi call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) addq $16, %rsp xorl %eax, %eax popq %rbx ret I separated out the actual calls to Get1 or Get2 you can see that the generated code is identical the compiler is very aggressive at optimizing, there are no function calls etc Lesson, write your code to be human readable and let the compiler do the heavy lifting
71,151,379
71,151,592
How to generate current datetime with system's regional format in C++?
I'm looking for a way to get the current system date time formatted in a manner consistent with the system's region. For example, a system in the US would have something like: 01-31-2022 1:59:00 PM And a system in Europe would have something like: 31-01-2022 13:59:00 I've experimented a bit with using Boost but can't seem to get exactly what I'm specifying here; is there any library or implementation that might let me achieve this? Thanks.
First, we configure the locale for the user's default by imbuing the output stream with the empty-name locale (locale("")). Then we use the locale-dependent date and time formats with std::put_time. For example: Live On Coliru #include <ctime> #include <iomanip> #include <iostream> int main() { std::time_t raw_now = time(nullptr); std::tm now = *localtime(&raw_now); std::cout.imbue(std::locale("")); std::cout << std::put_time(&now, "My locale: %x %X\n"); // For comparison, how we'd expect it to show up for a // user configured for Great Britain: std::cout.imbue(std::locale("en_GB.UTF-8")); std::cout << std::put_time(&now, "Great Britain: %x %X\n"); } On my box (configured for the US), this produces the following output: My locale: 02/16/2022 06:05:48 PM Great Britain: 16/02/22 18:05:48 There is also a %c format to produce date and time, but this (at least normally) includes the day of the week (e.g., Wed 16 Feb 2022 18:11:53 PST) which doesn't fit with what you seem to want. As a side-note: all compilers are supposed to accept at least "C" and "" for locale names. Any other name (like the en_GB.UTF-8 I've used above) depends on the compiler. You may need a different string if you're using a different compiler (I was testing with g++ on Linux).
71,151,613
71,152,639
how does python package links to dll (.so) files
I am creating a python package based on this repo. The package has few cpp files which are compiled when I build the package using setup.py and running pip install . This generates _C.cpython-36m-x86_64-linux-gnu.so file in my package installation directory. To import this dll (.so) file all I have to do is from . import _C (something like this) Now the imported _C object points to _C.cpython-36m-x86_64-linux-gnu.so. I don't understand how _C object gets linked to the specific .so file. Is that information written in any of the metadata files while the package is being built?
No. The mechanism for handling the C++ library loading is done by pybind. In the documentation (https://pybind11.readthedocs.io/en/stable/basics.html), you will see that in order to import a C++ library built with the pybind API, the correct syntax in your .py file is to import the prefix of the library. Thus, when you write import _C in your python code on your linux system it will look for _C.<whatever>.so and load the symbols from that file. All of the C++ files used to build import-able python modules in the repo you refer to ultimately include torch/extension.h (via vision.h --- https://github.com/microsoft/scene_graph_benchmark/blob/main/maskrcnn_benchmark/csrc/cuda/vision.h#L3) and if you explore the source for pytorch, extension.h includes python.h which includes pybind.h (https://pytorch.org/cppdocs/api/program_listing_file_torch_csrc_api_include_torch_python.h.html).
71,151,900
71,152,071
Segmentation fault in static member function c++
class Adder { public: static int Solve(int a, int b) {return a + b;} }; class Substructor { public: static int Solve(int a, int b) {return a - b;} }; class Comparer { public: static bool Solve(int a, int b) {return a < b;} }; class If { public: static int Solve(bool term, int a, int b) {return term ? a : b;} }; class Fibo { public: static int Solve(int num) { int res = If::Solve( Comparer::Solve(num, 2), 1, Adder::Solve( Fibo::Solve(Substructor::Solve(num, 1)), Fibo::Solve(Substructor::Solve(num, 2)) ) ); return res; } }; int calc(int x) { return Fibo::Solve(x); } #include <iostream> int main() { std::cout << calc(5) << '\n'; return 0; } This code leads to segmentation fault. I tested all classes separately, write recursive fibo static member function without other static member functions and it works. While combined it crushes. How to fix it and why it crush ?
The problem arises here: class Fibo { public: static int Solve(int num) { int res = If::Solve( Comparer::Solve(num, 2), 1, Adder::Solve( Fibo::Solve(Substructor::Solve(num, 1)), Fibo::Solve(Substructor::Solve(num, 2)) ) ); return res; } }; In the If::Solve() sentence, what you expected maybe, if Comparer::Solve(num, 2) checks that num<2, return 1 and do not evaluate the remaining expressions Fibo::Solve(Substructor::Solve(num, 1)) and the second one, it will not work as you expected. To evaluate If::Solve(), every arguments must be evaluated before to pass to If::Solve(). As it evaluates again and again recursively, stack overflow occurs, therefore program terminates. If you really wish to make it run, modify like this: class Fibo { public: static int Solve(int num) { if (Comparer::Solve(num, 3)) { return 1; } else return Adder::Solve( Fibo::Solve(Substructor::Solve(num, 1)), Fibo::Solve(Substructor::Solve(num, 2)) ); } }; This guarantees that if num is 1 or 2, return 1 and does not evaluates remaining expressions.
71,152,918
71,152,972
About increment/decrement operators
Here is the code snippet: #include <iostream> #include <iterator> #include <algorithm> #include <functional> #include <vector> std::vector<int> vec(5); int produce_seq() { static int value = 0; return (value*value++); } int main() { std::generate_n(vec.begin(),5, produce_seq); for(auto val:vec) { std::cout << val <<std::endl; } } Why this code snippet ouputs 0 2 6 12 20 other than 0 1 4 9 16 I think value*value++; is equivalent to value*value; value++;. UPDATED: Should not value++ be evaluated after the entire expression has already been evaluated? For example, if there is a expression like sum=a+b++;, sum=a+b; is always evaluated before b++.
Your program has undefined behavior. The order in which operands are evaluated is generally unspecified in C++. The only thing we can say in your example is that the value computation of value++ happens before its side effect on value and that the value computations of both the left-hand side and the right-hand side of value*value++ happen before the value computation of value*value++. This doesn't specify whether the side effect of value++ on value is sequenced before or after the value computation of value on the left-hand side of value*value++. Having a side-effect on a scalar unsequenced with a value computation on the same scalar causes undefined behavior. Undefined behavior means that you have no guarantee on how the program will behave at all. For all the details on what kind of evaluations are sequenced, see https://en.cppreference.com/w/cpp/language/eval_order.
71,152,949
71,153,020
In C++, How a std::thread can call a member function without creating an object?
If we have a class H with some operator() overloaded. How it is possible to create a thread from these member functions without instantiating an object from class H. Consider the following code #include<iostream> #include<thread> class H { public: void operator()(){ printf("This is H(), I take no argument\n"); } void operator()(int x){ printf("This is H(), I received %d \n",x); } }; int main(){ int param = 0xD; //No object created std::thread td_1 = std::thread(H()); std::thread td_2 = std::thread(H(),param); td_1.join(); td_2.join(); //From an object H h; std::thread td_3 = std::thread(h); std::thread td_4 = std::thread(h,param); td_3.join(); td_4.join(); return 0; } produce the output : This is H(), I take no argument This is H(), I received 13 This is H(), I take no argument This is H(), I received 13 The question is, how td_1 and td_2 called the member function operator() of class H without an object of class H?
how td_1 and td_2 called the member function operator() of class H without an object of class H? td_1 and td_2 does create objects of type H. Those objects are temporaries. Next, those supplied function object(which are temporaries in this case) are moved/copied into the storage belonging to the newly created thread of execution and invoked from there. You can confirm this by adding a default constructor and move constructor inside class H as shown below: #include<iostream> #include<thread> class H { public: void operator()(){ printf("This is H(), I take no argument\n"); } void operator()(int x){ printf("This is H(), I received %d \n",x); } //default constructor H() { std::cout<<"default constructor called"<<std::endl; } //move constructor H(H&&) { std::cout<<"move constructor called"<<std::endl; } }; int main(){ int param = 0xD; std::thread td_1 = std::thread(H()); std::thread td_2 = std::thread(H(),param); td_1.join(); td_2.join(); return 0; } The output of the above program is: default constructor called move constructor called move constructor called default constructor called move constructor called move constructor called This is H(), I take no argument This is H(), I received 13
71,153,181
71,153,435
Sort Integers by The Number of 1 Bits . I used one sort function to sort the vector ? But why sort is not working?
Sort Integers by The Number of 1 Bits Leetcode : Problem Link Example Testcase : Example 1: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explantion: [0] is the only integer with 0 bits. [1,2,4,8] all have 1 bit. [3,5,6] have 2 bits. [7] has 3 bits. The sorted array by bits is [0,1,2,4,8,3,5,6,7]\ Example 2: Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] Output: [1,2,4,8,16,32,64,128,256,512,1024] Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. My Solution : class Solution { public: unsigned int setBit(unsigned int n){ unsigned int count = 0; while(n){ count += n & 1; n >>= 1; } return count; } vector<int> sortByBits(vector<int>& arr) { map<int,vector<int>>mp; for(auto it:arr){ mp[setBit(it)].push_back(it); } for(auto it:mp){ vector<int>vec; vec=it.second; sort(vec.begin(),vec.end()); //This Sort Function of vector is not working } vector<int>ans; for(auto it:mp){ for(auto ele:it.second){ ans.push_back(ele); } } return ans; } }; In my code why sort function is not working ? [1024,512,256,128,64,32,16,8,4,2,1] For the above testcase output is [1024,512,256,128,64,32,16,8,4,2,1] because of sort function is not working. It's correct output is [1,2,4,8,16,32,64,128,256,512,1024] Note : In the above example testcase every elements of the testcase has only one set-bit(1)
As your iteration in //This sort function ... refers to mp as the copy of the value inside the map, sort function will not sort the vector inside it, but the copy of it. Which does not affecting the original vector<int> inside the mp. Therefore, no effect occurs. You should refer the vector inside the map as a reference like this: class Solution { public: unsigned int setBit(unsigned int n) { unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } vector<int> sortByBits(vector<int>& arr) { map<int, vector<int>>mp; for (auto it : arr) { mp[setBit(it)].push_back(it); } for (auto& it : mp) { sort(it.second.begin(), it.second.end()); //Now the sort function works } vector<int>ans; for (auto it : mp) { for (auto ele : it.second) { ans.push_back(ele); } } return ans; } }; Although there is more design problem inside your solution, this will be a solution with minimized modification.
71,153,486
71,153,688
Send data with libcurl to .php in c++
I use libcurl to send request to my site for fetching some info. But I don't know how to get data from user (c++) and send that to .php file. It's my c++ source which get name from user : std::string userUname; std::cout << "[?] Enter Your Username: "; std::cin >> userUname; CURL* curl; CURLcode res; std::string readBuffer; curl = curl_easy_init(); if (curl) { const char* testlevi = "http://example.com/a.php"; curl_easy_setopt(curl, CURLOPT_URL, testlevi); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); res = curl_easy_perform(curl); curl_easy_cleanup(curl); std::cout << readBuffer << std::endl; } And thats my php file which gets username , and will echo: <?php $name = $_GET['name']; if($name == "Jason"){ echo "Welcome Jason."; }else{ echo "Username is wrong."; } ?> I just don't know how to send userUname to .php file($_GET['name'])
You have to send the userUname in the body : curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=" + userUname ); And in PHP change $_GET by $_POST OR $_REQUEST
71,154,459
71,154,695
C++: GetTempPath() without tilde (~)
I need to get temp path. So I tried GetTempPath() and std::getenv("TEMP"). The problem is that the result contains ~ symbol, for example C:\Users\OLEKSI~1.ALE\AppData\Local\Temp. Is it possible to get full temp path like C:\Users\Oleksii\AppData\Local\Temp?
GetLongPathName function: Converts the specified path to its long form. DWORD GetLongPathNameW( [in] LPCWSTR lpszShortPath, [out] LPWSTR lpszLongPath, [in] DWORD cchBuffer ); DWORD GetLongPathNameA( [in] LPCSTR lpszShortPath, [out] LPSTR lpszLongPath, [in] DWORD cchBuffer ); Set lpszShortPath = short path with ~ symbols. Read result from lpszLongPath. GetLongPathName
71,154,815
71,154,961
Should we use delete[] or delete on function that return allocated memory pointer?
Should i use delete[] or delete for Register() example below? We hit some memory leak issue and legacy code which is not allow to change the return type and input of the function. I understand that new[] should use delete[]. new should use delete. However for case below, which method is correct? UINT Register(UINT regaddr, usb_dev_handle* current_handle) { unsigned int val= 0; unsigned char* buffer = readregister(current_handle, char((regaddr >> 8) & 0x00FF), char(regaddr & 0x00FF)); raddrvaluefinal = buffer[2] << 8 | buffer[3]; delete buffer; return val; } unsigned char* readregister(usb_dev_handle *current_handle, char one, char two) { unsigned char *buffer = new unsigned char[4]; char cmd[2]; cmd[0] = 'D'; cmd[1] = 'B'; int rv = 0; unsigned char bin_size[2]; buffer[0] = one + 0x80; buffer[1] = two; buffer[2] = buffer[3] = 0; usb_bulk_write(current_handle, 0x02, cmd, 2, 500); bin_size[0] = (5 / 4) & 0x0FF; bin_size[1] = ((5 / 4) >> 8) & 0x0FF; rv = usb_bulk_write(current_handle, 0x01, (char*)bin_size, 2, 2000); unsigned int byteswrite += usb_bulk_write(current_handle, 0x04, (char*)buffer, 4, 2000); unsigned int bytesread += usb_bulk_read(current_handle, 0x86, (char*)buffer, 4, 2000); buffer[0] = one; buffer[1] = two; return buffer; }
I understand that new[] should use delete[]. new should use delete. unsigned char *buffer = new unsigned char[4]; ... delete buffer; The program is wrong, and against your understanding. When a dynamic array is allocated dynamically with new[], delete[] must be used to deallocate it. If you use delete, then the behaviour of the program is undefined. You shouldn't use owning bare pointers in the first place, and in this case there doesn't even seem to be any need to use a dynamic array. I recommend following instead: std::array<unsigned char, 4> readregister(usb_dev_handle *current_handle, char one, char two) { std::array<unsigned char, 4> buffer; // ... usb_bulk_write(current_handle, 0x04, reinterpret_cast<char*>(buffer.data()), 4, 2000); Sidenote: "new -> delete", "new[] -> delete[]" is a slight oversimplification. delete[] must be used if new is used to create an array: using T = int[4]; int* ptr = new T; delete[] ptr; // correct
71,154,952
71,155,552
Controlled access to private member
I have a class that contains a private std::vector and a flag. Every time an Object inside the vector is modified I want to set that flag. This is what I came up with.. struct Object { float f; int i; } class SomeClass { private: std::vector<Object> Data; bool Updated; public: inline const std::vector<Object>& ReadData const { return Data; } inline std::vector<Object>& WriteData { Updated = false; return Data; } } This design is the safest I could come up with. The only issue with this is the fact I can bypass this safety mechanism when I'm using Data inside SomeClass. So, even though I don't have lots of methods in SomeClass that operate on Data, could you suggest me a better design to achieve this? (Tracking every change to Data by setting Updated accordingly)
Your solution fails to achieve what you want. SomeClass has an Update method that does some stuff and sets Updated to true. Data is used inside a couple of big functions, and first thing they do is to check Updated and call Update when it's false. Again this is just the best I could come up with and I always feel naked when showing my ideas to the experts here I guess what you had in mind was something like this: SomeClass sc; auto& data = sc.WriteData(); sc.Update(); // checks if Updated is set to false // if necessary Updates the data and // resets Updated to true sc.do_some_thing_with_data(); // this can use Data as is because Updated is true But your "encapsulation" does not prevent a user to do this: SomeClass sc; auto& data = sc.WriteData(); // Updated = false sc.Update(); // Updated = true data[0] = 42; // modify Data sc.do_some_thing_with_data(); // assumes data has not been modified I suppose you actually want to call Update inside do_some_thing_with_data, however that does not change the problem: auto& data = sc.WriteData(); // Updated = false sc.do_some_thing_with_data(); // checks Updated, updates the data // and resets Updated = true // assumes data is updated -> OK data[0] = 42; sc.do_some_thing_with_data(); // checks Updated, // does not update data because Updated is still true // assumes data is updated -> WRONG Once you returned a non-const reference you are no longer in control of modifiying the member. Your flag does not provide the "security" you expect. Returning a non-const reference is not encapsulation! You can either not return a non-const reference, or don't pretend to encapsulate data when you don't encapusalte data (ie make the member public). If you want to be in control of modifications to data then do something along the line of: class SomeClass { private: std::vector<Object> Data; bool Updated; public: const std::vector<Object>& ReadData const { return Data; } void WriteData(const Object& obj,size_t index) { Data[index] = obj; Updated = false; } void WriteF(float f,size_t index){ Data[index].f = f; Updated = false; } void WriteI(int i,size_t index){ Data[index].i = i; Updated = false; } } And if you are worried about SomeClass being able to modify Data by bypassing the setters then thats because you want SomeClass do too much. Do other stuff in a different class: struct SomeOtherClass { SomeClass sc; }; Now SomeOtherClass can only modify Data in a controlled way. PS: You seem to got confused by encapsulation vs no encapsulation. To reiterate: Returning a non-const reference is not encapsulation. If you want to encapsulate Data then make it private and do not provide direct access to it. The class that is in charge of encapsulating data has direct access to it. Other classes don't.
71,155,502
71,333,674
Display runtime error message in gRPC server side and pass it to the client
I am using gRPC in a project where I have to set and get values from some separate/outside functions. Some functions has case that if they get unwanted value they will throw runtime error. By following this I have got an idea to catch a error_state from inside of the gRPC function. I am giving here some of my approach. A demo source is this proto file where only including here the client message part message NameQuery { string name = 1; int32 cl_value = 2; // This is a user input data which will be passed to the server and then to a outside function client/src/main.cpp int main(int argc, char* argv[]) { // Setup request expcmake::NameQuery query; expcmake::Address result; query.set_name("John"); int x; cout << "give value of x: "; cin>> x; query.set_cl_value(x); // remaining are as like as before server/src/main.cpp #include <iostream> using namespace std; void Check_Value(const ::expcmake::NameQuery* request) { if (request->cl_value() < 5) cout << "request->cl_value(): " << request->cl_value() << endl; else throw std::runtime_error("********** BAD VALUE **********"); } class AddressBookService final : public expcmake::AddressBook::Service { public: virtual ::grpc::Status GetAddress(::grpc::ServerContext* context, const ::expcmake::NameQuery* request, ::expcmake::Address* response) { std::cout << "Server: GetAddress for \"" << request->name() << "\"." << std::endl; Check_Value(request); // remaining are as like as before After building the project if from client side 5 or greater than 5 is given server didn't show any message but running continuously(which is obvious for the Wait function of gRPC) where my expectation was it should print in server console ********** BAD VALUE ********** Though, in client side I have got all passed value as BLANK where I can assume that, server didn't perform any process after the runtime_error. So my query is: 1/ How can I see the runtime_error message in server side console? 2/ Any gRPC default system to pass this incident to the client (Any generic message). Note: In my real example this runtime_error message related function is coming from another project where I cannot access to modify.
Found the solution. In server side I have missed to use the try ... catch in a right way. server.cpp try { Check_Value(request); } catch(const std::exception& e) { std::cout << e.what() << std::endl; // This will display the error message in server console return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what()); } An awesome resource regarding error handler in client side is found here. client.cpp // Class instance, message instances declaration grpc::Status status = stub->GetAddress(&context, request_, &response); if (status.ok()) // print server response, do the required job else std::cout << status.error_message() << std::endl;
71,156,078
71,156,293
Will friend injections be ill-formed?
There used to be a paragraph in the standard which stated that the names of a namespace-scope friend functions of a class template specialization are not visible during an ordinary lookup unless explicitly declared at namespace scope. Such names may be found under for associated classes. template <typename T> struct number { number(int); friend number gcd(number x, number y) { return 0; } }; void g() { number<double> a(3), b(4); a = gcd(a, b); // finds gcd becuase numer<double> is an associated class, // making gcd visible in its namespace (global scope) b = gcd(3, 4); // error: gcd is not visible } This feature has been used to capture and retrieve a metaprogramming state at compile time. template <int X> struct flag { friend consteval int f(flag<X>); }; template <int X, int N> struct injecter { friend consteval int f(flag<X>) { return N; } }; template <int N = 0, auto = []{}> consteval auto inject() { if constexpr (requires { f(flag<X>{}); }) { return inject<N+1>(); } else { void(injecter<X>{}); return f(flag<X>{}); } } static_assert(inject() == 0); static_assert(inject() == 1); static_assert(inject() == 2); static_assert(inject() == 3); // ... As far as I know, there is an issue from CWG which aimed to make such behaviour ill-formed although the mechanism for prohibiting them is as yet undetermined. However, as the paragraph seems to be absent from the latest draft, I'm wrondering if friend injections will be ill-formed in C++23.
From P1787R6: Merged [temp.inject] into [temp.friend] (Adopted in N4885 in March 2021) The current draft (N4901) reads ([temp.friend]p2): Friend classes, class templates, functions, or function templates can be declared within a class template. When a template is instantiated, its friend declarations are found by name lookup as if the specialization had been explicitly declared at its point of instantiation Which seems to cover the old [temp.inject]p2
71,156,246
71,156,623
How to propagate conan's compiler.cppstd setting to the compiler when building a library with CMake?
If you build a library with conan and set compiler.cppstd setting to e.g. 20 and call conan install, the libraries are still built with the default standard for the given compiler. The docs say: The value of compiler.cppstd provided by the consumer is used by the build helpers: The CMake build helper will set the CONAN_CMAKE_CXX_STANDARD and CONAN_CMAKE_CXX_EXTENSIONS definitions that will be converted to the corresponding CMake variables to activate the standard automatically with the conan_basic_setup() macro. So it looks like you need to call conan_basic_setup() to activate this setting. But how do I call it? By patching a library's CMakeLists.txt? I sure don't want to do that just to have the proper standard version used. I can see some recipes that manually set the CMake definition based on the setting, e.g.: https://github.com/conan-io/conan-center-index/blob/master/recipes/folly/all/conanfile.py#L117 https://github.com/conan-io/conan-center-index/blob/master/recipes/crc32c/all/conanfile.py#L58 https://github.com/conan-io/conan-center-index/blob/master/recipes/azure-storage-cpp/all/conanfile.py#L71 https://github.com/conan-io/conan-center-index/blob/master/recipes/caf/all/conanfile.py#L105 But this feels like a hack either. So what is the proper way to make sure libraries are built with the compiler.cppstd I specified?
Avoid patching, it's ugly and fragile, for each new release you will need an update due upstream's changes. The main approach is a CMakeLists.txt as wrapper, as real example: https://github.com/conan-io/conan-center-index/blob/5f77986125ee05c4833b0946589b03b751bf634a/recipes/proposal/all/CMakeLists.txt and there many others. cmake_minimum_required(VERSION 3.1) project(cmake_wrapper) include(conanbuildinfo.cmake) conan_basic_setup(KEEP_RPATHS) add_subdirectory(source_subfolder) The important thing here is including conanbuildinfo.cmake which is generated by cmake Conan generator, then the CMake helper will do the rest. The source_subfolder here is project source folder, then the main CMakeLists.txt will be loaded after configuring all Conan settings.
71,156,692
71,156,881
Will std::lower_bound be logarithmic for list<>?
Suppose I have a list<int> and maintaining it in ordered state. Can I isert new values into it with logarithmic complexity with code like this #include <iostream> #include <random> #include <list> #include <algorithm> using namespace std; ostream& operator<<(ostream& out, const list<int> data) { for(auto it=data.begin(); it!=data.end(); ++it) { if(it!=data.begin()) { out << ", "; } out << (*it); } return out; } int main() { const int max = 100; mt19937 gen; uniform_int_distribution<int> dist(0, max); list<int> data; for(int i=0; i<max; ++i) { int val = dist(gen); auto it = lower_bound(data.begin(), data.end(), val); data.insert(it, val); } cout << data << endl; } I would say not, because it is impossible to position iterator in list in O(1) but documentation says strange: The number of comparisons performed is logarithmic in the distance between first and last (At most log2(last - first) + O(1) comparisons). However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear. Notably, std::set and std::multiset iterators are not random access, and so their member functions std::set::lower_bound (resp. std::multiset::lower_bound) should be preferred. i.e. it doesn't recomment to use this function for set which is alterady search tree internally. Which containers this function is inteded to use then? How to insert and maintain sorted then?
Will std::lower_bound be logarithmic for list<>? No. Quote from documentation: for non-LegacyRandomAccessIterators, the number of iterator increments is linear. Which containers this function is inteded to use then? std::lower_bound is intended for any container that is - or can be - ordered, and doesn't have faster lower bound algorithm that relies on its internal structure - which excludes std::set and std::multiset as mentioned in the documentation.