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
74,256,801
74,259,525
C++ How do I get the next node to appear before the previous in a double linked list?
For example, my text file reads: A 1 A 3 B A 2 The goal is for the output to be 123, but I have gotten everything but that. #include <iostream> #include <string> #include <fstream> using namespace std; class Node { public: char letter; Node* next; Node* prev; Node(char cc) { letter = cc; next = prev = nullptr; } }; string command; char parameter; Node* p = nullptr; Node* rows[10]; int currentRow = 0; void main() { for (int i = 0; i < 10; i++) { rows[i] = new Node('.'); rows[i]->next = nullptr; rows[i]->prev = nullptr; } ifstream input("c:\\temp\\input.txt"); while (input.peek() != -1) { Node* c = rows[currentRow]; c = rows[currentRow]; while (c->next != nullptr) c = c->next; input >> command; if (command == "B") { // Back Curser //Moves curser back } else if (command == "F") { // Forward Curser //Moves curser forward } else if (command == "A") // Add char Done { input >> parameter; Node* newnode = new Node(parameter); c->next = newnode; newnode->prev = c; } } input.close(); // display linked list cout << endl; for (int i = 0; i < 10; i++) { Node* t = rows[i]->next; if (t != nullptr) { while (t != nullptr) { cout << t->letter; t = t->next; } cout << endl; } } } At first I had tried c = c->prev, but that did not work, as nothing was reorganized in my linked list. I also attempted to create a brand new node that was hopefully then filled by the upcoming character, but my logic did not add up to that, and I ran into multiple issues.
For the lack of implementation details in 'B', I'll just help you fix 'A' instead. You see, when moving the cursor back, you are now pointing to an element that already has a 'following node' (next is no longer nullptr) else if (command == "A") // Add char Done { input >> parameter; Node* newnode = new Node(parameter); newnode->next = c->next; //Link the new node to the previously following node (may be nullptr) c->next = newnode; newnode->prev = c; } Without the line I inserted, the previous next of c becomes inaccessible, leading to a memory leak.
74,257,055
74,257,072
Unable to delete instance variable array in C++
I am implementing a string class in C++, and I have come across an issue when trying to delete the char[] that contains the data of the string: class String { public: String(); String(char str[], int size); ~String(); void clear(); private: char *data; int size; }; String::String() { size = 0; } String::String(char str[], int _size) { data = str; size = _size; } String::~String() {} void String::clear() { if(size > 0) delete []data; size = 0; } int main() { char temp[] = {'a','b','c','d'}; String str(temp, 4); str.clear(); } This code results in an error, VSCode simply says "Exception has occurred. Unknown signal" and the program crashes once the delete []data line is reached. The program works without this line, but I want to prevent memory leaks. I've tried to declare a char* and assing that to new char[4], and from there populate each value one by one. This did nothing. Looking in the debugger, the correct array is assigned to data in str, so I memory does indeed seem to be allocated to the program, yet I just do not understand why I cannot delete the array. Is it const for some reason? Any thoughs?
You are trying to apply the operator delete to this array with automatic storage duration char temp[] = {'a','b','c','d'}; due to the constructor String::String(char str[], int _size) { data = str; size = _size; } that just copies the address of the first element of the array in the data member data. You need to allocate dynamically an array and copy the passed array in this dynamically allocated array. Pay attention to that the destructor deletes nothing String::~String() {} Also you need explicitly define at least the copy constructor and the copy assignment operator.
74,257,106
74,257,269
C++ Calling a function inside a function
I try to call a function in secim() because I want to shorten this function, but it gives a c3861 error. I try a lot of things, but every time it gives a different error. I thought it would be best to share the function without splitting it, because I don't know which way is true. I am new to programming, I think it's an easy problem, but I can't solve it. #include <iostream> using namespace std; int fact(int n) { // function to calculate factorial of a number if (n <= 1) return 1; return n * fact(n - 1); } int npr(int n, int r) { // finding permutation int pnr = fact(n) / fact(n - r); return pnr; } int combin(int n, int r) { int f1, f2, f3, y; f1 = fact(n); f2 = fact(r); f3 = fact(n - r); y = f1 / (f2 * f3); return y; } int secimm2(int s, int n, int r) { int ss; cout << "yeniden denemek ister misiniz 1-evet 2-hayir" << endl; cin >> ss; if (ss == 1) { return secim(); } else { return 0; } } int secim() { int s, n, r; cout << "islem seciniz\n1-faktoriyel\n2-perm\n3-kombinasyon\n"; cin >> s; if (s == 1) { cout << "1 adet sayi girin\ " << endl; cin >> n; cout << fact(n) << endl; return secimm2(s,n,r); } else if (s == 2) { cout << "2 adet sayi girin\n "; cin >> n; cin >> r; cout << npr(n, r) << endl; return secimm2(s, n, r); } else if (s == 3) { cout << "2 adet sayi girin\n "; cin >> n; cin >> r; cout << combin(n, r) << endl; return secimm2(s, n, r); } else { cout << "hatali giris tekrar dene\n" << endl; return secimm2(s, n, r); } } int main() { int s; cout << "islem seciniz\n1-faktoriyel\n2-perm\n3-kombinasyon\n"; cin >> s; cout << secim(); }
The compilator reads your code from top to bottom and will complain if it sees a function that isn't defined. For example: void foo() { bar(); // Error: What is bar()? Not declared yet. } void bar() { foo(); // OK: foo was declared and defined above. } The solution is to declare the function causing the issue before calling it: void bar(); // Tells that a method void bar() exists. But doesn't define it yet. void foo() { bar(); // OK: we know what bar() is: a call to the void bar() function. } void bar() { // Bar is now defined. Signature must follow declaration. foo(); // OK: foo was declared and defined above. } With your code, it gives the following fix: #include <iostream> using namespace std; int secim(); // Declares the secim function, but doesn't define it. int fact(int n) { // function to calculate factorial of a number if (n <= 1) return 1; return n * fact(n - 1); } int npr(int n, int r) { // finding permutation int pnr = fact(n) / fact(n - r); return pnr; } int combin(int n, int r) { int f1, f2, f3, y; f1 = fact(n); f2 = fact(r); f3 = fact(n - r); y = f1 / (f2 * f3); return y; } int secimm2(int s, int n, int r) { int ss; cout << "yeniden denemek ister misiniz 1-evet 2-hayir" << endl; cin >> ss; if (ss == 1) { return secim(); } else { return 0; } } int secim() { int s, n, r; cout << "islem seciniz\n1-faktoriyel\n2-perm\n3-kombinasyon\n"; cin >> s; if (s == 1) { cout << "1 adet sayi girin\ " << endl; cin >> n; cout << fact(n) << endl; return secimm2(s,n,r); } else if (s == 2) { cout << "2 adet sayi girin\n "; cin >> n; cin >> r; cout << npr(n, r) << endl; return secimm2(s, n, r); } else if (s == 3) { cout << "2 adet sayi girin\n "; cin >> n; cin >> r; cout << combin(n, r) << endl; return secimm2(s, n, r); } else { cout << "hatali giris tekrar dene\n" << endl; return secimm2(s, n, r); } } int main() { int s; cout << "islem seciniz\n1-faktoriyel\n2-perm\n3-kombinasyon\n"; cin >> s; cout << secim(); }
74,257,345
74,313,643
Which SYCL buffer constructors cause host write back on destruction?
SYCL buffers have the fun effect where when they are destroyed they may write back into the host memory from which they were formed. This is specified in 3.9.8.1 of the sycl 2020 standard: Buffer destruction: The destructors for sycl::buffer, sycl::unsampled_image and sycl::sampled_image objects wait for all submitted work on those objects to complete and to copy the data back to host memory before returning. These destructors only wait if the object was constructed with attached host memory and if data needs to be copied back to the host. sycl::buffer, has many constructors: buffer(const sycl::range<dimensions> &bufferRange, const sycl::property_list &propList = {}); ... buffer(T *hostData, const sycl::range<dimensions> &bufferRange, AllocatorT allocator, const sycl::property_list &propList = {}); buffer(const T *hostData, const sycl::range<dimensions> &bufferRange, const sycl::property_list &propList = {}); buffer(const T *hostData, const sycl::range<dimensions> &bufferRange, AllocatorT allocator, const sycl::property_list &propList = {}); buffer(const shared_ptr_class<T> &hostData, const sycl::range<dimensions> &bufferRange, AllocatorT allocator, const sycl::property_list &propList = {}); ... template <class InputIterator> buffer<T, 1>(InputIterator first, InputIterator last, AllocatorT allocator, const sycl::property_list &propList = {}); template <class InputIterator> buffer<T, 1>(InputIterator first, InputIterator last, const sycl::property_list &propList = {}); buffer(cl_mem clMemObject, const sycl::context &syclContext, event availableEvent = {}); But it does not specify directly, which ones do the copy on destruction method. For example, the iterator constructor, could be used with a range: std::vector<int> some_nums; // .. Fill the vector auto values = some_nums | ranges::filter([](int v) { return v % 2}; sycl::buffer<int, 1> buf{std::begin(values), std::end(values)}; This could be used to fill the buffer with all odd values. But if on buffer destruction the sycl subsystem attempts to write back to the range, this would be disastrous. How do we know which constructors cause this write to host on destruction?
Buffers are containers for data that can be read/written by both kernel and host. The destructor for a buffer can optionally write the data back to host memory, either by pointer or iterator. We can control the write-back of data using set_final_data() and set_write_back(). All the below buffer constructors can be used to write back to the host on destruction: buffer(T hostData, const sycl::range<dimensions> &bufferRange, const sycl::property_list &propList = {}); buffer(T *hostData, const sycl::range<dimensions> &bufferRange, AllocatorT allocator, const sycl::property_list &propList = {}); buffer(const T *hostData, const sycl::range<dimensions> &bufferRange, const sycl::property_list &propList = {}); buffer(const T *hostData, const sycl::range<dimensions> &bufferRange, AllocatorT allocator, const sycl::property_list &propList = {}); buffer(const shared_ptr_class<T> &hostData, const sycl::range<dimensions> &bufferRange, AllocatorT allocator, const sycl::property_list &propList = {}); buffer(const shared_ptr_class<T> &hostData, const sycl::range<dimensions> &bufferRange, const sycl::property_list &propList = {}); buffer(buffer<T, dimensions, AllocatorT> b, const id<dimensions> &baseIndex, const sycl::range<dimensions> &subRange); *Available only when: dimensions == 1 template <class InputIterator> buffer<T, 1>(InputIterator first, InputIterator last, AllocatorT allocator, const sycl::property_list &propList = {}); template <class InputIterator> buffer<T, 1>(InputIterator first, InputIterator last, const sycl::property_list &propList = {}); buffer(cl_mem clMemObject, const sycl::context &syclContext, event availableEvent = {});
74,257,533
74,257,596
Difference between std::decay and std::remove_cvref?
Does std::remove_cvref replace std::decay after C++20? From this link, I cannot understand what this means: C++20 will have a new trait std::remove_cvref that doesn't have undesirable effect of std::decay on arrays What is the undesirable effect of std::decay? Example and explanation, please!
std::remove_cvref does not replace std::decay. They are used for two different things. An array naturally decays into a pointer to its first element. std::decay will decay an array type to a pointer type. So, for example, std::decay<const char[N]>::type is const char*. Whereas std::remove_cvref removes const, volatile and & from a type without changing anything else about the type. So, for example, std::remove_cvref<const char[N]>::type is char[N] rather than char*.
74,257,626
74,257,769
how do i display a grid of images (and have them them transparent until a keyboard key is pressed)
any language. im wanting to make a program that will show what ability's im using in a game and have the picture of the ability's in a grid like ortholinear keyboard keys. it would be cool if the abilitys where tansparent untill the key is pressed then go opaque until i let go. iv been trying to find out how to do it with python but im not having much luck. i started with tkinter and i dont realy think that has the tools i need then i tryed matplotlib that seams tobe morefor data stuff if somone could point me in the right direction id appreciate it
I suggest you give this link a read: Monitor keypress in tkinter without focus You can refer to the answer that is not accepted, it shows how to accept key even if the program is not focus on. My suggestion is that, you create a "ability layout" in tkinter, then you assign the key of the ability layout to the actual keyboard. The background or layout opacity is constantly low, and once it is pressed, you trigger the opacity to be high. The problem you may face is that, you might get ban if you tried to run it, as we are unsure about the game ban mechanics.
74,258,394
74,258,971
How to install and call c++ library from folder other than /usr/local/include/
I have git cloned the package https://github.com/alex-mcdaniel/RX-DMFIT to a computing cluster directory. It requires the GNU computing library which I downloaded from https://www.gnu.org/software/gsl/ . The issue is make install gives cannot create directory '/usr/local/include/gsl': Permission denied as I don't have admin privileges on the cluster, so I would like to instead install the gsl library in a folder which I have permissions for, and tell the RX-DMFIT package where to look. The make file for RX-DMFIT is FILES = Constants.cpp Target.cpp bfield.cpp DM_profile.cpp \ greens.cpp diffusion.cpp dist.cpp psyn.cpp pIC.cpp \ emissivity.cpp surface_brightness_profile.cpp \ flux.cpp calc_sv.cpp run.cpp # prefix should point to location of darksusy prefix = /global/scratch/projects/general/RX-DMFIT/darksusy-6.3.1 LDLIBS = -lgsl -lgslcblas -ldarksusy -lFH -lHB -lgfortran example1: $(FILES) example1.cpp $(CXX) -o example1 $(FILES) example1.cpp \ -I/${prefix}/include -L/${prefix}/lib \ $(LDLIBS) example2: $(FILES) example2.cpp $(CXX) -o example2 $(FILES) example2.cpp \ -I/${prefix}/include -L/${prefix}/lib \ $(LDLIBS) How can I do this, and what modifications to the makefile are required?
This question contains two parts: How to install Gsl to a custom directory, and also how to modify the Makefile of RX-DMFIT to use Gsl from the custom directory. Install Gsl to a custom prefix To install Gsl into a custom directory, configure it to use a custom prefix before running make and make install. # Create a directory to be used as the custom prefix mkdir -p /path/to/custom/prefix # Configure gsl to use the custom prefix ./configure --prefix=/path/to/custom/prefix # Build and install make && make install Use Gsl from the custom prefix To use Gsl from the custom prefix, add -I/path/to/custom/prefix/include and -L/path/to/custom/prefix/lib to the command line arguments passed to the compiler. The -I flag tells the compiler to search for header files under the custom prefix, and the -L flag tells the compiler to search for (shared) libraries when linking the program. There are many ways to do so in the Makefile, and here's one of them: # Add this line under the "prefix = ..." line gsl_prefix = /path/to/custom/prefix # Add this line under every "-I/${prefix}/include -L/${prefix}/lib \" line # Be sure to include the "\" at the end -I${gsl_prefix}/include -L${gsl_prefix}/lib \
74,258,595
74,261,478
Fixing vector issue - Finding middle element of vector - C++
I'm trying to code an efficient method to which : The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers". I have the solution down for finding the middle number in a vector, but can't figure out a way to detect if the values received are more than 9. Obviously the vector will never be more than 9 since the vector gets resized in the loop and was wondering if anyone could guide me through a work around! Thank you in advance! Task description: Given a sorted list of integers, output the middle integer. A negative number indicates the end of the input (the negative number is not a part of the sorted list). Assume the number of integers is always odd. The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers". Input: 2 3 4 8 11 -1 Output: Middle item: 4 Input: 10 20 30 40 50 60 70 80 90 100 110 -1 Output: Too many numbers when input: 10 20 30 40 50 60 70 80 90 100 110 -1 is used, my output is: Middle item: 50 instead of Too many numbers #include <iostream> #include <vector> // Must include vector library to use vectors using namespace std; int main() { const int NUM = 9; vector<int> numInts(NUM); int value; //fills loop in with values for ( int i = 0; i < numInts.size(); ++i){ cin >> value; if (value > 0){ numInts.at(i) = value; } else{ numInts.resize(i); break; } } //outputs vector if within size -- but will always be in size(need to fix) if (numInts.size() > 9){ cout << "Too many numbers" << endl; } else{ cout << "Middle item: " << numInts.at(numInts.size()/2) << endl; } return 0; }
I tried to reimplement your code so it will work as you want. Ask me if you feel that this code doesn't seems right to you. #include <iostream> #include <vector> using namespace std; int main() { vector<int> nums(10); int value=0; int numberOfElements=0; bool moreThanNine=false; while(cin>>value) { if(value==-1) { break; } else { numberOfElements++; if(numberOfElements>9) { moreThanNine=true; } else { nums.at(numberOfElements-1) = value; } } } if(moreThanNine) { cout << "Too many numbers" << endl; } else { cout << "Middle item: " << nums.at(numberOfElements/2) << '\n'; } return 0; }
74,258,955
74,259,760
How to check if a particular overloaded function exists, using the decltype or declval
I wrote the following code, here as msg_hdr() function has 2 overloads, which makes decltype unusable. Instead of decltype, I have also tried invoke_result_t as well as result_of_t, but nothing seems to work. What changes should I make in the code to make it work. struct Header { int i; int j; }; struct Data { Header& msg_hdr() { return this->_msg_hdr; } const Header& msg_hdr() const { return this->_msg_hdr; } private: Header _msg_hdr; int k; }; template<typename, typename = void> constexpr bool has_msg_hdr = false; template<typename St> constexpr bool has_msg_hdr<St, std::enable_if_t<std::is_same_v<decltype(St::msg_hdr), Header>>> = true; template<typename St> constexpr void check(St s) { if constexpr(has_msg_hdr<std::remove_const_t<std::remove_reference_t<St>>>) { std::cout << "has msg_header \n"; } else { std::cout << "no msg_header \n"; } } int main(int argc, char** argv) { Data d; check(d); return 0; }
We can use this trick to detect particular overload function. template <typename T, typename... Args> class has_msg_hdr { template <typename C, typename = decltype( std::declval<C>().msg_hdr(std::declval<Args>()...) )> static std::true_type test(int); template <typename C> static std::false_type test(...); public: static constexpr bool value = decltype(test<T>(0))::value; }; Test code. std::cout << std::boolalpha << has_msg_hdr<Data>::value << " " << has_msg_hdr<Data,int>::value << std::endl;
74,260,053
74,260,139
Call a class's function template with function pointers as parameters
I'd want to use a function pointer in my template argument list. I do miss something of B even I am writing int in full main of both A and B. I have a class X.h like so, don't know which one it is now causing the error. struct X { int fun(int a) { return a; } template<typename A, typename B> A func(int x, B(*f)(int)) { A i = 10; return i + f(x); } }; and I like to use it in main.cpp int main() { X d; std::cout << d.func<int, int>(10, &X::fun) << "\n"; return 0; } The error is No instance of func matches the argument list...
The problem is that the argument &X::fun is of type int (X::*)(int) while the parameter f is of type int(*)(int) (when B = int) and there is no implicit conversion from the former to the latter and hence the error. To solve this you can change the parameter f to be of type B(X::*)(int) as shown below. Note that the syntax for making a call using member function pointer is different for making a call to a free function. With C++17, we can use std::invoke. struct X { int fun(int a) { return a; } template<typename A, typename B> //------------------vvvv-------------->added this X:: here A func(int x, B(X::*f)(int)) { A i = 10; //-----------------vvvvvvvvvv-------->this is the syntax to call using member function pointer return i + (this->*f)(x); //return std::invoke(f, this, x); //use std::invoke with C++17 } }; int main() { X d; std::cout << d.func<int, int>(10, &X::fun) << "\n"; //works now return 0; } Working demo
74,260,112
74,260,337
Why does std::views::split() compile but not split with an unnamed string literal as a pattern?
When std::views::split() gets an unnamed string literal as a pattern, it will not split the string but works just fine with an unnamed character literal. #include <iomanip> #include <iostream> #include <ranges> #include <string> #include <string_view> int main(void) { using namespace std::literals; // returns the original string (not splitted) auto splittedWords1 = std::views::split("one:.:two:.:three", ":.:"); for (const auto word : splittedWords1) std::cout << std::quoted(std::string_view(word)); std::cout << std::endl; // returns the splitted string auto splittedWords2 = std::views::split("one:.:two:.:three", ":.:"sv); for (const auto word : splittedWords2) std::cout << std::quoted(std::string_view(word)); std::cout << std::endl; // returns the splitted string auto splittedWords3 = std::views::split("one:two:three", ':'); for (const auto word : splittedWords3) std::cout << std::quoted(std::string_view(word)); std::cout << std::endl; // returns the original string (not splitted) auto splittedWords4 = std::views::split("one:two:three", ":"); for (const auto word : splittedWords4) std::cout << std::quoted(std::string_view(word)); std::cout << std::endl; return 0; } See live @ godbolt.org. I understand that string literals are always lvalues. But even though, I am missing some important piece of information that connects everything together. Why can I pass the string that I want splitted as an unnamed string literal whereas it fails (as-in: returns a range of ranges with the original string) when I do the same with the pattern?
String literals always end with a null-terminator, so ":.:" is actually a range with the last element of \0 and a size of 4. Since the original string does not contain such a pattern, it is not split. When dealing with C++20 ranges, I strongly recommend using string_view instead of raw string literals, which works well with <ranges> and can avoid the error-prone null-terminator issue.
74,261,052
74,261,151
Consider Vector of Child Pointers as Vector of Base Pointers
Suppose there are the following classes: class A { }; class B: public A { }; and the vector of unique_ptr to B: std::vector<std::unique_ptr<B>> bElements Is there a possibility to pass the vector to a function that accepts std::vector<std::unique_ptr<A>>& as a parameter
No. A std::vector<Foo> has no special relation to a std::vector<Bar> no matter what is the relation between Foo and Bar. They are two distinct completely different types. The fact that they are instantiations of the same class template is not relevant when you are asking for an exact type of argument of the function. Thouh, the fact that they are instantiations of the same template enables you to employ duck typing. Make the function a function template. It can take either a std::vector<std::unique_ptr<T>> or simply a container of type C, or iterators of type Iter. As you know the base class B you know how the ducks walk and how the ducks quack and can implement the function template so it will work with either std::vector<std::unique_ptr<A>> or std::vector<std::unique_ptr<B>>. ("the ducks" is the classes inheriting from A and "how they walk and how they quack" is the interface of A)
74,262,068
74,262,135
couldnt connect to active directory on windows 2019 server
I am working on active directory and was reading this https://learn.microsoft.com/en-us/windows/win32/adsi/setting-up-c---for-adsi-development and just used the mentioned code to connect to it but its not connecting to the server and says proccess exited with status code zero i used the below code. #include "stdafx.h" #include "activeds.h" int main(int argc, char* argv[]) { HRESULT hr; IADsContainer *pCont; IDispatch *pDisp=NULL; IADs *pUser; // Initialize COM before calling any ADSI functions or interfaces. CoInitialize(NULL); hr = ADsGetObject( L"LDAP://CN=users,DC=fabrikam,DC=com", IID_IADsContainer, (void**) &pCont ); if ( !SUCCEEDED(hr) ) { return 0; } } what am i doing wrong i did exactly as the documentation told
ADsGetObject is for non authenticated connection that is the code should be performed inside the server. if you are trying to connect to a server hosted on seperate machine you should be using ADsOpenObject you may have the reference in the following link https://learn.microsoft.com/en-us/windows/win32/api/adshlp/nf-adshlp-adsopenobject ADsOpenObject binds using explicit username and password you can try the following int login(LPCWSTR uname, LPCWSTR pass) { HRESULT hr; IADsContainer* pCont; IDispatch* pDisp = NULL; IADs* pUser; // Initialize COM before calling any ADSI functions or interfaces. CoInitialize(NULL); hr = ADsOpenObject(L"LDAP://machinename.domaincontroller.domain/CN=Users,DC=domaincontrollername,DC=domainname", uname, pass, ADS_SECURE_AUTHENTICATION, // For secure authentication IID_IADsContainer, (void**)&pCont); std::cout << hr << std::endl; std::string message = std::system_category().message(hr); std::cout << message << std::endl; if (!SUCCEEDED(hr)) { return 0; } else { return 1; } } instead of the variable you can type your username and password like L"usernameexample"
74,262,125
74,262,401
Difference between template argument deduction for classes and functions
What the problem is: I'm trying to implement a class that will have two specializations, one for integral types and one for all others. The first version that came to my mind: #include <type_traits> template<typename T, typename std::enable_if_t<std::is_integral<T>::value, bool> = true> class Test { }; template<typename T, typename std::enable_if_t<!std::is_integral<T>::value, bool> = true> class Test { }; But GCC fails with the following error when I try to compile the code above: <source>:2:84: error: template parameter 'typename std::enable_if<std::is_integral<_Tp>::value, bool>::type <anonymous>' template<typename T, typename std::enable_if_t<std::is_integral<T>::value, bool> = true> ^~~~ <source>:6:85: note: redeclared here as 'typename std::enable_if<(! std::is_integral<_Tp>::value), bool>::type <anonymous>' template<typename T, typename std::enable_if_t<!std::is_integral<T>::value, bool> = true> ^~~~ However, using a similar technique for functions compiles without problems: #include <type_traits> template<typename T, typename std::enable_if_t<std::is_integral<T>::value, bool> = true> void test() { } template<typename T, typename std::enable_if_t<!std::is_integral<T>::value, bool> = true> void test() { } What I am trying to achieve: First of all, I want to understand why the version with functions compiles, but the version with classes does not. My second goal is to implement a class that satisfies the conditions that I specified at the very beginning. What I have tried: Using partial specializations solves problem 2: #include <type_traits> template<typename T, bool = std::is_integral<T>::value> class Test; template<typename T> class Test<T, true> { }; template<typename T> class Test<T, false> { }; But this approach is bad because it allows to use Test<float, true> and if I understand correctly (please correct me if I'm wrong), then specialization for integral types will be used, which is not what I want. Summarizing: I'll just duplicate my goals in the form of questions: Why does the version with functions compile, but the version with classes doesn't? How can I implement a class that satisfies the conditions that I specified at the very beginning?
Using std::enable_if in the template parameter list of a class is not guaranteed, since the standard only has SFINAE for functions, not for types. For types it may be available, but only as a non-standard compiler extension. C++20 adds concepts to the standard, which does work for template parameters on template classes too. template<class T> concept NotIntegral = !std::integral<T>; template<class T> class Test; template<std::integral T> class Test<T> { public: void operator()() const { std::cout << "integral\n"; } }; template<NotIntegral T> class Test<T> { public: void operator()() const { std::cout << "not integral\n"; } }; int main() { std::cout << "float: "; (Test<float>{})(); std::cout << "int: "; (Test<int>{})(); } For prior versions of C++ you could add a static_assert to the class body which doesn't prevent the user from specifying an invalid value for the second template parameter, but at least compiling the code will yield a compiler error of your choosing: template<typename T> class Test<T, true> { static_assert(std::is_integral_v<T>, "The second template parameter must contain true if and only if the first template parameter is an integral type"); }; You could introduce a function for creating a the object instead of providing allowing the user to create objects with invalid template parameters though: template<typename T, bool = std::is_integral<T>::value> class Test; template<class T> Test<T, std::is_integral<T>::value> MakeTest() { return {}; } template<typename T> class Test<T, true> { friend Test<T, std::is_integral<T>::value> MakeTest<T>(); Test() = default; public: void operator()() const { std::cout << "integral\n"; } }; template<typename T> class Test<T, false> { friend Test<T, std::is_integral<T>::value> MakeTest<T>(); Test() = default; public: void operator()() const { std::cout << "not integral\n"; } }; int main() { std::cout << "float: "; MakeTest<float>()(); std::cout << "int: "; MakeTest<int>()(); // Test<int, false> test; // would yield a compiler error because of the inaccessible default constructor }
74,262,202
74,289,802
How to add C++ QQuickPaintedItem in QML
I want to add C++ class like this notchedrectangle.hpp to QML: #ifndef NOTCHEDRECTANGLE_HPP #define NOTCHEDRECTANGLE_HPP #include <QtQml/qqmlregistration.h> #include <QQuickPaintedItem> class NotchedRectangle : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) QML_ELEMENT public: NotchedRectangle(); void paint(QPainter* painter) override; QColor color() const; void setColor(QColor color); signals: void colorChanged(); private: QColor m_color; }; #endif // NOTCHEDRECTANGLE_HPP I have qmake build system, but don't know - what should I add in qmake file. My filesystem looks like that: I tried to add to qmake file this strings: CONFIG += qmltypes QML_IMPORT_NAME = UI.NR QML_IMPORT_MAJOR_VERSION = 1 INCLUDEPATH += UI/NotchedRectangle But they will cause error: [Makefile.Debug:1175: qlauncher_metatypes.json] Error 1 Can you help me, please?
QML_IMPORT_NAME is not a name of class! It's the name of package and must be different. I use "Custom". Next you must include class in main.cpp And finally - you should make Recompile
74,262,609
74,263,152
Pass integer argument to slot function for QPushButton
I'm trying to pass an integer argument to a function using the connect() method in QtCreator. I'm creating a game where the user will be able to select one of three game setting options. They can click either button 1, button 2, or button 3, and an integer (1, 2, or 3) corresponding to the setting they picked should be passed to the function setDesiredSetting(). I know that it's possible to pass arguments to slots - I believe my problem is similar to this Qt 5 assign slot with parameters to a QPushButton and I tried to use QSignalMapper as the solution suggested. The issue is, when I go to run my program and I click on button 1 to test, it seems the setDesiredSetting() function never gets called because I don't see the qInfo print statement being printed to the terminal with the desired setting number. Because of this, I can't seem to test if the integer argument was successfully passed. Code: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QLineEdit> #include <QSignalMapper> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); private: Ui::MainWindow *ui; private slots: void setDesiredSetting(int desiredSetting); }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Desired game theme selected QSignalMapper mapper; connect(ui->themeOneButton, SIGNAL(released()), &mapper, SLOT (map())); mapper.setMapping(ui->themeOneButton, 1); connect(&mapper, SIGNAL(mapped(int)), this, SLOT (setDesiredSetting(int))); //connect(ui->themeTwoButton, &QPushButton::clicked, this, &MainWindow::setDesiredSetting(2)); //connect(ui->themeThreeButton, &QPushButton::clicked, this, &MainWindow::setDesiredSetting(3)); } void MainWindow::setDesiredSetting(int desiredSetting) { qInfo("Setting selected: %d \n", desiredSetting); }
First things first, why do you use the old SIGNAL and SLOT macros when you seem to already be aware of the new signal/slot syntax ? There is no such mapped() signal in QSignalMapper class (so obviously, it cannot work). Maybe QSignalMapper::mappedInt() is what you wanted ? If you used the proper signal/slot connection syntax instead of the old macros, you would have received a nice compile-time error indicating that the signal you gave doesn't even exist. In case you didn't know, you can use a lambda function instead of a QSignalMapper, it would make the code much clearer and simpler. For example: connect(ui->themeOneButton, &QPushButton::clicked, [&](){ qInfo() << "Selected setting: " << desiredSetting; }); Of course the above code sample assumes the desiredSetting variable is accessible in this scope so that the lambda function can get a reference to it. (But since you didn't mention how and where the user choice for the desired settings is made, there might be something more to fix) Note: if the variable is not guaranteed to be available every time the lambda slot is called, you shall get the value by copy instead of by reference.
74,263,199
74,263,521
Issue on using multiple structures by pointers cause crash on program executing
Hello I noticed this weird issue when using multiple pointer structures at the same time. Can somebody explain to me what is causing it ? #include <iostream> using namespace std; typedef struct A{ int x; }a; int main() { a *a1, *a2; a1->x = 3; cout << a1->x << endl; // display "3" a2->x = 2; cout << a2->x << endl; // ...does not display "2" ??? return 0; }
Before assigning the values to your pointers, the pointers have to be initialized properly. a *a1, *a2; These pointers are not initialized. They point to some random location in memory. The "new" keyword allocates memory for your structure. You can use it like this: a *a1 = new A, *a2 = new A;
74,263,291
74,265,943
How to mesh a 2D point cloud in C++
I have a set of 2D points of a known density I want to mesh by taking the holes in account. Basically, given the following input: I want something link this: I tried PCL ConcaveHull, but it doens't handle the holes and splitted mesh very well. I looked at CGAL Alpha shapes, which seems to go in the right direction (creating a polygon from a point cloud), but I don't know how to get triangles after that. I though of passing the resulting polygons to a constrained triangulation algorithm and mark domains, but I didn't find how to get a list of polygons.
The resulting triangulated polygon is about a two step process at the least. First you need to triangulate your 2D points (using something like a Delaunay2D algorithm). There you can set the maximum length for the triangles and get the the desired shape. Then you can decimate the point cloud and re-triangulate. Another option is to use the convex hull to get the outside polygon, then extract the inside polygon through a TriangulationCDT algorithm, the apply some PolygonBooleanOperations, obtain the desired polygon, and finaly re-triangulate. I suggest you look into the Geometric Tools library and specifically the Geometric Samples. I think everything you need is in there, and is much less library and path heavy than CGAL (the algorithms are not free for this type of work unless is a school project) or the PCL (I really like the library for segmentation, but their triangulation breaks often and is slow). If this solves your problem, please mark it as your answer. Thank you!
74,263,416
74,263,681
Question about `has_const_iterator`/`has_begin_end`
The following code comes from cxx-prettyprint , which implements detecting whether type T has a corresponding member #include<iostream> #include<vector> #include<type_traits> using namespace std; struct sfinae_base { using yes = char; using no = yes[2]; }; template <typename T> struct has_const_iterator : private sfinae_base { private: template <typename C> static yes& test(typename C::const_iterator*); template <typename C> static no& test(...); public: static const bool value = sizeof(test<T>(nullptr)) == sizeof(yes); using type = T; }; template <typename T> struct has_begin_end : private sfinae_base { private: template <typename C> static yes& f(typename std::enable_if< std::is_same<decltype(static_cast<typename C::const_iterator(C::*)() const>(&C::begin)), typename C::const_iterator(C::*)() const>::value>::type*); template <typename C> static no& f(...); template <typename C> static yes& g(typename std::enable_if< std::is_same<decltype(static_cast<typename C::const_iterator(C::*)() const>(&C::end)), typename C::const_iterator(C::*)() const>::value, void>::type*); template <typename C> static no& g(...); public: static bool const beg_value = sizeof(f<T>(nullptr)) == sizeof(yes); static bool const end_value = sizeof(g<T>(nullptr)) == sizeof(yes); }; int main() { vector<int> sa{ 1,2,3,4,5 }; cout << has_const_iterator<vector<int>>::value; cout<<has_begin_end<vector<int>>::beg_value; cout << has_begin_end<vector<int>>::end_value; return 0; } run it online Some time later I read someone else's blog and changed it to this #include<utility> #include<iostream> #include<vector> using namespace std; template <typename T> struct has_const_iterator { private: template <typename U> static constexpr decltype(std::declval<U::const_iterator>(), bool()) test(int) { return true; } template <typename U> static constexpr bool test(...) { return false; } public: static const bool value = test<T>(1); //为什么这个不对? using type = T; }; template <typename T> struct has_begin_end { private: template <typename U> static constexpr decltype(std::declval<U>().begin(), bool()) f(int) { return true; } template <typename U> static constexpr bool f(...) { return false; } template <typename U> static constexpr decltype(std::declval<U>().end(), bool()) g(int) { return true; } template <typename U> static constexpr bool g(...) { return false; } public: static bool const beg_value = f<T>(2); static bool const end_value = g<T>(2); }; int main() { vector<int> sa{ 1,2,3,4,5 }; cout << has_const_iterator<vector<int>>::value; cout<<has_begin_end<vector<int>>::beg_value; cout << has_begin_end<vector<int>>::end_value; return 0; } run it online For the first piece of code it shows 111 For the second piece of code it shows 011 Snippet 2 was working fine a few months ago, but not now. My question is, what's wrong with the second one,and why it was good before and now goes wrong? Added: I found this, what does he mean by introduce ODR violations?
If you force a call the overload of has_const_iterator::test that returns true (by removing the other): #include <utility> #include <vector> #include <iostream> template <typename T> struct has_const_iterator { private: template <typename U> static constexpr decltype(std::declval<U::const_iterator>(), bool()) test(int) { return true; } //template <typename U> //static constexpr bool test(...) { return false; } public: static const bool value = test<T>(1); }; int main() { std::cout << has_const_iterator<std::vector<int>>::value; } then you get this error message (more or less): error: dependent-name 'U::const_iterator' is parsed as a non-type, but instantiation yields a type note: say 'typename U::const_iterator' if a type is meant It tells you exactly what's wrong: typename is missing before U::const_iterator. The reason is that U::const_iterator is a dependent name (it could be a type or a variable, for example, depending on what U is exactly), so you need to specify that it refers to a type. Note that the previous version does use typename: template <typename C> static yes& test(typename C::const_iterator*); //-------------------------------------^^^^^^^^ This version works: #include <utility> #include <vector> #include <iostream> template <typename T> struct has_const_iterator { private: template <typename U> static constexpr decltype(std::declval<typename U::const_iterator>(), bool()) test(int) { return true; } template <typename U> static constexpr bool test(...) { return false; } public: static const bool value = test<T>(1); }; int main() { std::cout << has_const_iterator<std::vector<int>>::value; } Demo
74,263,795
74,273,834
Speed problems with realtime recording with libavcodec and libavformat
I am trying to use libavcodec and libavformat to write an mp4 video file in realtime using h264. I am using an approach heavily inspired by this answer here This works well as a non-realtime solution however, avcodec_receive_packet() starts running much slower after 20 frames or so (this is usually around the first time it returns success and thus av_interleaved_write_frame() is called for the first time). This is so slow that my writing cannot work in realtime. Solutions I have tried: Enabling multithreading on my codec context Running avcodec_receive_packet() and av_interleaved_write_frame() on a separate thread to my capture from the realtime video source Changing the gop_size in the video context Lowering my bitrate in the video context Is there anything I'm missing? Possibly some fundamental rules to capturing video in realtime. I am not very experienced with programming with video.
I have solved this by not using h.264 encoding and instead using libavcodec's mpeg2video encoder. This leads to a much larger file size however the frame by frame encoding has a much more consistent processing time. Thanks to @G.M.'s comment for that. I have not yet tested any other encoders so possibly those could be helpful too. Another possible solution was using GPU acceleration as mentioned by @VC.One, however for my use case, this was not feasible due to the target hardware for this to run not being known. A possible hybrid method is to determine the target hardware in the code and enable H.264 with GPU processing if a powerful enough GPU is available and to use mpeg2video encoding if not.
74,263,931
74,264,142
Why is there a difference between templated recursive calls and fold expressions with type cast or promotion?
#include <array> #include <type_traits> #include <iostream> template<class... Types> class Test { public: Test() : format_({ [&] { if constexpr(std::is_same_v<Types, int64_t>) { return "%ld "; } else if constexpr(std::is_same_v<Types, int32_t>) { return "%d "; } else if constexpr(std::is_same_v<Types, double>) { return "%f "; } }() ... }) {} template<typename T, typename ... Args> void print_recursive(T && v, Args && ... args) { size_t i = sizeof...(Types) - sizeof...(args) - 1; printf(format_[i], std::forward<T>(v)); if constexpr(sizeof...(Args) > 0) { print_recursive(std::forward<Args>(args)...); } else { printf("\n"); } } void print_fold(Types && ... args) { size_t i = 0; ([&]{ printf(format_[i++], args); }(), ...); printf("\n"); } private: std::array<const char*, sizeof...(Types)> format_; }; int main() { Test<int64_t, int32_t, double> t; t.print_recursive(1.0, 2, 3.0); t.print_fold(1.0, 2, 3.0); } OUTPUT: 0 2 3.000000 1 2 3.000000 Built and ran with the following: g++ test.cpp -o test -std=c++17 && ./test Compiler Info: $ gcc --version gcc (GCC) 9.2.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In the above example, the format_ array is defined using fold expressions and used in both print calls. Each print call has the same format specifier for the same index. Each print call has the same args past to it as well. However the output is different for the two. Why is that the case? EDIT: Adding the correct recursive call that will convert the function arguments to the class template types first before making the recursive call as recommended by @n. m. void print_recursive(Types && ... args) { print_recursive_impl(std::forward<Types>(args)...); } template<typename T, typename ... Args> void print_recursive_impl(T && v, Args && ... args) { size_t i = sizeof...(Types) - sizeof...(args) - 1; printf(format_[i], std::forward<T>(v)); if constexpr(sizeof...(Args) > 0) { print_recursive_impl(std::forward<Args>(args)...); } else { printf("\n"); } }
You print double as an integer in the recursive call. That's a UB or some other nonsense. In the fold version you convert them to the appropriate types first.
74,263,987
74,264,156
Wrong cost adjacency matrix
I try to obtain the adjacency matrix of weights, and then use it in the calculation of the minimum weight path. There is a problem, when I try to display it, I get a wrong result : By logic, the diagonal must have only 0, and in the places where the vertices are adjacent, must be the weight of the edge //set the source and destination of each edge g->edge[0]->src = 0; g->edge[0]->dest = 1; g->edge[0]->weight = 9; g->edge[1]->src = 0; g->edge[1]->dest = 10; g->edge[1]->weight = 6; g->edge[2]->src = 1; g->edge[2]->dest = 2; g->edge[2]->weight = 3; g->edge[3]->src = 1; g->edge[3]->dest = 10; g->edge[3]->weight = 2; g->edge[4]->src = 2; g->edge[4]->dest = 3; g->edge[4]->weight = 2; g->edge[5]->src = 2; g->edge[5]->dest = 6; g->edge[5]->weight = 3; g->edge[6]->src = 2; g->edge[6]->dest = 5; g->edge[6]->weight = 3; g->edge[7]->src = 3; g->edge[7]->dest = 4; g->edge[7]->weight = 5; g->edge[8]->src = 4; g->edge[8]->dest = 5; g->edge[8]->weight = 4; g->edge[9]->src = 6; g->edge[9]->dest = 10; g->edge[9]->weight = 2; g->edge[10]->src = 6; g->edge[10]->dest = 7; g->edge[10]->weight = 9; g->edge[11]->src = 7; g->edge[11]->dest = 8; g->edge[11]->weight = 7; g->edge[12]->src = 7; g->edge[12]->dest = 9; g->edge[12]->weight = 2; g->edge[13]->src = 8; g->edge[13]->dest = 9; g->edge[13]->weight = 7; g->edge[14]->src = 9; g->edge[14]->dest = 10; g->edge[14]->weight = 5; My code : for (i = 0; i < numberOfVertices; i++) { adjacency_matrix[i][i] = 0; for (j = i + 1; j < numberOfVertices; j++) { adjacency_matrix[i][j] = g->edge[i]->weight; adjacency_matrix[j][i] = g->edge[i]->weight; } } What's wrong?
for (i = 0; i < numberOfVertices; i++) { adjacency_matrix[i][i] = 0; for (j = i + 1; j < numberOfVertices; j++) { adjacency_matrix[i][j] = g->edge[i]->weight; adjacency_matrix[j][i] = g->edge[i]->weight; } } In this code you are setting every edge from vertex i to every other vertex to the same weight. I do not think this is what you want. ( Note: It is hard to know what you do want. When reporting a problem you need to include a description of both what happens AND what you wanted to happen. "It's wrong!" is almost useless as a bug report. )
74,264,154
74,264,211
Does value-initialization use the implicit default constructor?
According to this site /link/: If the default constructor is explicitly declared but marked as deleted, empty brace initialization can't be used: and it also gives an example to this: class class_f { public: class_f() = delete; class_f(string x): m_string { x } {} // if it is deleted, there will be no errors. string m_string; }; int main() { class_f cf{ "hello" }; class_f cf1{}; // compiler error C2280: attempting to reference a deleted function } What I don't really understand is that, if there is no user-provided constructor, there will be no more error, even if the deleted default constructor is still there. As far as I know, if there is a user-provided constructor, there will be no implicit default constructors, but the default constructor is already deleted. So I don't know what is called in case of the value-initialization and why it is works in the example below: #include <string> class class_f { public: class_f() = delete; std::string m_string; }; int main() { class_f cf1{}; // Does the implicit-default constructor is called here? But, it is deleted or not? }
There is a difference between the C++ 17 Standard and the C++ 20 Standard according to the definition of aggregates. According to the C++ 17 Standard this declaration class class_f { public: class_f() = delete; std::string m_string; }; declares an aggregate that you may initialize using braces. From the C++ 17 Standard (11.6.1 Aggregates) 1 An aggregate is an array or a class (Clause 12) with (1.1) — no user-provided, explicit, or inherited constructors (15.1), (1.2) — no private or protected non-static data members (Clause 14), (1.3) — no virtual functions (13.3), and (1.4) — no virtual, private, or protected base classes (13.1). According to the C++ 20 Standard this declaration does not declare an aggregate and compiler will issue an error relative to the object initialization. From the C++ 20 Standard (9.4.2 Aggregates) 1 An aggregate is an array or a class (Clause 11) with (1.1) — no user-declared or inherited constructors (11.4.5), (1.2) — no private or protected direct non-static data members (11.9), (1.3) — no virtual functions (11.7.3), and (1.4) — no virtual, private, or protected base classes (11.7.2). You can try the following demonstration program #include <iostream> #include <iomanip> #include <type_traits> class class_f { public: class_f() = delete; std::string m_string; }; int main() { std::cout << "std::is_aggregate_v<class_f> = " << std::boolalpha << std::is_aggregate_v<class_f> << '\n'; } Run it setting a compiler option to support C++ 17 and then to support C++ 20. The type trait std::is_aggregate was introduced in C++ 17.
74,264,539
74,265,249
Remove repeated code in function definition
this is my first question, so I may miss the "correct structure". Anyway, I have a header file, with a function. This function (void readFile()) is defined in a cpp file. Within this definition I have code which repeats itself a lot. If it was in main, I would simply declare a new function, define the repeatable in it, and then call everytime the function. But since it's in a non-main cpp file, I am having issues with this process. Basically, what my function does, is read through a file char by char, and saves the data to different objects, based on the text. My code looks like: source.open("bookings.txt", std::ios::in); char c; source.get(c); while (c != '|'){ CurrentID.push_back(c); source.get(c); } object.setID(CurrentID) This code repeats itself, replacing only the line of "object.setID". I tried declaring function "search(std::ifstream x, char y, std::string z);" with definition void Search(std::ifstream x, char y, std::string z){ x.get(y); // next after | while (y != '|'){ z.push_back(y); x.get(y); } } But if I try to call this function within my "void readFile()" definition, like this: // First block as a repeatable source.get(c); while (c != '|'){ CurrentID.push_back(c); source.get(c); } object->setID(CurrentID) CurrentID.clear(); // second block as a function, with repeatable code commented out void Search(std::ifstream quelle, char c, std::string &CurrentID); /* source.get(c); while (c != '|'){ CurrentID.push_back(c); source.get(c); }*/ object->setPrice(stof (CurrentID)); CurrentID.clear(); It jumps from "CurrentID.clear()" in first block, directly to "object->setPrice" in second block, ignoring the existence of the void Search function. Any proposition how to make the function work, or maybe other way, to remove repeated code?
I don't know if this will exactly answer your question. If not, please post your entire code, especially the readFile function. Let's say you want a readFile function to: parse an input stream, and fill the fields ID (string) and price (float) of a list of object structs, the values in the stream being separated by a | character, and, using a second function readToken for the repeated code (i.e., read from the input stream until the separator is found and return a string). The code below does that. Notice: you define readFile and readToken as separate functions, and both change the state of the input stream. [Demo] #include <iostream> #include <sstream> #include <string> // stof #include <vector> struct object { std::string id; float price; }; std::string readToken(std::istringstream& iss) { std::string ret{}; char c{}; while (true) { iss >> c; if (not iss.eof() and c != '|') { ret.push_back(c); } else { return ret; } } } std::vector<object> readFile(std::istringstream& iss) { std::vector<object> ret{}; while (not iss.eof()) { auto id = readToken(iss); auto price = std::stof(readToken(iss)); ret.emplace_back(id, price); } return ret; } int main() { std::istringstream input{"ID1|25.5|ID2|3.14"}; auto objects = readFile(input); for (const auto& o : objects) { std::cout << o.id << ", " << o.price << "\n"; } } // Outputs: // // ID1, 25.5 // ID2, 3.14 A simpler way to do this would be to have std::getline read tokens: [Demo] std::vector<object> readFile(std::istringstream& iss) { std::vector<object> ret{}; while (not iss.eof()) { std::string id{}; std::getline(iss, id, '|'); std::string price_str{}; std::getline(iss, price_str, '|'); auto price = std::stof(price_str); ret.emplace_back(id, price); } return ret; }
74,264,990
74,265,056
Getting odd number between two number
The rule is I need to display the odd number between two number that the user inputted. But my code have problem. For example when i input: 3 and 11 The output is 5 7 9 11 11 should not be included because that's what the user input even it is odd number. The rule is between. 5 7 9 is my target. i'm thinking if it's because of my formula or the way i increment it. First try: i increment numOne before "if" #include <iostream> using namespace std; int main() { int numOne,numTwo; cout << "Please Enter First Number : "; cin >> numOne; cout << "Please Enter Second Number ( Should be greater than first number) : " ; cin >> numTwo; cout << "Odd Numbers Between are: "; while (numOne<numTwo) { numOne++; if ( numOne % 2 == 1) { cout<<numOne<<" "; } } return 0; } The output is: 5 7 9 11 -still wrong because 11 should not be include- :( **Second try: i increment numOne below "if" #include <iostream> using namespace std; int main() { int numOne, numTwo; cout << "Please Enter First Number : "; cin >> numOne; cout << "Please Enter Second Number ( Should be greater than first number) : " ; cin >> numTwo; cout << "Odd Numbers Between are: "; while (numOne<numTwo) { if ( numOne % 2 == 1) { cout<<numOne<<" "; } numOne++; } return 0; } The output is: 3 5 7 9 -before 11 is the problem but now it's gone when i incremented below.. But it is still wrong because 3 should not be included also- :( 3 and 11 is the users input.. Even it is odd it should not be included.. Only the odd number "between them". "5 7 9"
Your second attempt works if increment numOne before you start. numOne++; while (numOne < numTwo) { if (numOne % 2 == 1 || numOne % 2 == -1) { cout << numOne << " "; } numOne++; } But, you may wish to use a for loop. for (int i = numOne + 1; i < numTwo; i++) { if (i % 2 == 0) continue; cout << i << " "; }
74,265,064
74,265,332
How to convert a std::string to const char* or char* at compile-time
Why yet another question on string to hash conversion My question is basically the same as the popular How to convert a std::string to const char* or char* question, but with a twist. I need the hash at compile time. Before rejecting my question, let me briefly explain my motivation. Motivation In my framework I am building, I have many threads. I have carefully designed the file structure so these threads re-use files whose functionality are the same so as not to violate ODR and lose maintainability. At the top of the list is error logging. My elaborate code begs to be re-used as-is in these different apps. So the initialized errorLogger object needs to be a different instance for each thread. Proposed solution Templatize my ErrorLogger class with a constant non-type parameter. In my framework, each app has a unique string that identifies itself. Now if I could hash that string at compile time, I would have the non-type template parameter I need for the compiler to generate separate instances. Here is the example code that doesn't work: #include <string> std::string threadUniqueStr { "threadUniqueName" }; /*constexpr*/ auto threadUniqueHash = std::hash< std::string > {} ( threadUniqueStr ); // uncommented constexpr results in 'expression did not evaluate to a constant' template< size_t > void Func() {} int main() { //Func< threadUniqueHash >(); // ERROR: expression did not evaluate to a constant Func< 33 >(); // works fine } But maybe there is an easier C++ way to do this that I am overlooking? Edit 1: My Solution Answer 1 shows how to create a hash from a string using string_view which follows @NathanOliver's advice that you have to write your own hash function for it to be constexpr. But I understand that writing your own hash function can have problems. @Pepijn Kramer points out 1) two strings may still produce the same hash and 2) from his experience, that a class hierarchy featuring app reporting at the top and individual error reporting behavior derived classes served his purposes in multi-dev situations (like mine). Since I don't want to use templates non-type parameter feature in an un-tried manner even though I can make a case for it, I am going to create my own ErrorLogger class hierarchy. Thanks to all for your helpful input. Edit 2: My Solution 2 I ended up using my original design for my error logger. Answer 1's string_view hash lets me constexpr a unique enough hash number which I use to create explicit template specializations, one for each named project. The ErrorLogger code itself is put into a static inside the specialization. Here is what the coding structure looks like: // .h template< size_t ProjectNameNumT > // primary non-type template global func void INFOMSG(); template< size_t ProjectNameNumT > void INFOMSG( bool yesNo ); // 2nd primary template; 1st overload // global define in Proj A ErrorLogger< PROJ_A_HASH > errorLoggerProjA; // global define in Proj B ErrorLogger< PROJ_B_HASH > errorLoggerProjB; // .cpp template<> void INFOMSG< PROJ_A_HASH >() { errorLoggerProjA.initLoggerHasRun = true; // set bool in specialization A specialization } // .cpp template<> void INFOMSG< PROJ_B_HASH >() { errorLoggerProjB.initLoggerHasRun = true; // set bool in specialization B specialization } // .cpp template<> void INFOMSG< PROJ_B_HASH >( bool yesNo ) { errorLogger.initLoggerHasRun = yesNo; // uses } // dev user's interface INFOMSG< PROJ_A_HASH >(); // sets bool to true in A INFOMSG< PROJ_B_HASH >(); // sets bool to true in B INFOMSG< PROJ_A_HASH >( false ); // sets bool in A to whatever yesNo value which is false here The ODR goal was achieved without sacrificing dev interface ease-of-use.
In C++17 a string_view can be constexpr so you can make your own hash function that takes one of those e.g. the hash function from someone's answer here would be like the following. #include <string_view> #include <iostream> constexpr size_t some_hash(std::string_view sv) { size_t hash = 5381; for (auto c : sv) hash = ((hash << 5) + hash) + c; return hash; } template<size_t N> void some_function() { std::cout << N << "\n"; } int main() { some_function<some_hash("foobar")>(); }
74,265,827
74,266,125
Is there a significant performance gap bewteen native VulkanSDK and its C++ binding?
Recently I'm trying to learn vulkan, and I found that although nearly every tutorial or book I found teaches vulkan with C++, the API style of it is more C than C++. Naturally, I looked for its official C++ API, and that raised my question: Is there a significant performance gap bewteen native VulkanSDK and its C++ binding? Or more generally, is there a significant performance gap bewteen C library and its C++ binding?
No C and C++ compilers and linkers are both well optimized at this point of life. Generally speaking - performance of code is the result of the whole programming process - from the initial design, to the programmer that codes, to the last step in the CI for deployment. So in general - are C bindings faster than C++? No. About Vulkan - It's a low level library, the bindings themselves have no much difference. The usage is very important since Vulkan is considered more "Low level" than OpenGL - this results in more control of the buffers and overall program flow. Memory,IO, CPU, Graphics RAM are all controlled by the developer which is the main concern for performance. Standard libraries are important C header files and C++ STD may differ in implementation which is the biggest point to consider when choosing a language - What does the ecosystem provide you as a programmer?. Since you'll probably need some vectors and matrix structures and a good math library for game development. This may affect your choices. Benchmark and metrices Nothing is written in stone. If you are concerned with performance first thing you'll need is to measure it. And that's a great exercise you can do - Are C bindings faster than C++? Just use a benchmark in your application and test it yourself! Best of luck.
74,266,694
74,267,203
Why operator= and copy constructor are treated differently in virtual inheritance?
It seems that in virtual inheritance, operator= and copy constructor are treated differently. Consider the following code: #include <iostream> #include <ostream> class A { public: A(int x) : x(x) { std::cout << "A is initialized" << std::endl; } A(const A& rhs) { std::cout << "Copy constructor for A" << std::endl; } A& operator=(const A& rhs) { std::cout << "A::operator=()" << std::endl; return *this; } virtual void funcB() = 0; virtual void funcC() = 0; int x; }; class B : virtual public A { public: B(int x) { std::cout << "B is initialized" << std::endl; } B(const B& rhs) { std::cout << "Copy constructor for B" << std::endl; } B& operator=(const B& rhs) { std::cout << "B::operator=()" << std::endl; return *this; } void funcB() override { std::cout << "B" << std::endl; } void funcC() override = 0; }; class C : public B { public: C(int x) : A(x + 1), B(x) { std::cout << "C is initialized" << std::endl; } void funcC() override { std::cout << "C" << std::endl; } }; int main() { C c(1); C c2(c); c2 = c; std::cout << c.x; } Here B inherit virtually from A and C inherit from B. The output is: A is initialized B is initialized C is initialized Copy constructor for A Copy constructor for B B::operator=() 2 We can see that the default copy constructor of C has successfully called the copy constructor for both B and A, which is what I want. But the default operator= did not call operator= of A, which is strange. A possible explanation to this is that the copy constructor of A is called by B, not C. However, since I have deliberately made B pure virtual, I don't have to initialize A in the copy constructor of B and in fact I did not. So the copy constructor of A is called most likely from C, but I have no proof of it since A will be initialized before B anyway, no matter who calls its constructor.
you're using compiler generated operator= (i.e C::operator=(const C&)), which calls operator= for all it's direct base class (and members) since A is not a direct base class of C, A::operator=(const A&) is not called. B is expected to copy A if it want, unlike constructor, you can implement assignment for B that doesn't change it's A (or whatever you want) on the other hand, if A is direct base class class C : public B , virtual public A { ... } then the compiler generated operator= would call A's assignment operator (and it's unspecific whether A is assigned multiple times)
74,266,896
74,267,153
Erasing multiple items from std::vector
I'm thinking about some different ways of erasing several pointers of a std::vector of pointers. I know that de erase/remove_if idiom is a good suit, but I'm thinking about a situation in which I have a container of pointers to remove from the std::vector that I have, something like this: std::vector<Object*> elementsToRemove; ... // fill elementsToRemove RemoveObjects(elementsToRemove, myObjectsVector) I'm asking about this because in my project we are facing some performance issues mostly because of item-by-item removal of vector containers, which imply in several reallocations. One way that I'm considering to implement this is with the erase/remove_if idiom, in which the predicate of the remove_if is a function that checks if the Object* is in the elementsToRemove Container. Anyone have a better sugestion of how to approach this problem? I'm considering to implement this is with the erase/remove_if idiom, in which the predicate of the remove_if is a function that checks if the Object* is in the elementsToRemove Container. However, this approach will require n x r comparisons (n is the number of Objects, and r is the number of objects to remove).
If you can sort both vectors then you need only a single pass through both for remove_if (erase is linear as well): #include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> X{1,2,3,4,5,6,7,8,9}; std::vector<int> remove{1,3,6,7}; auto first = remove.begin(); auto it = std::remove_if(X.begin(),X.end(),[&](int x) { while (first != remove.end() && *first < x) ++first; return (first != remove.end() && *first == x); }); X.erase(it,X.end()); for (const auto& x : X ) std::cout << x << " "; } Letting remove_if continue to scan the input vector X even though all elements from remove are already consumed is a little silly. Take the code with a grain of salt. It is just to demonstrate that also with the erase remove idiom it can be done with less than n x r comparisons. Sorting is O(N logN) so you'd get that in total. Alternatively you can sort only RemoveObjects then looking up an element in it can be done via binary search. Note that comparing the pointers via < is unspecified. Comparing them via std::less on the other does yield a (implementation defined) strict total order. std::sort uses std::less by default, you should need to consider that the resulting ordering is not necessarily consisten with <.
74,267,323
74,267,471
C++ Creating a unique pointer results in error "allocating an object of abstract class type" and "no matching constructor for initialization"
Edit: Turns out, in my Sunflower implementation, I named the function grow() instead of growImpl() so the compiler didn't find the implementation and was considering Sunflower as abstract. This question can be closed. I am trying to dynamically create an object of a class which inherits from an interface. I am trying to wrap this object in a unique pointer (I am not allowed to use new) and return it. I get the following error: /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/usr/include/c++/v1/memory:2099:32: error: allocating an object of abstract class type 'Sunflower' return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...)); The interface has some pure virtual functions. I know that when a function is declared as pure virtual, it must have an implementation. But I have added an implementation just to make it compile. So, I am not sure why Sunflower is considered an abstract class when it is supposed to be an implementation of the Flower interface. If I remove the virtual and const = 0 keywords from my flower class I get the following error: /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/usr/include/c++/v1/memory:2099:32: error: no matching constructor for initialization of 'Sunflower' return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...)); How do I make sure that sunflower is not considered abstract and create the unique pointer successfully? This is the flower interface: #include <algorithm> #include <numeric> #include <iostream> using namespace task3; std::unique_ptr<Flower> createSunflower(ex5::task3::Location location, ex5::task3::Color color); class Flower{ public: Flower(); Flower(Location _location, Color _color) : location(_location.getRow(), _location.getColumn()), color{_color} { } Flower(const Flower&) = delete; Flower(Flower&&) = delete; virtual ~Flower() = default; Flower& operator=(const Flower&) = delete; Flower& operator=(Flower&&) = delete; ex5::task3::Location getLocation(){return location;} void grow(const Garden& garden){ return growImpl(garden); } [[nodiscard]] std::unique_ptr<Flower> spread(const Garden& garden){ return spreadImpl(garden); } Color getColor(){return color;} Location location; Color color; private: virtual void growImpl(const Garden&) ; [[nodiscard]] virtual std::unique_ptr<Flower> spreadImpl(const Garden&) ; }; The implementation of this is here, which contains the sunflower class. The line that is giving me the error is in the function createSunflower(). I just added the make_unique in spread() to provide an implementation. But the line in createSunflower is giving me the error with or without the implementation of spread() and grow() : using namespace task3; class Sunflower final: public Flower{ //public: private: void grow(const Garden& garden) const override{ cout << endl; } [[nodiscard]] std::unique_ptr<Flower> spread(const Garden& garden)const override { return std::make_unique<Flower> ({0,0}, Color::BLACK); } }; std::unique_ptr<Flower> createSunflower(ex5::task3::Location location, ex5::task3::Color color){ return std::make_unique<Sunflower>(location, color); } The enums and structs are defined here, these are given to me and I cannot change them: namespace task3{ class Garden { public: plant(){ //do stuff } private: std::vector<std::unique_ptr<Flower>> flowers; }; class Location { public: Location(size_t row, size_t column) : locationPair{row, column} { } [[nodiscard]] size_t getRow() const noexcept { return locationPair.first; } [[nodiscard]] size_t getColumn() const noexcept { return locationPair.second; } private: std::pair<size_t, size_t> locationPair; }; enum class Color { WHITE, RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET, BLACK }; }}
std::make_unique<T>() creates an instance of T, which means T can't be an abstract type. So, inside of Sunflower::spread(), calling std::make_unique<Flower>(...); will not work when Flower is an abstract type. You MUST instantiate a derived class instead in that case, eg return std::make_unique<Sunflower>(...); spread() returns a unique_ptr<Flower>. A unique_ptr<Sunflower> can be assigned to a unique_ptr<Flower> as long as Flower has a virtual destructor (which it does in your example). Just like your createSunflower() function is doing. In fact, you could simply have Sunflower::spread() call createSunflower() instead, eg: std::unique_ptr<Flower> createSunflower(ex5::task3::Location, ex5::task3::Color); class Sunflower final: public Flower{ //public: private: ... [[nodiscard]] std::unique_ptr<Flower> spread(const Garden&) const override { return createSunflower({0,0}, Color::BLACK)); } }; std::unique_ptr<Flower> createSunflower(ex5::task3::Location location, ex5::task3::Color color){ return std::make_unique<Sunflower>(location, color); }
74,267,728
74,268,247
c++ 20 concepts in derived template class
for my test about CRTP I created this base class: template<typename Derived> struct Base { void print() const { std::cout << "print\n"; } }; And this class: struct A: public Base<A> { void printSub() { std::cout << "printSub from A\n"; } }; And I can use these classes without problem: A a1{}; a1.print(); a1.printSub(); My problem is: how is possible to use concept/requires for template class? I want add something like this: template<typename Derived> requires requires (Derived t) { t.printSub(); } struct Base { void print() { std::cout << "print\n"; } }; To accept only Derived class with printSub method. But I receive this error: template constraint failure... I did some tests but I did not find solutions (I also found this thread but it can't help me). Where am I wrong? Thanks for any help
You cannot meaningfully constrain the derived class template parameters of a CRTP base class for the same reason that you can't do this: template<typename Derived> class Base { using alias = Derived::SomeAlias; }; Derived isn't complete yet, and using a constraint usually requires completeness.
74,267,934
74,268,516
How to have inherited functions use local variables
I want to apply the functions from one class to the private variables from another derived class. I was hoping that this way I could avoid redefining the exact same function multiple times. I've added an example below. #include <iostream> class A { public: void print1(); void print2(); private: int array[3] = {1, 2, 3}; }; class B: public A { public: void print3(); private: int array[3] = {4, 5, 6}; }; void A::print1() { std::cout << this->array[0] << std::endl; } void A::print2() { std::cout << this->array[1] << std::endl; } void B::print3() { print1(); print2(); std::cout << this->array[2] << std::endl; } int main() { B b; b.print3(); // Output = 1 2 6, I want = 4 5 6 return 0; } I thought that perhaps defining the array in class A and B as public, so it would get overwritten, would work, but this did not have any effect.
There are two solutions, related to design patterns called "Non-virtual interface" or "Template methods". Without virtual methods: add a member which will point to the private array: class A { public: A() : array(_array) {} void print1(); void print2(); protected: A(int array[3]) : array(array) {} int *array; private: int _array[3] = {1, 2, 3}; }; class B: public A { public: B() : A(_array) {} void print3(); private: int _array[3] = {4, 5, 6}; }; Or add a virtual method, which will return the pointer: class A { public: void print1(); void print2(); protected: virtual int *array() { return _array; }; private: int _array[3] = {1, 2, 3}; }; class B: public A { public: void print3(); protected: virtual int *array() { return _array; }; private: int _array[3] = {4, 5, 6}; }; In this second solution use array() instead of array in methods (std::cout << this->array()[0] << std::endl; etc.).
74,267,964
74,268,009
C++ Trying to pass arrays to functions
I am trying to make this code work on Visual Studio 2022, but it tells me that after the second void printArray(int theArray\[\], int sizeOfArray) it expected a ;. I am doing this code based on https://youtu.be/VnZbghMhfOY. How can I fix this? Here is the code I have: #include <iostream> using namespace std; void printArray(int theArray[], int sizeOfArray); int main() { int bucky[3] = {20, 54, 675}; int jessica[6] = {54, 24, 7, 8, 9, 99}; printArray(bucky, 3); void printArray(int theArray[], int sizeOfArray) { for (int x = 0; x < sizeOfArray; x++){ cout << theArray[x] << endl; } } } I tried to change the code order but that only made it worse, the error saying ; is apparently useless and the whole thing breaks apart if I put it there.
You should take the implementation of the function "printArray" out of the main. #include <iostream> using namespace std; void printArray(int theArray[], int sizeOfArray); int main() { int bucky[3] = {20, 54, 675}; int jessica[6] = {54, 24, 7, 8, 9, 99}; printArray(bucky, 3); return 0; } void printArray(int theArray[], int sizeOfArray) { for (int x = 0; x < sizeOfArray; x++){ cout << theArray[x] << endl; } }
74,268,106
74,269,451
File that requires elevated privileges
I want to create a file that is: Read-only accessible for all local users. Read-write accessible only when application runs with elevated privileges. I have found Windows-classic-samples here. I modified it a bit, so it gives the creator full access and everyone else GENERIC_READ: #include <Accctrl.h> #include <Aclapi.h> #include <stdexcept> #include <filesystem> #define SCOPE_EXIT_LINE(...) /* Assume ignored. */ void accessImpl(const std::filesystem::path &path, bool readWrite) { PACL pAcl = nullptr; DWORD dwAclSize; SID_IDENTIFIER_AUTHORITY siaWorld = SECURITY_LOCAL_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY siaCreator = SECURITY_CREATOR_SID_AUTHORITY; PSID pEveryoneSid = nullptr; PSID pOwnerSid = nullptr; dwAclSize = sizeof(ACL) + 2 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + GetSidLengthRequired(1) + GetSidLengthRequired(1); pAcl = static_cast<PACL>(LocalAlloc(0, dwAclSize)); if(pAcl == nullptr) { throw std::runtime_error("Failed to allocate ACL"); } InitializeAcl(pAcl, dwAclSize, ACL_REVISION); SCOPE_EXIT_LINE(if(pAcl) LocalFree(pAcl)); AllocateAndInitializeSid(&siaWorld, 1, SECURITY_LOCAL_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSid); SCOPE_EXIT_LINE(if(pEveryoneSid) FreeSid(pEveryoneSid)); AllocateAndInitializeSid(&siaCreator, 1, SECURITY_CREATOR_OWNER_RID, 0, 0, 0, 0, 0, 0, 0, &pOwnerSid); if(AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_READ | (readWrite ? GENERIC_WRITE : 0) | GENERIC_EXECUTE, pEveryoneSid) == 0) { throw std::runtime_error("Failed to set AddAccessAllowedAce"); } if(AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, pOwnerSid) == 0) { throw std::runtime_error("Failed to set AddAccessAllowedAce"); } const auto pSD = static_cast<PSECURITY_DESCRIPTOR>(LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH)); if(pSD == nullptr) { throw std::runtime_error("Failed to set LocalAlloc SD"); } if(InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION) == 0 || SetSecurityDescriptorDacl(pSD, TRUE, pAcl, FALSE) == 0 || SetFileSecurityW(path.c_str(), DACL_SECURITY_INFORMATION, pSD) == 0) { throw std::runtime_error("Failed to set permissions"); } } Then I create the file with elevated privileges. Which seems to create the desired access structure: But for some reason, writing to the file fails even with elevated privileges. (I tried with PowerShell, NotePad++, etc) What am I doing wrong?
As @RbMm and @RaymondChen show in the comments, this can be done very cleanly: #include <Windows.h> #include <Accctrl.h> #include <Aclapi.h> #include <sddl.h> #include <filesystem> enum class FileAccess { ReadOnly, ReadWrite }; void grantAllAccess(const std::filesystem::path &file, const FileAccess access) { const auto sidString = (access == FileAccess::ReadWrite) ? L"D:PAI(A;;0x12019f;;;WD)(A;;FA;;;BA)" : // Everyone Read/Write, Admin full access L"D:P(A;;FA;;;BA)(A;;FR;;;WD)"; // Everyone Read only, Admin full access PSID pSid = nullptr; if(ConvertStringSecurityDescriptorToSecurityDescriptorW( sidString, SDDL_REVISION_1, &pSid, nullptr) == 0) { throw std::runtime_error("Failed to create SID"); } if(SetFileSecurityW(file.c_str(), DACL_SECURITY_INFORMATION, pSid) == 0) { LocalFree(pSid); throw std::runtime_error("Failed to set SID to file"); } LocalFree(pSid); } See this answer for how to generate these cryptic strings. See this repo to convert these strings to readable text.
74,269,148
74,270,185
Creating logical device in Vulkan returns -8, but only sometimes
While using a class to hold my window class and Vulkan class, this error VK_ERROR_FEATURE_NOT_PRESENT is returned when I use vkCreateDevice however, when I put the same code the class is running into the main class, it works completely fine. I also had a similar problem with getting the instance extensions via SDL_Vulkan_GetInstanceExtensions. working main.cpp window.createWindow(); engine.window = window.window; try { engine.initialize(); } catch (XiError error) { std::cout << "Error " << error.code << ": " << error.definition << std::endl; } window.instance = engine.getVkInstance(); VkPhysicalDeviceProperties deviceProperties; vkGetPhysicalDeviceProperties(engine.physicalDevice, &deviceProperties); std::cout << deviceProperties.deviceName << ", Driver Version " << deviceProperties.driverVersion << std::endl; try { window.createSurface(); } catch (XiError error) { std::cout << "Error " << error.code << ": " << error.definition << std::endl; } window.mainLoop(); vkDestroyDevice(engine.logicalDevice, nullptr); vkDestroySurfaceKHR(engine.instance, window.surface, nullptr); vkDestroyInstance(engine.instance, nullptr); SDL_DestroyWindow(window.window); SDL_Quit(); not working main.cpp try { app.run(); } catch (XiError error) { std::cout << "Error " << error.code << ": " << error.definition << std::endl; } VkPhysicalDeviceProperties deviceProperties; vkGetPhysicalDeviceProperties(app.engine.physicalDevice, &deviceProperties); std::cout << deviceProperties.deviceName << ", Driver Version " << deviceProperties.driverVersion << std::endl; app.window.mainLoop(); app.shutDown(); app.run() window.createWindow(); engine.window = window.window; engine.createVulkanInstance(); window.instance = engine.getVkInstance(); window.createSurface(); engine.getPhysicalDevices(); engine.selectPhysicalDevice(); engine.createLogicalDevice(); window.mainLoop(); app.shutDown() vkDestroyDevice(engine.logicalDevice, nullptr); vkDestroySurfaceKHR(engine.instance, window.surface, nullptr); vkDestroyInstance(engine.instance, nullptr); SDL_DestroyWindow(window.window); SDL_Quit(); window engine and app are pre-defined by my own classes I've tried manually adding the different required and supported extensions, and it works, but it feels hacky and is quite a large bulk of code. If this is a weird out of scope error, I've really no idea. if any other code is needed I'll be happy to provide it and the GitHub can also be found here: https://github.com/XiniaDev/Xinia-Engine
I think your problem is that requiredFeatures in XiEngine is not initialised. You set a few values to true, but I think you need a memset(&requiredFeatures, 0, sizeof(requiredFeatures)); or similar at the start of XiEngine::XiEngine to fix it.
74,269,200
74,269,238
Conditional operator not giving correct output
We have an issue that I have been able to recreate with this sample code: int main() { double d = -2; // ... cout << "d: " << d << endl; cout << "-d: " << -d << endl; cout << "Conditional Operator (expect value 2): " << (d < 0)? -d : d; cout << endl; return 0; } The output is as follows: d: -2 -d: 2 Conditional Operator (expect value 2): 1
It's a problem of operator precedence. Use: cout << "Conditional Operator (expect value 2): " << (d < 0? -d : d); Explanations: The reason is that << has a higher precedence than ? So your orignal statement does not mean what you expect, i.e. cout << "Conditional Operator (expect value 2): " << ( (d < 0)? -d : d ); but (cout << "Conditional Operator (expect value 2): " << (d < 0) ) ? -d : d ; So cout outputs (d<0) after the string. Since the expression is true it results as output 1, unless you'd have used cout << std::boolalpha <<..., in which case it would have printed true. The printing is then finished and (cout<<...<<...) is then used as condition for the ternary operator, but the final result is lost, as it is not part of the cout expression and nothing is done with that result.
74,269,427
74,269,514
why when run my code the function doesn't work as expected
I made a function to get the larger number out of two when I run it it prints a random large number #include<iostream> using namespace std; int larger(int num1,int num2); int main() { int n1,n2,result; result=larger(n1,n2); cout<<"enter two number\n"; cin>>n1>>n2; cout<<"the larger number is "<<result<<endl; } int larger(int num1,int num2) { int max; if (num1>=num2) max=num1; else max=num2; return max; }
It's because you are calling the function before inputting 'n1' and 'n2'. result=larger(n1, n2) should come after the cin >>...
74,269,551
74,269,741
why does ranges::view_interface<T>::size require a move constructor
I don't understand where the requirement for moving comes from. I can't find it in forward_range and sized_sentinel... Basic example: #include <ranges> #include <string> #include <iostream> class vrange: public std::ranges::view_interface<vrange> { public: vrange(std::string &d): data(d){;}; vrange(const vrange &&) = delete; auto begin() const noexcept { return data.begin(); }; auto end() const noexcept { return data.end(); }; private: std::string data; }; int main(){ std::string h("Hello world"); vrange r(h); std::cout << r.size() << std::endl; for (const auto &i: r){ std::cout << i; } std::cout << std::endl; } removing the call to r.size(), or defaulting the vrange move constructor and assignment operator makes it compile fine. compiler message: /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/bits/ranges_util.h: In instantiation of ‘constexpr _Derived& std::ranges::view_interface<_Derived>::_M_derived() [with _Derived = vrange]’: /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/bits/ranges_util.h:101:35: required from ‘constexpr bool std::ranges::view_interface<_Derived>::empty() requires forward_range<_Derived> [with _Derived = vrange]’ w.cpp:25:12: required from here /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/bits/ranges_util.h:70:23: error: static assertion failed 70 | static_assert(view<_Derived>); | ^~~~~~~~~~~~~~ /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/bits/ranges_util.h:70:23: note: constraints not satisfied In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/ranges:37: /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/concepts:136:13: required for the satisfaction of ‘constructible_from<_Tp, _Tp>’ [with _Tp = vrange] /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/concepts:150:13: required for the satisfaction of ‘move_constructible<_Tp>’ [with _Tp = vrange] /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/concepts:247:13: required for the satisfaction of ‘movable<_Tp>’ [with _Tp = vrange] /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/concepts:137:30: note: the expression ‘is_constructible_v<_Tp, _Args ...> [with _Tp = vrange; _Args = {vrange}]’ evaluated to ‘false’ 137 | = destructible<_Tp> && is_constructible_v<_Tp, _Args...>;
This has nothing to do with size specifically. view_interface is used to build a type that is a view. Well, the ranges::view concept requires that the type is at least moveable. And view_interface has a very specific requirement on the type given as its template argument: Before any member of the resulting specialization of view_interface other than special member functions is referenced, D shall be complete, and model both derived_from<view_interface<D>> and view. Well, your type does not model view because it is not moveable. So you broke the rules, and you therefore get undefined behavior. Which can include compile errors happening if you call certain members but not others.
74,271,784
74,273,816
is it ok for arguments and expects go out of scope
I'm wondering is it ok if arguments and expects are going out of scope when they actually be matched later? like this: struct Object { // ... }; struct TestFixture : public testing::Test { MOCK_METHOD1(handle, void(Object obj)); }; TEST_F(TestFixture, Basic) { { Object obj; // = get different obj EXPECT_CALL(*this, handle(obj)); } { Object obj; // = get different obj EXPECT_CALL(*this, handle(obj)); } { Object obj; // = get different obj EXPECT_CALL(*this, handle(obj)); } // call handle 3 times } all the 3 obj variable will go out of scope, also will EXPECT_CALL create some kind of local variables there? Is this test ok in gtest? Thanks.
From reference/matchers.html Except Ref(), these matchers make a copy of value in case it’s modified or destructed later. So you are fine.
74,272,161
74,272,392
How get name macros from value?
I write #define macros I want to have a function or a macro that prints its name when I give it a value for example : ` #define ten 10 string printName(int value); int main() { cout<<printName(10); } ` output : ten A solution or code sample
Use of macros should be avoided wherever possible. Instead you could use a std::map<int, std::string> for your purpose: int main() { const std::map<int, std::string> printName{{10, "ten"}, {11, "eleven"}};//add more if you want std::cout << printName.at(10) << std::endl; //prints ten }
74,272,713
74,280,169
Accessing raspberry Pi camera using C++
I am trying to run openCV in C++ and capture the camera input. The program looks like this: #include <iostream> #include <sstream> #include <new> #include <string> #include <sstream> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #define INPUT_WIDTH 3264 #define INPUT_HEIGHT 2464 #define DISPLAY_WIDTH 640 #define DISPLAY_HEIGHT 480 #define CAMERA_FRAMERATE 21/1 #define FLIP 2 void DisplayVersion() { std::cout << "OpenCV version: " << cv::getVersionMajor() << "." << cv::getVersionMinor() << "." << cv::getVersionRevision() << std::endl; } int main(int argc, const char** argv) { DisplayVersion(); std::stringstream ss; ss << "nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method=2 ! video/x-raw, width=480, height=680, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink"; //ss << "nvarguscamerasrc ! video/x-raw(memory:NVMM), width=" << INPUT_WIDTH << //", height=" << INPUT_HEIGHT << //", format=NV12, framerate=" << CAMERA_FRAMERATE << //" ! nvvidconv flip-method=" << FLIP << //" ! video/x-raw, width=" << DISPLAY_WIDTH << //", height=" << DISPLAY_HEIGHT << //", format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink"; cv::VideoCapture video; video.open(ss.str()); if (!video.isOpened()) { std::cout << "Unable to get video from the camera!" << std::endl; return -1; } std::cout << "Got here!" << std::endl; cv::Mat frame; while (video.read(frame)) { cv::imshow("Video feed", frame); if (cv::waitKey(25) >= 0) { break; } } std::cout << "Finished!" << std::endl; return 0; } When running this code I get the following outout: OpenCV version: 4.6.0 nvbuf_utils: Could not get EGL display connection Error generated. /dvs/git/dirty/git-master_linux/multimedia/nvgstreamer/gst-nvarguscamera/gstnvarguscamerasrc.cpp, execute:751 Failed to create CaptureSession [ WARN:0@0.269] global /tmp/build_opencv/opencv/modules/videoio/src/cap_gstreamer.cpp (1405) open OpenCV | GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1 Got here! Finished! If I run the other commented command to video.open() I get this output: OpenCV version: 4.6.0 nvbuf_utils: Could not get EGL display connection Error generated. /dvs/git/dirty/git-master_linux/multimedia/nvgstreamer/gst-nvarguscamera/gstnvarguscamerasrc.cpp, execute:751 Failed to create CaptureSession I'm currently running this from headless mode on a jetson nano. I also know that OpenCV and xlaunch works because I can use mjpeg streamer from my laptop and successfully stream my laptop camera output to my jetson nano by using video.open(http://laptop-ip:laptop-port/); and that works correctly (OpenCV is able to display a live video feed using xlaunch just fine). I think this command is telling me my camera is successfully installed: $ v4l2-ctl -d /dev/video0 --list-formats-ext ioctl: VIDIOC_ENUM_FMT Index : 0 Type : Video Capture Pixel Format: 'RG10' Name : 10-bit Bayer RGRG/GBGB Size: Discrete 3264x2464 Interval: Discrete 0.048s (21.000 fps) Size: Discrete 3264x1848 Interval: Discrete 0.036s (28.000 fps) Size: Discrete 1920x1080 Interval: Discrete 0.033s (30.000 fps) Size: Discrete 1640x1232 Interval: Discrete 0.033s (30.000 fps) Size: Discrete 1280x720 Interval: Discrete 0.017s (60.000 fps) Any help would be much appreciated
Well I fixed it by rebooting. I already did do a reboot but I also now have some errors whenever I run the program. I did recompile the dlib library but so I do think that when you update the gstreamer library you need to reboot your machine to successfully use it.
74,272,874
74,275,145
preventing r-value references in variadic template
looking at std::ref and std::cref, the way I think it works is having two prototypes template< class T > std::reference_wrapper<const T> cref( const T& t ) noexcept; template< class T > void cref( const T&& ) = delete; and the T&& template function is deleted. But when I imitate this with a similar variadic template function, the compilation is successful if atleast one argument satisfies the condition. So now I don't understand how or why this (does not?) works. template<typename ... Ts> void foo(const Ts& ... ts) { } template<typename ... Ts> void foo(const Ts&& ...) = delete; int main(){ std::string a{"sss"}; foo<std::string>(a); //foo<std::string>("sss"); error, deleted foo foo<std::string, std::string>(a, "sss"); // I was expecting error here //foo<std::string, std::string>("aaaa", "sss"); error, deleted foo foo<std::string, std::string, std::string>(a, "aaa", "sss"); // I was expecting error here } This seems to be the case with clang, gcc and also msvc https://godbolt.org/z/8cboT48En
Ordinary string literals are lvalues, so your test isn't testing what you want. Testing with literals that are rvalues, I found you need to have each variant of cv-ref qualifiers. #include<iostream> #include<utility> #include<string> template<typename ... Ts> void foo(const Ts& ... ts) { } template<typename ... Ts> void foo(Ts& ... ts) { foo(std::as_const(ts)...); } template<typename ... Ts> void foo(const Ts&& ...) = delete; template<typename ... Ts> void foo(Ts&& ...) = delete; using namespace std::string_literals; int main(){ std::string a{"sss"}; foo(a); // errors, as desired // foo("sss"s); // foo(a, "sss"s); // foo("aaaa"s, "sss"s); // foo(a, "aaa"s, "sss"s); } See it live
74,273,263
74,276,256
How can one write a multi-dimensional vector of image data to an output file?
Question: Is there a good way to write a 3D float vector of size (9000,9000,4) to an output file in C++? My C++ program generates a 9000x9000 image matrix with 4 color values (R, G, B, A) for each pixel. I need to save this data as an output file to be read into a numpy.array() (or similar) using python at a later time. Each color value is saved as a float (can be larger than 1.0) which will be normalized in the python portion of the code. Currently, I am writing the (9000,9000,4) sized vector into a CSV file with 81 million lines and 4 columns. This is slow for reading and writing and it creates large files (~650MB). NOTE: I run the program multiple times (up to 20) for each trial, so read/write times and file sizes add up. Current C++ Code: This is the snippet that initializes and writes the 3D vector. // initializes the vector with data from 'makematrix' class instance vector<vector<vector<float>>> colorMat = makematrix->getMatrix(); outfile.open("../output/11_14MidRed9k8.csv",std::ios::out); if (outfile.is_open()) { outfile << "r,g,b,a\n"; // writes column labels for (unsigned int l=0; l<colorMat.size(); l++) { // 0 to 8999 for (unsigned int m=0; m<colorMat[0].size(); m++) { // 0 to 8999 outfile << colorMat[l][m][0] << ',' << colorMat[l][m][1] << ',' << colorMat[l][m][2] << ',' << colorMat[l][m][3] << '\n'; } } } outfile.close(); Summary: I am willing to change the output file type, the data structures I used, or anything else that would make this more efficient. Any and all suggestions are welcome!
Use the old C file functions and binary format auto startT = chrono::high_resolution_clock::now(); ofstream outfile; FILE* f = fopen("example.bin", "wb"); if (f) { const int imgWidth = 9000; const int imgHeight = 9000; fwrite(&imgWidth, sizeof(imgWidth), 1, f); fwrite(&imgHeight, sizeof(imgHeight), 1, f); for (unsigned int i=0; i<colorMat.size(); ++i) { fwrite(&colorMat[i], sizeof(struct Pixel), 1, f); } } auto endT = chrono::high_resolution_clock::now(); cout << "Time taken : " << chrono::duration_cast<chrono::seconds>(endT-startT).count() << endl; fclose(f); The format is the following : [ImageWidth][ImageHeight][RGBA][RGBA[RGBA]... for all ImageWidth * ImageHeight pixels. Your sample ran in 119s in my machine. This code ran in 2s. But please note that the file will be huge anyway : you are writing the equivalent of two 8K files without any kind of compression. Besides that, some tips on your code : Don't use a vector of floats to represent your pixels. They won't have more components than RGBA. Instead create a simple struct with four floats. You don't need to look through width and height separately. Internally all lines are put sequentially one after the other. It is easier to create a one dimension array of width * height size.
74,274,489
74,274,797
How can I simplify the For loop(c++)?
I found a code on the internet to encrypt user input with Caesar encryption. But in the code the loop head bother me, because we didn't have things like "message[i]" or "\0" in class. Is it possible to write this in a different way? But we had not used arrays as far as in this loop header. This is not homework or anything like that. I'm practicing for my computer science test next week and there will probably be something similar. The loop header always looked like this for example for(i = 0; i < 4; i++). How can I write this code without arrays? How can I write the loop differently? Or do I have to change other code parts? #include <iostream> using namespace std; int main() { char message[100], ch; int i, key; cout << "Enter a message to encrypt: "; cin.getline(message, 100); cout << "Enter key: "; cin >> key; for (i = 0; message[i] != '\0'; ++i) { //<- ch = message[i]; //<- if (ch >= 'a' && ch <= 'z') { ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } message[i] = ch; //<- } else if (ch >= 'A' && ch <= 'Z') { ch = ch + key; if (ch > 'Z') { ch = ch - 'Z' + 'A' - 1; } message[i] = ch; //<- } } cout << "Encrypted message: " << message; return 0; }
To have a for loop closer to what you are used to, we need to know how many letters were input. The smallest change that does that is to use strlen to count them. for (i = 0; i < strlen(message); ++i) However it's better to use std::string to hold text, because that knows it's size. int main() { std::string message; int key; std::cout << "Enter a message to encrypt: "; std::getline(std::cin, message); std::cout << "Enter key: "; std::cin >> key; for (i = 0; i < message.size(); ++i) { char ch = message[i]; if (ch >= 'a' && ch <= 'z') { ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } message[i] = ch; //<- } else if (ch >= 'A' && ch <= 'Z') { ch = ch + key; if (ch > 'Z') { ch = ch - 'Z' + 'A' - 1; } message[i] = ch; //<- } } std::cout << "Encrypted message: " << message; return 0; } And even better than that, you can loop over the chars in a string directly int main() { std::string message; int key; std::cout << "Enter a message to encrypt: "; std::getline(std::cin, message); std::cout << "Enter key: "; std::cin >> key; for (char & ch : message) // <- N.b. char &, we are modifying the `char` objects owned by message { if (ch >= 'a' && ch <= 'z') { ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } } else if (ch >= 'A' && ch <= 'Z') { ch = ch + key; if (ch > 'Z') { ch = ch - 'Z' + 'A' - 1; } } } std::cout << "Encrypted message: " << message; return 0; }
74,274,552
74,276,978
Why use boost::bind instead of direct function call in boost.asio operations?
I've noticed 3 main options to call handler for async operations in Boost.Asio: class MyClass { public: void doReadFromSocket(); //implementation options provided below. private: void handleRead(const boost::system::error_code& ec, std::size_t bytesTransferred) { // ... handle async_read result. } boost::asio::streambuf m_buffer; boost::asio::ip::tcp::socket m_socket; } Option 1 - use lambda function: void MyClass::doReadFromSocket() { boost::asio::async_read(m_socket, m_bufferIn, boost::asio::transfer_at_least(1), [this](const boost::system::error_code& ec, std::size_t bytesTransferred) { // ... } } Option 2 - use direct member function call: UPD. The option is not correct, as pointed out in the comments. void MyClass::doReadFromSocket() { boost::asio::async_read(m_socket, m_bufferIn, boost::asio::transfer_at_least(1), handleRead); } Option 3 - use boost::bind to call member function that handles the read: void MyClass::doReadFromSocket() { boost::asio::async_read(m_socket, m_bufferIn, boost::asio::transfer_at_least(1), boost::bind(&MyClass::handleRead, this, _1, _2)); } } The main questions are: Are there any differences in those ways to handle the read operation, especially in terms of performance? Why do we need boost::bind to handle the read? Why not use a direct member function call? A lot of examples in the boost library use boost::bind to handle async operations. Also, this option seems the least convenient from my perspective
Like others said, not all of your options are correct. Looking beyond that: bind (std or boost) has the added effect of returning a bind-expression templated on the original functor type. In C++ this means that the original associated namespaces for ADL still apply to the bound handler. This property is important when e.g. the associated executor, allocator or cancellation slot are important (like, a strand). The inverse of this is a common pitfall, e.g. when using std::function<> instead of a bind expression: boost::asio::bind_executor does not execute in strand boost::bind has the advantage of being available on C++03 (which Asio supports) lambdas have a slight benefit of reducing the number of explicit functions defined, at the cost of increased complexity; especially the lifetime of captured variables can be harder to check. Also note that you might still need to manually associate an executor (asio::bind_executor) with some lambda handlers. The reason I feel lambdas have become more viable in generic Asio code is because in "recent" Asio versions IO objects are constructed from a specific executor, which will be the default executor for completion handlers passed to async_ initiation functions on these IO objects. Note though that this scratches the surface of options. Contrary to what some people commented, the "handler" argument is not necessarily a handler. It's actually what's known as a completion Token. It can be many things, like use_future, use_awaitable, deferred, detached, as_tuple(another_token) etc. Also, there are design patterns where the handler itself is a class - e.g. derived from asio::coroutine. This is often used inside the library because it provides a very lightweight way to provide "faux coroutine"-like state machines to implement asynchronous operations in a way that's compatible with C++03 and all completion tokens, without incurring unnecessary overhead. Also note that many libraries use convenience helpers (like beast::bind_front_handler) to reduce the amount of repeated code for bind expressions. To Summarize It's up to you, based on specific requirements and personal preference. Asio is a highly generic framework for asynchronous operations and you have choices on how you interact with it.
74,274,997
74,276,531
Move one more vector to the vector of vectors?
I have the structure vector<vector<x>> a and one more vector<x> v. I need to append this new vector to the existing vector of vectors (as new a item, not to concatenate), but it is long and I do not need it afterwards, so I would like to move the contents instead: As of the time of writing, the code is trivial: a.push_back(v); that obviously works. Can this be optimized like a.push_back(std::move(v)); or somehow else?
Yes, this will definitely work. As you can read in the definition of std::move here, std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type. So the result can be interpreted as rvalue reference. And if we then look at the description of the std::vectors push_back function here, then we will find void push_back( T&& value ) which will "move the value into the new element" So, your approach will work.
74,275,568
74,395,346
Is it possible to define preprocessor directives for an Unreal project at build time?
I am looking for a way to easily define macros / preprocessor directives at project build/cook time for an Unreal Engine project. For example, if I want a defined C++ macro MY_BUILDTIME_VAR to be 0 in certain builds, and 1 in others, without having to modify source code every time, in a similar approach to environment varibles in many tools (i.e. NODE_ENV in node.js), or to the command-line approach of i.e. g++ (see here). I am aware it's possible to define target-wide macros in a project's target.cs with GlobalDefintions.Add("MY_TARGET_VAR=0") or module-wide macros in a module's Build.cs with PublicDefinitions.Add("MY_MODULE_VAR=0"). It helps to have all things defined in one place, but those definitions are still baked in the source file, and can't be changed at build time. The official documentation mentions several ways of building/cooking an Unreal project with custom parameters, such as the Project Launcher tool and the RunUAT script file. Do any of them allow for build-time macro definitions? Note: I am not using MS Visual Studio, but JetBrains Rider with .uproject only, so I can't define them in an .sln solution file.
Use an environment variable and read it in your build.cs file. Based on the environment variable set the value of your macro. This is a handy utility method I use for this purpose: private void AddEnvironmentVariableDefinition(string variableName, string defName, string defaultValue = "0") { string value = System.Environment.GetEnvironmentVariable(variableName) ?? defaultValue; PublicDefinitions.Add(String.Format("{0}={1}", defName, value)); }
74,275,656
74,276,361
How to virtual List control using a map data structure'?
I have a question while studying C++ MFC. void AnchorDlg::OnGetdispinfoListctrl(NMHDR *pNMHDR, LRESULT *pResult) { NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR); LV_ITEM* pItem = &(pDispInfo)->item; CString str; if(pItem == NULL) return; int nRow = pItem->iItem; int nCol = pItem->iSubItem; if(nRow<0 || nRow >= mapShip->size()) return; auto iter = mapShip->begin(); if(pItem->pszText) { switch(nCol) { case 1: str.Format(_T("%.0f"), iter->second->mmsi); //str.Format(_T("%.0f"), iter->second->mmsi); lstrcpy(pItem->pszText, str); break; case 2: str.Format(_T("%.7f"), iter->second->lat); lstrcpy(pItem->pszText, str); break; case 3: str.Format(_T("%.7f"), iter->second->lng); lstrcpy(pItem->pszText, str); break; case 4: str.Format(_T("%.1f"), iter->second->sog); lstrcpy(pItem->pszText, str); case 5: str.Format(_T("%.1f"), iter->second->cog); lstrcpy(pItem->pszText, str); } } *pResult = 0; } mapShip consists of double and data objects. I want to print out 1000 data, but only one data is printed. I've used iter but only one data is output. Same data print repeat. I must used map data structure. I don't know how to use the map.
You don't seem to do anything with pItem->iItem (nRow), you just set it to the beginning of the list. You should instead search your data with this - requests may arrive in any random order. You don't have to iterate the list in OnGetdispinfoListctrl(), instead you should return the data to be displayed, given the iItem and iSubItem members. So consider using a more efficient structure to hold your data, if they are really too many (lists are not, because they are serial access structures, not random access ones). Also, don't copy the text into Item.pszText, instead set Item.pszText to point to your data. The if(pItem->pszText) check is not needed, neither is correct: void AnchorDlg::OnGetdispinfoListctrl(NMHDR *pNMHDR, LRESULT *pResult) { NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR); LV_ITEM* pItem = &(pDispInfo)->item; // Persistent Buffer static CString str; if (pItem == NULL) return; int nRow = pItem->iItem; int nCol = pItem->iSubItem; if (nRow < 0 || nRow >= mapShip->size()) return; if (Item.mask & LVIF_TEXT) //Item/subItem text { //auto iter = mapShip->begin(); auto pValue = SearchMyData(nRow); switch (nCol) { case 1: str.Format(_T("%.0f"), pValue->mmsi); break; case 2: str.Format(_T("%.7f"), pValue->lat); break; case 3: str.Format(_T("%.7f"), pValue->lng); break; case 4: str.Format(_T("%.1f"), pValue->sog); break; case 5: str.Format(_T("%.1f"), pValue->cog); break; } pItem->pszText = const_cast<LPTSTR>((LPCTSTR)str); } *pResult = 0; } EDIT: Here is a excerpt from the documentation about the LV_ITEM structure: pszText If the structure specifies item attributes, pszText is a pointer to a null-terminated string containing the item text. When responding to an LVN_GETDISPINFO notification, be sure that this pointer remains valid until after the next notification has been received. Also: cchTextMax This member is only used when the structure receives item attributes. ... It is read-only during LVN_GETDISPINFO and other LVN_ notifications. And the example in the LVN_GETDISPINFO documentation does exactly this, ie sets the pszText pointer rather than copies text into it. Also, you shouldn't get the conversion error if you are using either the multibyte (ANSI) or the wide (Unicode) version of both the LVITEM and CString, which you seem to do (you do not set them explicitly, which is OK, it defaults to T interpretation). It must be a const conflict. So, either use a const_cast: pItem->pszText = const_cast<LPTSTR>((LPCTSTR)str); or a char array instead: static TCHAR _szItem[MAX_LEN]; // Persistent buffer . . CString str; str.Format(_T("%.0f"), iter->second->mmsi)); _tcscpy_s(_szItem, str); pItem->pszText = _szItem; break;
74,275,797
74,275,983
Nested template argument deduction
I have some function that is templated on output type. This function then accepts an input argument that in its turn is templated on the output type. I do not want to specify the output type twice as that just clutters the api. In my world, I have told the compiler everything it needs to know to deduce this correctly but I cannot get it to work. Suggestions? template<typename T> struct TestStruct {}; template<typename T, template<typename> class U> T testFunc(U<T> arg) { return T{0}; } int main() { testFunc<double>(TestStruct<double>{}); // Compiles testFunc<double>(TestStruct{}); // Does not compile }
The problem isn't with testFunc but with TestStruct{} as you're not passing a template argument and the corresponding template parameter of class template TestStruct doesn't have a default argument. I do not want to specify the output type twice As you want to specify the double only once you can do: template<typename T, template<typename> class U> T testFunc(U<T> arg) { return T{0}; } int main() { //----------------------vvvvvv-------------->only once as you want testFunc(TestStruct<double>{}); //----------^------------------------------->no need to specify double here as it can be deduced } Demo As shown in the above modified program, we're only specifying double once when passing it as a template argument for TestStruct. The template argument for T of function template testFunc can be deduced.
74,276,942
74,277,035
Question regarding initialization of an array
My problem: I have the following piece of code that is a wrapper for 2D square matrices in order to transpose them and print them. I cannot understand why we can write this: arrayNN(T DATA[N][N]){ n = N; data = DATA; } In particular this line of code:data = DATA;. My thoughts: As far as i know, in C/C++ you cannot give the values of a matrix to another matrix. For example this piece of code doesn't work, no matter how we write the definition of b: double array[3][3] = { {11,12,13},{21,22,23},{31,32,33}}; //only one definition //double **b; //double *b[3] double b[3][3]; b = array; Code: It works. #include <iostream> using namespace std; template <typename T, size_t N> class arrayNN { private: int n; T (*data)[N]; # a vector of N elements of pointers to datatype T = 2d matrix public: arrayNN(): n(N), data(NULL) {}; arrayNN(T DATA[N][N]){ n = N; data = DATA; } void print(ostream &out){ for(int i = 0;i<N;i++){ for(int j=0;j<N; j++){ cout << data[i][j] << '\t'; } cout << endl; } } void transpose(){ for(int i = 0;i<N;i++){ for(int j=0;j<i; j++){ T temp = data[i][j]; data[i][j] = data[j][i] ; data[j][i] = temp; } } } }; int main(){ double array[3][3] = { {11,12,13},{21,22,23},{31,32,33}}; arrayNN<double,3> A(array); A.print(cout); A.transpose(); A.print(cout); return 0; }
T (*data)[N]; # a vector of N elements of pointers to datatype T = 2d matrix No, data is not a vector or an array. Instead it is a pointer to an array of size N with elements of type T. This means that when you wrote data = DATA; you're actually assigning the pointer DATA to the pointer data. Note that the function parameter DATA is a pointer and not an array. You can refer to What is array to pointer decay? for seeing why DATA is a pointer.
74,277,117
74,277,722
How do i make it so that a certain input lists the functions and a certain input calls one of them?
You know how this shows up when you choose a directory in the terminal? Is there a way I could create my own version of this, but when the user chooses one of the choices, it calls a function? i mean nothing about the terminal or directory, i am using it as an example user types "menu" and there'd be a list of words that show up "games" "text" "about" user can type "open games" and it runs the function i named games here are my test functions: void game() { cout << "you are in game" } void text() { cout << "you are in text" } void about() { cout << "you are in about" how do i make it so that a certain input LISTS the different functions, and a certain input CALLS the different functions?
I have understood that you want to see a list of functions in your program, not files on your hard disk. There's no built-in way to do this, and although I can think of some more clever ways to do it, they are beyond your current level of understanding. Therefore, I recommend doing it the simple and stupid way: while(true) { string input; getline(cin, input); if(input == "open games") games(); else if(input == "open text") text(); else if(input == "open about") about(); else if(input == "options") cout << "games text about\n"; else cout << "unknown command\n"; }
74,277,297
74,293,070
Statically include large binary file in C++ executable in Visual Studio
I have a large binary file, ~1gb in size. I'd like to include this statically in a C++ executable compiled in Visual Studio 2019. The executable is built for Windows. I'd like to access the binary file at runtime, but don't want to ship it alongside the application. So reading at runtime from a file is not an option. I have seen the solution that just includes it as a byte array, but that is cumbersome, is there no better solution? How would including it as a resource file look like?
Can be done with Resource files. Right click project > Add > Resource File > Import > Select file > Choose a resource type name freely. #include <Windows.h> #include "resource.h" ... # IDR_SOMETHING is the resource identifier, can be found in the autogenerated resource.h HRSRC res = FindResource(NULL, MAKEINTRESOURCE(IDR_SOMETHING), "Res type name you choose"); DWORD size = SizeofResource(NULL, res); HGLOBAL data = LoadResource(NULL, res); data will be a simple pointer to start of memory where the resource is located.
74,277,675
74,277,741
How to resolve compilation terminated and g++ : fatal error in cpp on Ubuntu O.S
I wirte the code right why does it show's me fatal error ? I think i didn't miss anything then why my code shows me error where i didn't do anything wrong ? And what is the meaning of fatal error why it's occurres and how solve it ? The code is #include <iostream> using namespace std ; // Function call by reference using pointers //writing function for swap system // Call by reference using pointers void swapPointer(int* a, int* b){ //temp a b int temp = *a; //4 4 5 *a = *b; //4 5 5 *b = temp; //4 5 4 } int main(){ int x =4, y=5; cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl; swapPointer(&x, &y); //This will swap a and b using pointer reference cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl; return 0; } And the error code is cd "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/" && g++ Call_By_Value_&_Referance.cpp -o Call_By_Value_&_Referance && "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/"Call_By_Value_&_Referance [1] 24291 [2] 24292 [3] 24293 g++: error: Call_By_Value_: No such file or directory g++: fatal error: no input files compilation terminated. _Referance: command not found _Referance.cpp: command not found _Referance: command not found [1] Exit 1 cd "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/" && g++ Call_By_Value_ [2]- Exit 127 _Referance.cpp -o Call_By_Value_ [3]+ Exit 127 _Referance && "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/"Call_By_Value_ "It's also showing no input file what's it's mean by and if i need to refresh or reset my compiler than how can I do it in ubuntu?"
Don't put & in file names it confuses things as that character in Unix says to put the command into the background. Change Call_By_Value_&_Referance.cpp to Call_By_Value_And_Referance.cpp and anywhere else you have them. Don't post images, and reformat your question correctly.
74,277,767
74,278,577
VScode debugging: /dev/gpiomem Permission denied
Goal: I want to set up the VScode debugging on Ubuntu with a Raspberry Pi 400. What I have done: I am able to compile and run the program using sudo ./program_name. I have to run sudo otherwise I get permission denied error. I would like to not run VScode with root privileges as its generally discouraged. The problem: When I launch the debugger (press F5) and I include wiringPi.h, I get the following error: wiringPiSetup: Unable to open /dev/mem or /dev/gpiomem: Permission denied. Aborting your program because if it can not access the GPIO hardware then it most certianly won't work Try running with sudo? [1] + Done "/usr/bin/gdb" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-j40gmjsr.mas" 1>"/tmp/Microsoft-MIEngine-Out-vltmyj1b.a3g" My launch.json file looks like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "C/C++ - Build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/${fileBasenameNoExtension}", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "preLaunchTask": "C/C++: g++ build active file", "miDebuggerPath": "/usr/bin/gdb" } ] } What should I be doing to be able to launch the debugger with my setup? Can I add something to the launch.json file?
gdb does not have permission to open /dev/mem or /dev/gpiomem. There are two approaches you can go forward with. Option 1 -- Elevate GDB's permissions Instead of running vscode as root (which was already suggested, and you rightfully pointed out this is generally a bad idea), you can run gdb from within vscode as root, by having it call sudo gdb to launch the debugger as compared to just gdb. Option 2 -- De-escelated /dev/mem and /dev/gpiomem The other option is to give yourself access to /dev/mem and /dev/gpiomem without elevating your permissions. /dev/gpiomem is mostly harmless to give access to, but allowing non-root access to /dev/mem is a major security hole and not advisable. If it all possible, go with option 1. To give your use permission to open those files, you may do one of two things. 1.) Add yourself to the owning group. /dev/mem is owned by the group kmem, so adding your main user to that group will allow you read access. 2.) Modifying file permissions. sudo chmod ugo+xwr fname will allow any user to read, write, or execute that file. This is generally insecure, but helpful if you activate it only for a moment to solve some issue.
74,277,870
74,278,462
Parallizing loading from a model in file
I have a model mesh that I want to load its vertices, indices, in parallel. The problem is I had to remove return statements if eof is catched for each block, reading vertices, reading faces. also I'm not sure if that's correct approach. MVP Code is here. std::ifstream inp(file_name, std::ios::in | std::ios::binary); char buffer[40] = { 0 }; if (inp.eof()) { return false; } inp.read(buffer, 40); // making sure it is little endian auto ReadUnsignedIntLittleEndian = [&]() { unsigned int num = 0; for (int i = 0; i < 4; ++i) { if (inp.eof()) { throw - 1; // throw and exception } inp.read(buffer, 1); unsigned int tmp = (unsigned char)(buffer[0]); tmp <<= (i * 8); num = num | tmp; } return num; }; auto ReadReal = [&]() { inp.read(buffer, sizeof(T)); T num = *((T*)&(buffer[0])); return num; }; // read vertices #pragma omp for for (int i = 0; i < numVerts; ++i) { T x = ReadReal(); //if(inp.eof()) return; T y = ReadReal(); //if(inp.eof()) return; T z = ReadReal(); //if(inp.eof()) return; meshPtr->AddVertex(x, y, z); } // read edges #pragma omp for for (int i = 0; i < numEdges; ++i) { int v1 = ReadUnsignedIntLittleEndian(); int v2 = ReadUnsignedIntLittleEndian(); meshPtr->AddEdge(v1, v2); } } Here is how Add Vertex looks like: int Mesh<T>AddVertex(const Vertex<T> vertex) { int vertexIndex = vertices_.size(); auto v = std::make_shared<Vertex<T> >(vertex); v->SetIndex(vertexIndex); vertices_.push_back(v); return vertexIndex; }
To load data fast, make your class structure exactly match the file format. If the file contains repeated binary data: float float float int then your vertex class should be class Vertex { float x, y, z; int index; }; and reading it will be as easy as this Vertex *data = new Vertex[numVerts]; fread(data, sizeof(Vertex), numVerts, file);
74,278,732
74,278,967
How to get the real value of variable declared outside the loop, after using that varible in loop
I was working with loops and stuck with this problem. I had declared a variable outside the main code and then used it in the loop, but when I am returning the value of that variable after that loop, I am unable to get that value again. int n; int main () { // Sum of N natural numbers using FOR LOOP // 1st METHOD cin>>n; int sum = 0; for(int i=1 ; i<=n ; i++){ sum=sum+i; } cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum<<endl; // 2nd METHOD int sum4=0; for( n ; n>0 ; n--){ sum4+=n; } cout<<"\nThe sum of first "<< :: n<<" natural number is : "<<sum4<<endl; // Sum of N natural numbers using WHILE LOOP int sum1=0; while(n>0){ sum1+=n; n--; } cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum1<<endl; // Sum of N natural numbers using DO WHILE LOOP int sum2=0; do{ sum2+=n; n--; } while(n>0); cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum2<<endl; return 0; } Output: The sum of first 55 natural number is : 1540 The sum of first **0** natural number is : 1540 The sum of first **0 **natural number is : **0** The sum of first **-1** natural number is : **0** Can I declare a universal variable and use it in a loop, and at the same time after the loop quits it does not change the value of that variable and give the output as declared?
Can I declare a universal variable and use it in a loop and at the same time after loop quits it does not change the value of that variable and gives the output as declared. Let me rephrase that as: "Can I modify something, and at the same time, ensure it is not modified?" No, you can't. What you can do is copy something, and modify the copy. for(int i=n; i>0 ; i--){ sum4+=i; } int sum1=0; int i = n; while(i>0){ sum1+=i; i--; } int sum2=0; i = n; do{ sum2+=i; i--; } while(i>0);
74,278,907
74,279,273
Winsock Received buffers caracters
I am currently trying to create an application to send messages from a server to a client after initiating the connection by sending filters from the client to the server (like a subscrition). The entire application is done but I found out that the messages I send contain special caracters and dont have the size they are supposed to have. Here is an example with the filters (which are 3 letter words) that the server receives: Client connected! Bytes received: 3 REceived Filters:ATL���������������������� Although it says that 3 bytes were received, it prints 25 caracters. Here is the server side part of the code I use to receive the filters: // Receiving and sending data on server socket int iSendResult; // buffer for received msg char recvbuf[3]; int recvbuflen = 3; int compteurSend = 1; do { iResult = recv(ClientSocket, recvbuf, recvbuflen, 0); if (iResult > 0) { printf("\nBytes received: %d\n", iResult); printf("REceived Filters:"); std::cout << recvbuf << "\n" << std::endl; } ...... rest of the code to send back data ...... And here is the client side part of the code I use to send te filters: // Sending and receiving data // buffer for sending filters const char* sendbuf = "ATL"; int sendbuflen = strlen(sendbuf); // buffer for receiving char recvbuf[4000]; int recvbuflen = sizeof(recvbuf); // Send an initial buffer iResult = send(ConnectSocket, sendbuf, sendbuflen, 0); if (iResult == SOCKET_ERROR) { printf("send failed: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); return 1; } std::cout << "Filters Sent: " << "'" << sendbuf << "'" << " containing " << iResult << " bytes\n\n"; While the output of the cout on the client part is correct, stating " Filters Sent: 'ATL' containing 3 bytes ", I can only understand that the issue comes from the server side and the alocation of the buffer size. Did I miss anything or did I mess up on the use of sizeof and strlen.
std::cout << recvbuf is treating recvbuf as a null-terminated char* string, but there is no null terminator being sent by the client, and no null terminator being inserted by the server after the data received. So, operator<< ends up reading past the valid data, which is why you are seeing extra garbage being printed. So, you can either: update the client to send the null terminator (just make sure the server's recvbuf is large enough to receive it): const char* sendbuf = "ATL"; int sendbuflen = strlen(sendbuf) + 1; // <-- here add a null terminator artificially on the server side: char recvbuf[4]; do { iResult = recv(ClientSocket, recvbuf, sizeof(recvbuf)-1, 0); if (iResult > 0) { recvbuf[iResult] = '\0'; // <-- here printf("\nBytes received: %d\n", iResult); printf("Received Filters:"); std::cout << recvbuf << "\n" << std::endl; } since recv() tells you how many bytes are actually received, simply use ostream::write() instead of operator<<, eg: std::cout.write(recvbuf, iResult); std::cout << "\n" << std::endl;
74,279,284
74,280,459
Add a panel when a button is clicked? (beginner)
I want to add a panel to my main window, when a button is clicked (Like a menu where you can switch between home and e.g. settings). I'm still learning wxWidgets, so I don't know most of the things. I searched the Web but found nothing that really helped me. Here's me Code: ` #include "MainFrame.h" #include <wx/wx.h> MainFrame::MainFrame(const wxString& title): wxFrame(nullptr, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE & ~wxRESIZE_BORDER & ~wxMAXIMIZE_BOX) { //Startfenster erstellen wxPanel* homePanel = new wxPanel(this, wxID_ANY, wxPoint(50, 0), wxSize(1550, 900)); homePanel->SetBackgroundColour(wxColour(*wxWHITE)); wxPanel* menue = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(50, 900)); menue->SetBackgroundColour(wxColor(100, 100, 100)); //Startfenster gestalten wxStaticText* welcomeText = new wxStaticText(homePanel, wxID_ANY, "Willkommen!", wxPoint(600, 100), wxDefaultSize); welcomeText->SetFont(wxFont(50, wxFONTFAMILY_DEFAULT , wxFONTSTYLE_ITALIC, wxFONTWEIGHT_NORMAL)); wxInitAllImageHandlers(); //Bitmaps erstellen wxBitmap homesymbol; homesymbol.LoadFile(wxT("homesymbol.png"), wxBITMAP_TYPE_PNG); wxBitmap settingssymbol; settingssymbol.LoadFile(wxT("settingssymbol.png"), wxBITMAP_TYPE_PNG); wxBitmap timetablesymbol; timetablesymbol.LoadFile(wxT("timetablesymbol.png"), wxBITMAP_TYPE_PNG); //Knöpfe zum Menü hinzufügen wxBitmapButton* homeButton = new wxBitmapButton(menue, wxID_ANY, homesymbol, wxDefaultPosition, wxSize(50, 50), wxBU_AUTODRAW | wxNO_BORDER); wxBitmapButton* settingsButton = new wxBitmapButton(menue, wxID_ANY, settingssymbol, wxPoint(0, 850), wxSize(50, 50), wxBU_AUTODRAW|wxNO_BORDER); wxBitmapButton* timetableButton = new wxBitmapButton(menue, wxID_ANY, timetablesymbol, wxPoint(0, 50), wxSize(50, 50), wxBU_AUTODRAW | wxNO_BORDER); //Knöpfe ein Event zusteilen homeButton->Bind(wxEVT_BUTTON, &MainFrame::OnHomeClicked, this); CreateStatusBar(); } void MainFrame::OnHomeClicked(wxCommandEvent& evt) { } ` I got the code from OttoBotCode on YouTube. There's also a App.cpp App.h and MainFrame.h. Tell me if you also need the other ones! Thanks! What I tried: Make a sizer in the MainFrame.h class, add in the MainFrame.cpp class and control it in the void OnButtonClicked What I expected: I expected to show a panel that shows up when a button is pressed
SOLUTION: In the Header-File create the wxPanel with wxPanel* panel; (also create any controls you want to add/remove later on the panel. In the Eventmethod, use: panel->RemoveChild(exampleButton); panel->Refresh(); to remove Child "exampleButton"m which you created in the Header-File.
74,279,366
74,279,469
How to guarantee that std::cout always uses n width
I have output that looks like this: BTC-USDT [FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [BINANCE_US] 20457.50 20467.28 I would like it to look like this: BTC-USDT [ FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [BINANCE_US] 20457.50 20467.28 I think I am close with this code, but I am confused by setw() std::cout << pair << std::setfill(' ') << std::setw(15) << " [" << exch << "] " << fixed << setprecision(2) << bid << " " << ask << std::endl;
If you want a given value to have certain output characteristics, like width, alignment, etc, you need to apply the appropriate I/O manipulator(s) before you output the value, not after. In your example, you want pair to be left-aligned with a width of 9, and exch to be right-aligned with a with of 10, so apply std::setw and std::left/std::right accordingly, eg: std::cout << std::setfill(' ') << std::setw(9) << std::left << pair << " [" << std::setw(10) << std::right << exch << "] " << std::fixed << std::setprecision(2) << bid << ' ' << ask << std::endl; Output: BTC-USDT [ FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [BINANCE_US] 20457.50 20467.28 Online Demo
74,280,091
74,280,122
C++ read "enter" in command line
I have a very simple question. I have a project like below: #include <iostream> #include <fstream> using namespace std; int main(){ string file_name; cin >> file_name; ifstream file(file_name); if(file.good()){ cout << "File can be loaded"; } else{ cout << "Default file will be loaded"; } return 0; } In the command line, if I just hit Enter on my keyboard, I want to read nothing in file_name and then it will load a default file automatically. The current situation is it will wait until I type in something. How can I do this?
operator>> discards leading whitespace first (unless the skipws flag is disabled on the stream), and then reads until whitespace is encountered. Enter generates a '\n' character, which operator>> treated as whitepace. For what you want to do, use std::getline() instead, eg: #include <iostream> #include <fstream> using namespace std; int main(){ string file_name; getline(cin, file_name); if (file_name.empty()) { file_name = "default name here"; cout << "Default file will be loaded" << endl; } else { cout << file_name << " will be loaded" << endl; } ifstream file(file_name); if(file.is_open()){ cout << "File is opened" << endl; } else{ cout << "File is not opened" << endl; } return 0; }
74,280,456
74,280,636
Sorting by the last and first digit of numbers in an array (c++)
I need to sort an array of numbers by looking first to their last digit first (and also comparing if another number in the array has the same last digit) and first digit second from minimum to maximum like bubble sort but with a twist. For example: () array = {22,32,76,45,95,31,10,28,79,21} return should be: {10,21,31,22,32,45,95,76,28,79} I've tried using this method down below but it gives numbers at random or sometimes to some extend correct. Any help will be appreciated. I did try this block of code: #include <iostream> bool checkNumber(int a,int b){ // digits of A: int lastDigitA = a % 10; int firstDigitA = (a - lastDigitA) / 10; // digits of B: int lastDigitB = b % 10; int firstDigitB = (b - lastDigitB) / 10; // checkif big or small: if(lastDigitA == lastDigitB){ if(firstDigitA == firstDigitB){ return true; } else if(firstDigitA < firstDigitB){ return true; } else if(firstDigitA > firstDigitB){ return false; } } else if(lastDigitA < lastDigitB){ return true; } else if(lastDigitA > lastDigitB){ return false; } return false; } int main() { const int N = 10; int A[N] = {10,14,45,22,36,98,78,64,44,39}; for (int i = 0; i < N; i++) { int temp = A[i]; for (int j = N-1; j > i+1; j--) { if(checkNumber(A[i],A[j+1])){ int min = A[j]; A[j] = temp; A[i] = min; } } } for (int i = 0; i < N; i++) { std::cout << A[i] << " "; } return 0; } What i got: {39, 36, 14, 64, 45, 98, 14, 14, 14, 22} what i was expecting: {10, 22, 14, 44, 64, 45, 36, 78, 98, 39}
This example shows how code can cleanup if you use tested standard libary containers and algorithms. Use std::vector for variable input length arrays. For sorting use std::sort with a custom compare function. And you will end up with code with a lot less (potentially buggy) index managment. #include <algorithm> #include <iostream> #include <vector> #include <string> bool checkNumber(int lhs, int rhs) { while ((lhs > 0) || (rhs > 0)) { int l = lhs % 10; int r = rhs % 10; if (l != r) return l < r; lhs /= 10; rhs /= 10; } return false; } int main() { std::vector<int> values{ 22,32,76,45,95,31,10,28,79,21 }; std::sort(values.begin(), values.end(), checkNumber); for (const int value : values) { std::cout << value << " "; } return 0; }
74,280,858
74,281,983
How do I use Legacy OpenGL calls with QT6?
I'm new to Qt and am trying to import some older C++ openGL code. I'm currently using Qt 6.4. I've subclassed my OpenGL-using class to QOpenGlFunctions. Many of the glFoo calls "work" but the class also uses calls like glEnableClientState, glVertexPointer, glNormalPointer, glTexCoordPointer, glDisableClientState, glColor4fv, & glMaterialfv which come up with errors like undefined reference to __imp_glTextCoordPointer. Looking at the documentation these appear to no long be supported by "default" but it looks like they are supported using older versions of QOpenGlFunctions such as QOpenGlFunction_1_4 (https://doc-snapshots.qt.io/qt6-dev/qopenglfunctions-1-4.html). Trying to change my subclass from QOpenGLFunctions to QOpenGLFunctions_1_4 complains that really only QOpenGLFunctions_1_4_CoreBackend and QOpenGLFunctions_1_4_DeprecatedBackend exist but there appears to be no documentation on those and if I subclass to one of them I start seeing complaints about my constructor... How do I actually access the functions from these older versions of the class?
This question was answered by Chris Kawa over at the Qt Forums and it worked for me! Here is his answer: OpenGL 3.1 introduced profiles. Core profile does not support these old functions and Compatibility profile does. So first you have to make sure you have a context in version either lower than 3.1 (which does not support profiles) or 3.1 and up set up to use Compatibility profile. AFAIK Qt does not support OpenGL < 3.1 anymore, so you only have the latter option. If you're not sure what context you have you can simply do qDebug() << your_context and it will print out all the parameters, or you can query individual fields of it e.g. your_conext->format()->profile(). If your context is not set correctly the simplest way is to set it up like this before any OpenGL is initialized in your app: QSurfaceFormat fmt; fmt.setVersion(3,1); fmt.setProfile(QSurfaceFormat::CompatibilityProfile); fmt.setOptions(QSurfaceFormat::DeprecatedFunctions); QSurfaceFormat::setDefaultFormat(fmt); When you have the correct context you can access the deprecated functions like this: QOpenGLFunctions_1_4* funcs = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_1_4>(context()); if(funcs) { //do OpenGL 1.4. stuff, for example funcs->glEnableClientState(GL_VERTEX_ARRAY); } else { // Not a valid context? } And for anyone as amateur as I am, context() comes from QOpenGLWidget::context() which returns a QOpenGLContext*
74,281,083
74,281,350
Overloading the stream extraction operator - Invalid operands to binary expression
trying to overload the extraction operator in this class class Mystring { private: char* cstring; size_t size; public: friend std::istream &operator>>(std::istream &is, Mystring &str); the function: #include <iostream> #include "mystring.h" std::istream &operator>>(std::istream &is, Mystring &obj) { char *buff = new char[1000]; is >> buff; /* Invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *') */ obj = Mystring{buff}; delete [] buff; return is; } the error I get is: Invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *') when I tried to do something like this: is >> *buff; It reads only the first char Mystring name; std::cout << "name: " << std::endl; std::cin >> name; std::cout << "Your name is " << name; name: harry Your name is h
You get the error because the overload reading into a CharT*: template< class CharT, class Traits> basic_istream<CharT, Traits>& operator>>( basic_istream<CharT, Traits>& st, CharT* s ); was removed in C++20. In C++20, the closest you can get is to read into an array of known extent, using the new overload: template< class CharT, class Traits, std::size_t N > basic_istream<CharT, Traits>& operator>>( basic_istream<CharT, Traits>& st, CharT (&s)[N] ); which in this case could be used by declaring buff as an array instead of a pointer: std::istream &operator>>(std::istream &is, Mystring& obj) { if(char buff[1000]; is >> buff) obj = Mystring{buff}; return is; } I however suggest that you use a std::string instead of this pair: char* cstring; size_t size;
74,281,528
74,282,049
How to nest and combine a bunch of functions?
Like I have a bunch of functions, f, g, h.... How to easily combine them to new_func(x) = f(g(h(x)))? For convenience, we can assume that the last function has no parameters and that the other functions can be called nested. Could the template parameter package achieve this? update: Actually, I want a way can give me a combination of functions, like some_nest_method(f, g, h)(x) == f(g(h(x)))
you can merge the function recursively something like this template <typename F> F combine(F f){return f;} template <typename F, typename...Fs> auto combine(F f, Fs ...fs){ auto rest = combine(fs...); return [=](auto arg){ return f(rest(arg)); }; } https://godbolt.org/z/EzqjKr4q5
74,281,612
74,281,708
How to remove duplicates entries, sum them and assign to a new vector?
I have a std::vector<std::tuple<int, int, double> triplets that is sorted by the first term of the tuple. It looks like triplets = { {0, 0, 1}, {1, 2, 5}, {2, 2, 1}, {2, 2, 3}, {3, 0, 2}, {4, 4, 2}, {4, 4, 5}, {5, 5, 6} } I need to remove the duplicates tuples that have the same first and second entries, keep just one entry related to these duplicates and sum the third entries. The expected result must be triplets_new = { {0, 0, 1}, {1, 2, 5}, {2, 2, 4}, {3, 0, 2}, {4, 4, 7}, {5, 5, 6} } Is there a way to do that using STL or a for-like solution?
If sorted, loop through vector and check each element if it has same first and second value with the next element.If so, add the third value to this element and remove the next element. If not sorted, build an hash table and make {first,second} as key. loop through your vector, if key already exist, add the third to current value in the hash table, otherwise add it to the hash table. Last step is loop through the hash table and convert it back to a vector.
74,282,126
74,287,613
Bug or compilation error with some compilers for simple std::ranges code
I have a piece of code that uses the ranges library of C++20, taken from this SO anwer. The code is rejected by some compiler (versions) and some older GCC versions return garbage. Which compiler is right? The code is supposed to print the elements of the first column in a std::vector<std::vector>. #include <vector> #include <string> #include <ranges> #include <iostream> int main() { // returns a range containing only the i-th element of an iterable container auto ith_element = [](size_t i) { // drop the first i elements in the range and take the first element from the remaining range return std::views::drop(i) | std::views::take(1); }; // returns a range over the i-th column auto column = [ith_element](size_t i) { return std::views::transform(ith_element(i)) | std::views::join; // returns a range containing only the i-th elements of the elements in the input range }; std::vector<std::vector<std::string>> myvec = { { "a", "aaa", "aa"}, {"bb", "b", "bbbb"}, {"cc", "cc", "ccc"} }; for (auto const& v: myvec | column(0)){ std::cout << v << std::endl; } return 0; } Compiler Explorer Output: With GCC 10.1, 10.2, 10.3, 10.4: b Doesn't compile with GCC 11.1 and clang. error: no match for 'operator|' (operand types are 'std::vector<std::vector<std::__cxx11::basic_string<char> > >' and 'std::ranges::views::__adaptor::_Pipe<std::ranges::views::__adaptor::_Partial<std::ranges::views::_Transform, std::ranges::views::__adaptor::_Pipe<std::ranges::views::__adaptor::_Partial<std::ranges::views::_Drop, long unsigned int>, std::ranges::views::__adaptor::_Partial<std::ranges::views::_Take, int> > >, std::ranges::views::_Join>') Expected a bb cc Works as expected with GCC 11.2, 11.3, 12.1, 12.2, MSVC 19.33
GCC 11.2, 11.3, 12.1, 12.2, MSVC 19.33 are correct. Clang up to 15 does not support libstdc++'s <ranges> at all, and with libc++ the program works correctly. GCC 10.1, 10.2, 10.3, 10.4 and 11.1 mishandle std::views::drop(i) which is used in ith_element(i). Here's why std::views::drop(i) is complicated, and how old GCC did it wrong: How the argument is stored To make range | std::views::drop(i) work, the result of std::views::drop(i) must memorize the value of i. But should it store a copy of i, or a reference to i? GCC 10.x stores a reference when the argument is an lvalue. Hence, with GCC 10.x, the result returned by return std::views::drop(i) | std::views::take(1); contains a dangling reference. GCC 11.1 implements P2281R1 Clarifying range adaptor objects which makes such objects always store a copy of the argument. Brace vs. paren initialization Does range | std::views::drop(i) initialize the result with braces (std::ranges::drop_view{range, i}) or with parentheses (std::ranges::drop_view(range, i))? The relevant constructor of drop_view is drop_view(V, range_difference_t<V>). Note that the second parameter is a signed integer type, and list initialization disallows unsigned to signed conversion (because it's a narrowing conversion). Thus, with braces, the corresponding argument cannot be an unsigned integer (e.g. size_t). GCC 10.x somehow permits this conversion, while GCC 11.1 (with P2281R1 implemented) rejects it. Hence, with GCC 11.1, uses of std::views::drop(i) is always an error when i is size_t. GCC 11.2 and 12 implement P2367R0 Remove misuses of list-initialization from Clause 24, which changes std::views::drop to use parentheses instead of braces, and thus allows conversion from size_t to the difference type.
74,283,791
74,283,829
Why is the dynamically allocated memory released multiple times?
I use mutex and static variable to make sure the dynamically allocated memory to be released only once. But they are still released multiple times. Why? Thanks. I have read some threads saying it's not necessary to explicitly release static pointers. But It would be good to understand why that happens. // use C++-20 #include <iostream> #include <vector> #include <thread> #include <atomic> using namespace std; class A { private: static atomic_int *a;//=NULL; static std::mutex mutex_; public: A() { std::lock_guard<std::mutex> lock(mutex_); if (!a) { a = new atomic_int[10](); std::cout << "creation A..." << std::endl; } } ~A() { std::lock_guard<std::mutex> lock(mutex_); if (a) { delete[] a; //delete a; a = NULL; std::cout << "deletion A..." << std::endl; } } A(A &t) { cout << "copy..." << endl; } }; atomic_int *A::a = NULL; std::mutex A::mutex_; class B { private: static A *a; static std::mutex mutex_; public: B() { std::lock_guard<std::mutex> lock(mutex_); if (!a) { a = new A(); std::cout << "creation B ..." << std::endl; } } ~B() { std::lock_guard<std::mutex> lock(mutex_); if (a) { cout << "Delete B" << endl; delete a; a = NULL; } } void run() { std::cout << "Hello from B" << std::endl; } thread take_action() { return thread([this] { run(); }); } }; A *B::a = NULL; std::mutex B::mutex_; int main() { cout << "Hello World" << endl; vector<B> b; vector<std::thread> b_thread; for (int i = 0; i < 3; ++i) { b.push_back(B()); } // // B b1, b2; for (int i = 0; i < 3; ++i) { b[i].run(); } for (int i = 0; i < b.size(); ++i) { b_thread.push_back(b[i].take_action()); } for (int i = 0; i < b_thread.size(); ++i) { b_thread[i].join(); } // b1.run(); // b2.run(); return 0; } Result: Hello World creation A... creation B ... Delete B deletion A... creation A... creation B ... Delete B deletion A... creation A... creation B ... Delete B deletion A... Hello from B Hello from B Hello from B Hello from B Hello from B Hello from B
Because when you use such codes for (int i = 0; i < 3; ++i) { b.push_back(B()); } You will create three B objects, they are temporary variables, and they will destruct after push_back execute, so you allocate A pointer and delete it three times.
74,284,237
74,284,406
Rounding converting from string to double/float
I am trying to extract a number from a string and convert it into a double or float so I can do some numerical operations on it. I am able to isolate the variable I need so the string consists only of the number, but when I try to convert it to a float or double it rounds the value, ie from 160430.6 to 160431. //Helper Function to Extract Value of Interest //Based on column of final digit of numbers being same across various FLOPS output files double findValue(string &line, int &refN){ setprecision(100); string output; //go to end column and work backwards to get value string while(line[refN] != ' '){ output = line[refN] + output; refN = refN - 1; } const char* outputx = output.c_str(); double out = atof(outputx); //removing the const char* line and replacing atof with stod(output) runs into the same issue return out; } int main() { string name; cin >> name; ifstream file(name); //opens file if(!file.is_open()){"error while opening the file"; }else{ //Temporary Reference Definitions string ref = "TOGW"; int refN = 25; string line = findLine(file,ref); double MTOGW = findValue(line, refN); cout << MTOGW; } return 0; } I initially tried using stof() to convert, but that rounded. I have also tried using stod() and stold(), and last tried converting to a const char* and using atof(). I have messed with the setprecision() value, but also have not been able to solve it that way. I cannot use Boost
You were almost there. The rounding was occurring on output, so that's where you need to use setprecision. That and always use double instead of float to ensure you have enough precision in your variables. #include <vector> #include <ranges> #include <iomanip> #include <iostream> #include <string> using std::string; double findValue(string &line, int &refN){ //setprecision(100); string output; //go to end column and work backwards to get value string while(line[refN] != ' '){ output = line[refN] + output; refN = refN - 1; } const char* outputx = output.c_str(); double out = strtod(outputx, NULL); return out; } int main() { string s = " 160430.6"; int n = s.size() - 1; std::cout << std::setprecision(10) << findValue(s, n) << '\n'; } See it in action on the Godbolt compiler.
74,284,796
74,458,692
standalone version of folly::Synchronized
Is there a functional equivalent of https://github.com/facebook/folly/blob/main/folly/docs/Synchronized.md that is self-contained and preferably header only so I don't have to pull in entire folly library into my project?
There is a dicussion on reddit where folly::Synchronized also has been mentioned and some other solutions are provided. Probably you're searching for something like this: https://github.com/copperspice/cs_libguarded A snippet of there test code: shared_guarded<int, shared_mutex> data(0); { auto data_handle = data.lock(); ++(*data_handle); data_handle.reset(); data_handle = data.lock(); } auto data_handle = data.try_lock(); REQUIRE(data_handle != nullptr); REQUIRE(*data_handle == 1); Note: cs_libguarded requires C++17.
74,285,711
74,313,052
WinUI3: Unable to access UIElement defined programmatically inside a event delegate function
I'm creating the UI in WinUI3 with C++ programmatically. In XAML we can access an UIElement from all event delegate functions by its x:Name property, but when I define everything programmatically in c++ I was not able to set something like that. I want to make the UIElements defined programmatically accessible from Event delegate functions. I tried it accessing directly(like the below code) but was not able to achieve that. This is my Mainwindow file namespace winrt::TestWinUI::implementation { struct MainWindow: MainWindowT<MainWindow> { MainWindow(); int32_t MyProperty(); void MyProperty(int32_t value); void ComboxSelectionChanged(IInspectable const& sender, RoutedEventArgs const& args); Window window; StackPanel line; ComboBox combobox1; ComboBox combobox2; } MainWindow constructor MainWindow::MainWindow(){ combobox1.PlaceholderText(L"Select Country"); combobox1.Items().Append(box_value(L"India")); combobox1.SelectionChanged({ this,&MainWindow::ComboxSelectionChanged }); line.Children().Append(combobox1); window.Content(line); window.Activate(); } This is my App file void App::OnLaunched(Microsoft::UI::Xaml::LaunchActivatedEventArgs const&) { make<MainWindow>(); } Here I was able to access all the UIElements[like combobox1] of MainWindow in MainWindow() constructor and was able to get the screen programmatically. I have assigned the ComboxSelectionChanged event to combobox1 when item selection is changed. By this, I was able to get an event when the item selection was changed in combobox1. But when I tried to access combobox2 inside the ComboxSelectionChanged() event delegate function, I'm getting a runtime error like this It would be of great help if you could help me with accessing the UIElement from all event delegate functions when UIElements are defined programmatically.
Found the issue. The issue was because of App.xaml.cpp file. void App::OnLaunched(Microsoft::UI::Xaml::LaunchActivatedEventArgs const&) { make<MainWindow>(); } I was getting the crash in this case, I was not able to access UIElement defined programmatically inside an event delegate function, because the window is initialized with null in .h : winrt::Microsoft::UI::Xaml::Window window{ nullptr }; void App::OnLaunched(LaunchActivatedEventArgs const&) { window = make<MainWindow>(); window.Activate(); } But 2 windows will be created as I'm creating one programmatically and activating it and the window created programmatically was able to access UIElement defined programmatically inside an event delegate function So to make the windows which were created programmatically as the single main window, and not to use MainWindow.xaml, we can directly initialize App.xaml.h's window to the window which was programatically created. instead of calling make<MainWindow>(); This will solve the issue. Thank you
74,286,806
74,287,054
Pass derived class members to base class constructor
I have the following piece of code that is working but I don't understand why it works (inspired by a real life code base): Base class definition: class Pointers { private: int* Obj1; double* Obj2; public: Pointers(int* Obj1_, double* Obj2_) : Obj1{Obj1_}, Obj2{Obj2_} {} }; We now derive a class from our base class where we shadow the two pointers with an int and a double of the same name: class Objects : public Pointers { public: int Obj1{69}; double Obj2{72}; Objects() : Pointers(&Obj1, &Obj2) {} }; Within the constructor of Objects we call the constructor of Pointers and pass the adresses of Obj1 and Obj2. This actually works: The (shadowed) pointers will point to Obj1 (69)and Obj2 (72). My question is: Why is this working? I thought that in the first step the base class members are constructed (which are the two pointers) and only after that the derived class members (the int and double with the same name) are constructed. How can we pass these objects adresses to the base class constructor in the first place?
It works, because at the moment when you call your base class constructor, the derived class members int Obj1{69}; double Obj2{72}; are not yet initialized, but their addresses are already known, and you are using their addresses to initialize pointers in the base class. Note that it has little to do with shadowing. Of course if you try to print the pointed values in Pointers constructor Pointers(int* Obj1_, double* Obj2_) : Obj1{Obj1_}, Obj2{Obj2_} { std::cout << "Obj1: " << *Obj1 << ", Obj2: " << *Obj2 << std::endl; } you will get some garbage (UB), because pointed to values are not yet initialized. To make the code more clear avoid member fields assignments in the class body, rather use the constructor member initializer list: Objects() : Pointers(&Obj1, &Obj2), Obj1{69}, Obj2{72} {}
74,286,823
74,286,912
Conversion to string if input may be a string with spaces and line breaks
I am trying to convert any input of arithmetic type or char or string (including spaces and or line breaks) to a string. I tried using to_string which works for any input but string. I then tried void dataToString() { std::stringstream ss; ss << cryptedData; ss >> dataString; } which works even for strings as an input but will only take the string up to the first space. How can this be altered to store the entire string but also work for any input type mentioned above. Note that I can not use conditionals to run different code for different types as this is done in the constructor of a class so it wont compile if any of the possible inputs is run through any of the loops.
To get the contents of a stream as string, you can simply use the str member function: std::string dataToString() { std::ostringstream ss; ss << cryptedData; dataString = std::move(ss).str(); }
74,287,539
74,287,993
Why is the move ctor not called, in this std::move case?
If build and run this short example #include <memory> // for class template `unique_ptr` #define LOG() std::printf("[%p] %s\n", this, __PRETTY_FUNCTION__) class bar_t final { public: bar_t(int val) : m_val(val) { LOG(); } ~bar_t(void) { LOG(); } bar_t(bar_t&& dying) : m_val(std::move(dying.m_val)) { LOG(); } int get_value(void) const { return m_val; } private: int m_val; }; class foo_t final { public: foo_t(int a_val) : m_bar(a_val) { LOG(); } ~foo_t(void) { LOG(); } bar_t m_bar; }; std::unique_ptr<foo_t> gen_foo(int val) { return std::make_unique<foo_t>(val); } int main(int argc, char *argv[]) { #if 1 bar_t&& bar = std::move(gen_foo(42)->m_bar); // Bad // bar_t& bar = gen_foo(42)->m_bar; // gives same result as previous line #else bar_t bar(std::move(gen_foo(42)->m_bar)); // Good #endif std::printf("bar.get_value() = %d\n", bar.get_value()); return 0; } We'll have this output [0x5616d6510e70] bar_t::bar_t(int) [0x5616d6510e70] foo_t::foo_t(int) [0x5616d6510e70] foo_t::~foo_t() [0x5616d6510e70] bar_t::~bar_t() bar.get_value() = 0 where bar.get_value() returns 0 instead of 42. On the other hand, if we set the #if criterion to 0, build and run again, we'll have [0x55acef3bfe70] bar_t::bar_t(int) [0x55acef3bfe70] foo_t::foo_t(int) [0x7fff70612574] bar_t::bar_t(bar_t&&) [0x55acef3bfe70] foo_t::~foo_t() [0x55acef3bfe70] bar_t::~bar_t() bar.get_value() = 42 [0x7fff70612574] bar_t::~bar_t() where bar.get_value() returns 42. The question is why bar.get_value() returns 0 in the first case where the #if criterion is 1? How do we explain it? What happened under the hood that led to 0 instead 42, even though std::move is called to transfer value 42? Thanks.
It is widely recognised that std::move has a misleading name: it does not actually perform a move. Instead, it performs a cast, similar to static_cast<T&&>1. To perform a move, you need to invoke a move constructor or a move assignment operator. This doesn’t happen in your #if 1 code branch, but it does happen in the other branch with the explicit constructor call. Since the constructor isn’t marked explicit, you could also have written bar_t bar = std::move(gen_foo(42)->m_bar); This looks like the move is performed by std::move but what actually happens is that bar is initialised by calling its move constructor. Importantly, the reason why your first code does not involve lifetime extension (which would make it work even without the move) is that the temporary object that would need to be bound for lifetime extension to work is the return value of gen_foo(42), not gen_foo(42)->m_bar. Here’s an example where lifetime extension does work (note that we don’t need std::move since gen_foo(42) is already an rvalue): std::unique_ptr<foo_t>&& foo = gen_foo(42); // extends the lifetime bar_t& bar = foo->m_bar; // regular reference And, just for completeness, the following move-constructs foo. Once again std::move is unnecessary since gen_foo(42) is already an rvalue: std::unique_ptr<foo_t> foo = gen_foo(42); // move construction bar_t& bar = foo->m_bar; // regular reference Move constructing a std::unique_ptr is cheap and easy, and this code shows the common usage (there isn’t really a reason to use lifetime extension with std::unique_ptr objects). 1 The actual implementation is slightly more complex.
74,288,310
74,288,349
C++ How to create and return an iterator inside a function?
I tried to write a function that receives a list and an index and returns an iterator to the list that starts at that index. The function: template<class T> typename std::list<T>::iterator begin_it_at_index(list<T> list_to_iterate_on, const int index) { return next(list_to_iterate_on.begin(), index); } When I called the function to get the iterator, I did get the first element I wanted at the correct index, but when I did "++" on the iterator it just jumped out of the list instead of going to the next element. The code: list<int> temp = {10,20,50,100}; for (auto it = begin_it_at_index(temp, 1); it != temp.end(); ++it) { cout << *it << endl; } The output: 20 74211408 Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) What am I doing wrong?
You need to pass the container by reference to begin_it_at_index. Otherwise a value copy is taken, and the returned iterator is invalidated as the local list_to_iterate_on in the function goes out of scope. That is, template<class T> typename std::list<T>::iterator begin_it_at_index( list<T>& list_to_iterate_on, const int index ) is a fix.
74,288,827
74,288,937
Optimizing class layout by minimizing padding safely
I have the following type and my goal is to optimize the size of Storage: struct Inlined { int data[9]; }; // sizeof => 36 struct Allocated { int* data; size_t capacity }; // sizeof => 16 union Data { Inlined inlined; Allocated allocated; }; // sizeof => 40 struct Storage { // sizeof => 56 size_t size; bool is_allocated; Data data; }; I understand that sizes and layout may vary between compilers and platforms. My goal is to get more compact layout on at least some compilers/platforms. As you can see in my example, Data has 4 bytes of padding because Inlined and Allocated have different alignments and Data is 8-byte aligned. I am trying to find a way to squeeze boolean is_allocated into this padding. So far, I came up with the following structure and I would really appreciate if someone can confirm or deny "safety" / "legalness" of such type: struct CompactStorage { // sizeof => 48 size_t size; union { struct { bool is_allocated; Inlined inlined; }; struct { bool copy_of_is_allocated; Allocated allocated; }; }; }; To clarify, by safety I mean that I expect CompactStorage::is_allocated and CompactStorage::copy_of_is_allocated to be aliasing the same memory. And I expect that if I write to CompactStorage::is_allocated then it does not overwrite bytes aliased by CompactStorage::allocated (and vice versa). If that does not hold, then I consider CompactStorage unsafe as it cannot be used as a replacement for Storage. P.S. I know about bitfields and deliberately do not use them due to (proven) performance implications.
This is very much well-defined. From [class.mem] In a standard-layout union with an active member of struct type T1, it is permitted to read a non-static data member m of another union member of struct type T2 provided m is part of the common initial sequence of T1 and T2; the behavior is as if the corresponding member of T1 were nominated. Where common initial sequence is The common initial sequence of two standard-layout struct types is the longest sequence of non-static data members and bit-fields in declaration order, starting with the first such entity in each of the structs, such that corresponding entities have layout-compatible types [...] Which means you may use is_allocated and copy_of_is_allocated interchangeably, given that the structs are standard-layout types.
74,288,908
74,289,315
Accessing a 2D vector using push_back()
I am currently declaring my vector as follows std::vector<std::vector<int>> test(5, std::vector<int>(2,0)); I then access it like this ` for (int i = 0; i < 5; i++) { std::cin >> test[i][0]; std::cin >> test[i][1]; } ` Since the vector is static (5 Rows, with 2 columns), I would like to make it variable (rows variable, column staitc) by using push_back. However, I don't know how to access the individual columns. Maybe someone can help me. I already tried to access it with test.at(i).at(0) and test.at(i).at(1) but it wont work. Although I found this solution ` #include <iostream> #include <vector> using namespace std; int main() { std::vector<std::vector<int> >nns; int i = 5; nns.push_back(std::vector<int> {i}); for(int i = 0; i <nns.size(); i++) { for(int j = 0; j < nns[i].size(); j++) { std::cout << nns[i][j] << std::endl; } } } ` but there you have to define a static size (int i = 5).
You know how to push a vector into the vector of vectors. You wrote this: nns.push_back(std::vector<int> {i}); You do not have to specifiy the size i here, you can push an empty vector nns.push_back({}); Now nns has a single element. nns[0] has 0 elements. Pushing elements to nns[0] works exactly the same, just that its elements are not vectors but integers: nns[0].push_back(42); If you do that m-times then nn[0] will have m elements. Also resize works on the inner as well as on the outer vectors. For example to get n elements (vectors) each with m elements (integers): nns.resize(n); for (int i=0; i<nn.size(); ++i) nns[0].resize(m); TL;DR There is nothing special about nested vectors. The outer vectors work exactly the same as the inner vectors. You can construct them with or without elements and you can push elements or resize them.
74,289,725
74,289,898
Can there be an array made out of strings pointing to the same Memory Adress
I have 3 strings. I need to create an array out of those 3 strings, when I do it, it gets shown to me that the memory adresses of the strings are different than the ones of the array. Meaning that they dont point to the same thing. But I want that if I change the strings out of which I made the array, after the array creation, that the array will automatically update. And vice-versa. Is this possible and how can I do this. This is my code to show that they dont use the same Memory adresses, hence, they arent the same: std::string x = "x"; std::string y = "y"; std::string z = "z"; std::string letters[3] = {x, y, z}; std::cout << &x << "\t" << &y << "\t" << &z << "\n"; std::cout << &letters[0] << "\t" << &letters[1] << "\t" << &letters[2] << "\n"; The output is: 0x20b1bff730 0x20b1bff710 0x20b1bff6f0 0x20b1bff690 0x20b1bff6b0 0x20b1bff6d0
So here some code using pointers, that does what you want std::string* xp = new std::string("x"); std::string* yp = new std::string("y"); std::string* zp = new std::string("z"); std::string* letters[3] = { xp, yp, zp }; *xp = "X"; // changes *xp and *letters[0], since xp == letters[0] Now raw pointers are a bad idea, so the above should be written using smart pointers #include <memory> std::shared_ptr<std::string> xp = std::make_shared<std::string>("x"); std::shared_ptr<std::string> yp = std::make_shared<std::string>("y"); std::shared_ptr<std::string> zp = std::make_shared<std::string>("z"); std::shared_ptr<std::string> letters[3] = { xp, yp, zp };
74,290,006
74,290,404
Passing values to a Constructor which takes pointers parameter
I am very new to C++ and I am trying to initialize an object called GameObject, in a class called Room, which holds a gameObjects array. The constructor of the GameObject class takes pointers as the parameters to initialize the fields. But I keep getting the error saying that there is "No matching constructor for initialization of GameObject. Could someone tell me what is my mistake here? Sorry if this question is formatted badly, I am not used to asking C++ questions with multiple header files and source files. But please also correct me on this. GameObject GameObject::GameObject(string* _name, string* _description, char* _keyWord): name(_name), description(_description), keyWord(_keyWord){ } Room //error!, "No matching constructor for initialization..." gameObjects[0] = new GameObject("knife", "a knife", 'k'); gameObjects[1] = new GameObject("sword", "a sword", 's'); };
Well, you in the GameObject constuctor: GameObject::GameObject(string* _name, string* _description, char* _keyWord): name(_name), description(_description), keyWord(_keyWord){} You are accepting the two strings and a char by pointer. So maybe you meant to accept them by reference instead like this: GameObject::GameObject(string& _name, string& _description, char _keyWord): name(_name), description(_description), keyWord(_keyWord){} Which works fine. For instance take this program: #include<iostream> #include<string> struct my_obj { my_obj(std::string s, std::string s_, char c) : s__(s), s___(s_), char_(c) {} std::string s__{}; std::string s___{}; char char_{}; }; struct my_obj_2 { my_obj(std::string* s, std::string* s_, char* c) : s__(s), s___(s_), char_(c) {} std::string s__{}; std::string s___{}; char char_{}; }; int main() { my_obj my_obj_1("Hello", "Goodbye", 'C'); // works fine my_obj_2 m_my_obj_2("Hello", "Goodbye", 'c'); // doesn't work fine } (1): This works fine because it finds a matching constructor: std::string -> std::string (2): Whereas this doesnt work fine because it is this conversion: std::string -> std::string* So in conclusion just remove the pointers on the constructor and if you wanted to you could pass then by & or const & like this GameObject::GameObject(string& _name, string& _description, char _keyWord): name(_name), description(_description), keyWord(_keyWord){}
74,290,411
74,290,505
How to set `rpath` with gcc?
I have an executable that uses some shared objects. These shared objects have other shared objects as dependencies, and I want to set my main executable's rpath to include the directories for those dependencies, since runpath is not used for indirect dependencies. I'm trying to bake rpath into my ELF, however when using this: gcc -std=c++20 -o main main.cpp -lstdc++ -L./lib -Wl,-rpath,./lib The result is that ./lib is set in the ELF as RUNPATH and not RPATH: Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6] 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] 0x000000000000001d (RUNPATH) Library runpath: [./lib] 0x000000000000000c (INIT) 0x1000 ... Can someone explain why this happens? I was expecting ./lib to be defined in the RPATH section and not RUNPATH. Seems like RPATH section does not exist at all. I am using gcc version 11.1.0, with ld version 2.34. I know this might not be the best solution for managing indirect dependencies and I'd be happy to hear a better one, however I still wonder why -Wl,-rpath,./lib results in RUNPATH defined in the ELF, and not RPATH.
To get a DT_RUNPATH entry you need --enable-new-dtags. To get a DT_RPATH entry (which is deprecated) you need --disable-new-dtags. In your case, something like this: gcc -std=c++20 -o main main.cpp -lstdc++ -L./lib -Wl,--disable-new-dtags,-rpath,./lib I'll suggest to use an absolute path with rpath, I'm not sure from which directory relative paths are interpreted. There is also $ORIGIN if you want to use the executable as reference point. See https://man7.org/linux/man-pages/man1/ld.1.html and https://man7.org/linux/man-pages/man8/ld.so.8.html for more informations.
74,291,350
74,296,888
Python cannot find Boost.Python module
I try to create a simple C++ module for python with Boost, but python gives me ModuleNotFoundError: No module named 'MyLib'. The .py file is in the same location as MyLib.dll. UPD: if i change dll to pyd or replace add_library(MyLib MODULE MyLib.cpp) with PYTHON_ADD_MODULE(MyLib MyLib.cpp) I get another error: ImportError: DLL load failed while importing MyLib: The specified module could not be found. CMake set(Boost_NO_SYSTEM_PATHS TRUE) set(BOOST_ROOT "C:/local/boost_1_80_0") set(CMAKE_SHARED_MODULE_PREFIX "") find_package(PythonLibs REQUIRED) include_directories(${PYTHON_INCLUDE_DIRS}) link_directories(${PYTHON_LIBRARIES}) find_package(Boost COMPONENTS python310 REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) add_library(MyLib MODULE MyLib.cpp) target_link_libraries(MyLib ${Boost_LIBRARIES} ${PYTHON_LIBRARIES}) C++ #include <boost/python.hpp> auto* get() { return "Hello from C++"; } BOOST_PYTHON_MODULE(MyLib) { using namespace boost::python; def("get", get); } Python from MyLib import get get()
You mention that your binary module is named MyLib.dll. That is the first problem.[1], [2] On Windows, CPython expects binary modules to have extension .pyd. Either rename the DLL manually, or (as you mention) use PYTHON_ADD_MODULE instead of add_library to achieve the same automatically. Once you do this, another problem may appear: ImportError: DLL load failed while importing MyLib: The specified module could not be found. When you're unsure, the best way to debug such errors on Windows is to use a tool like https://github.com/lucasg/Dependencies to find which third party libraries are required, and possibly missing. In this case, the likely culprit will be the boost.python DLL. Generally boost.python is linked dynamically, since that allows multiple binary modules that depend on it to work together. Make sure that DLL is in the library search path and things should work.
74,292,315
74,430,470
thread_local storage, constructors, destructors, and tbb
It's my understanding that tbb may maintain pool threads for reuse... is there a way to ensure that data that I have declared using a modern C++ implementation as thread_local and with a non-trivial (default) constructor and destructor, which is initialized whenever the data is first used from a new thread is destroyed when tbb puts a thread into its pool and constructed again when the thread is pulled out of the pool? I am, as I said, currently just declaring my data as static and using the C++ thread_local specifier. EDIT: Apologies for not spelling this out initially, but an early respondent has made it clear that some assumptions might be made about the code I am hoping to update which are not valid. Refactoring usage of tbb isn't practical, because the code makes heavy use of it already and it is non-trivial to refactor them all, but I will need the threads created by it to still have access to the thread local data. A have hidden all access to thread_local data behind a small number of functions, which is what I was ideally hoping to change. Is there some way, perhaps with an additional thread_local value, that I can tell that I'm on a thread that has been reused since the last time the data was accessed? This is actually the ideal solution I would be looking for. One major disadvantage I find with refactoring all tbb calls in the application is not so much that there are many of them (although that is certainly a significant factor), but that then I am adding references to thread_local data in every single tbb thread, even if that particular thread did not ever actually need to access it. On systems which delay construction of thread_local data until it is first accessed, this overhead is undesirable. This is why, ideally, I would like to put the logic for it inside of the functions that accesses the thread_local data.
Program logic context and threads should be considered as another concept. Threads are used by your program context. Your program context might need one thread which is created and destroyed mutually with you program context, or might run on a thread provided from pooled thread, or might run on multiple threads which are created on demand or provide from thread pool. one thread Your program context just have to use a thread local instance. pooled threads Your program context needs to re-initialize/re-create a thread local instance, because the thread local instance was already used by a thread with another context and it is not irrelevant to your current program context. multiple thread If your program context is composed of multiple threads(e.g. func a() run on thread t1, func b() run on tread t2), you should not to use thread local storage because the program context can not ensure data integrity. In the code below, TBB assign a thread from pooled thread to a individual parallel_for context, so unless you initialize a thread local instance at first in your context, the data of this counting context would be collapsed. #include <ranges> #include <tbb/tbb.h> using namespace std; using namespace std::ranges::views; int main() { class A{ public: A(int ctx) : m_ctx(ctx){} int m_ctx; int m_num = 0; }; thread_local A a(-1); // already existing instance tbb::parallel_for(0, 7, 1, [](int i) { //a = A(i); // re-initialize thread local a.m_ctx = i; // not re-initize thread local, only assign context id for (auto i : iota(0, 5)) { a.m_num++; printf("ctx=%d count=%d th=%d \n", a.m_ctx, a.m_num, tbb::this_task_arena::current_thread_index()); } }); } Output with not re-initializing a thread local instance. So, the count value is collapsed because that TBB assigns a thread which already used a thread local instance for another program context. Output with no re-initialization is collapsed. ctx=0 count=1 th=0 ctx=0 count=2 th=0 ctx=0 count=3 th=0 ctx=0 count=4 th=0 ctx=0 count=5 th=0 ctx=1 count=6 th=0 ctx=1 count=7 th=0 ctx=1 count=8 th=0 ctx=1 count=9 th=0 ctx=1 count=10 th=0 ctx=2 count=11 th=0 ctx=2 count=12 th=0 ctx=2 count=13 th=0 ctx=3 count=1 th=1 ctx=3 count=2 th=1 ctx=3 count=3 th=1 ctx=3 count=4 th=1 ctx=3 count=5 th=1 ctx=5 count=1 th=2 ctx=5 count=2 th=2 ctx=5 count=3 th=2 ctx=5 count=4 th=2 ctx=5 count=5 th=2 ctx=6 count=1 th=4 ctx=6 count=2 th=4 ctx=6 count=3 th=4 ctx=6 count=4 th=4 ctx=6 count=5 th=4 ctx=2 count=14 th=0 ctx=2 count=15 th=0 ctx=4 count=1 th=3 ctx=4 count=2 th=3 ctx=4 count=3 th=3 ctx=4 count=4 th=3 ctx=4 count=5 th=3 Output with re-initializing thread local instance. it works well. ctx=0 count=1 th=0 ctx=0 count=2 th=0 ctx=0 count=3 th=0 ctx=0 count=4 th=0 ctx=0 count=5 th=0 ctx=1 count=1 th=0 ctx=1 count=2 th=0 ctx=1 count=3 th=0 ctx=1 count=4 th=0 ctx=1 count=5 th=0 ctx=2 count=1 th=0 ctx=2 count=2 th=0 ctx=2 count=3 th=0 ctx=2 count=4 th=0 ctx=2 count=5 th=0 ctx=5 count=1 th=2 ctx=5 count=2 th=2 ctx=5 count=3 th=2 ctx=5 count=4 th=2 ctx=5 count=5 th=2 ctx=6 count=1 th=0 ctx=6 count=2 th=0 ctx=6 count=3 th=0 ctx=6 count=4 th=0 ctx=6 count=5 th=0 ctx=4 count=1 th=3 ctx=4 count=2 th=3 ctx=4 count=3 th=3 ctx=4 count=4 th=3 ctx=4 count=5 th=3 ctx=3 count=1 th=1 ctx=3 count=2 th=1 ctx=3 count=3 th=1 ctx=3 count=4 th=1 ctx=3 count=5 th=1
74,293,348
74,293,466
Right bit shift in body of lambda used as a template argument doesn't compile on GCC
GCC doesn't compile this code, while other compilers (clang, msvc) do template<auto T> struct S { }; int main() { S<[]{int x,y; x<<y;}> s1; // compiles fine S<[]{int x,y; x>>y;}> s2; // error } error: error: expected ';' before '>>' token | S<[]{int x,y; x>>y;}> s2; | ^~ | ; However when I explicitly call operator>>, GCC accepts it struct S2 { void operator>>(S2 arg) { } }; S<[]{S2 x,y; x.operator>>(y);}> s2; // compiles It also does compile when I move the lambda definition outside of template parameter list auto lam = []{int x,y; x>>y;}; S<lam> s; // compiles Is it a compiler bug?
g++ is actually correct here. From [temp.names]/3 (C++20 Draft N4860): When a name is considered to be a template-name, and it is followed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-than operator. When parsing a template-argument-list, the first non-nested > is taken as the ending delimiter rather than a greater-than operator. Similarly, the first non-nested >> is treated as two consecutive but distinct > tokens, the first of which is taken as the end of the template-argument-list and completes the template-id. [Note: The second > token produced by this replacement rule may terminate an enclosing template-id construct or it may be part of a different construct (e.g., a cast). — end note] [Example: template<int i> class X { /* ... */ }; X< 1>2 > x1; // syntax error X<(1>2)> x2; // OK template<class T> class Y { /* ... */ }; Y<X<1>> x3; // OK, same as Y<X<1> > x3; Y<X<6>>1>> x4; // syntax error Y<X<(6>>1)>> x5; // OK — end example] The >> is treated as two > tokens. You can wrap it in brackets to enforce what you are trying to do if you want. template<auto T> struct S { }; int main() { S<[]{int x,y; (x>>y);}> s2; // now compiles fine } Note: it may be that both accepting or rejecting is correct, since it's a bit vague what is meant by nested. See comments.
74,294,181
74,294,258
redefined virtual function call
#include <iostream> class Base { public: virtual void foo() { std::cout << "Base::foo()\n"; }; }; class Derived : public Base { public: void foo() override { std::cout << "Derived::foo()\n"; Base::foo(); } }; int main() { Derived obj; obj.foo(); return 0; } Hello this is my code and I have a question, why I can call Base::foo() in Derived class if I already redefined it in Derived class, why compiler doesn't delete Base::foo in class Derived after redefine?
"why compiler doesn't delete Base::foo in class Derived after redefine" Because that isn't what virtual and override do. When you provide an override to a base class function, you do not replace it. You are defining a new version for that function. The base class's implementation continues to exist and to be accessible. Consider the following code. Someone can still use a Base object, and the behaviour should not be changed because Derived exists. The output for base_obj.foo() should continue to be "Base::foo()" regardless of the existance of Derived. : #include <iostream> class Base { public: virtual void foo() { std::cout << "Base::foo()\n"; } }; class Derived : public Base { public: void foo() override { std::cout << "Derived::foo()\n"; } }; int main() { Derived obj; obj.foo(); Base base_obj; base_obj.foo(); return 0; } Also consider that multiple classes can derive from Base. I could add a class MyClass : public Base with its own version of foo(), and it should not interfere with how Base or Derived objects behave. If overriding a member function would cause the base member function to be entirely replaced or removed, it becomes nearly impossible to reason about code without reading carefully every class that derives from it. And unless your IDE provides tools for that, it implies reading all of the code base. It would make it C++ code that uses polymorphism extremely difficult to understand.
74,294,427
74,294,507
Wrong results when assigning to int array in c++
#include <iostream> using std::cout; using std::cin; using std::endl; int main(){ int v[5]; int a[5][5]; int i = 0, j = 0; for (i = 0; i < 5; i++){ v[i] = 0; for (j = 0; j < 5; j++){ a[i][j] = 0; cout << "A[" << i << ", " << j << "] = " << endl; cin >> a[i][j]; v[i] = v[i] + a[i][j]; } v[i] = v[i] / 5; } for (i = 0; i < 30; i++){ cout << "v[" << i << "] = " << v[i] << endl; } } When I remove the v[i] = 0 line just under the first loop the code runs but returns very large numbers. I don't understand how this is happening. Grateful for any help. Edit: thanks you for all the replies. I think I understand why I got downvotes. To clarify, this is for a beginners course and we were given the bare-bones of the language mostly to train logic. The question itself is pretty nonsensical as it asks us to declare the array as a int despite the fact that the answer is distorted by integer division.
Initializing a value in c++ like int v[5]; just reserves space. It does nothing to initialize the values to 0 or something. Anything could be in those five indices. Whatever happens to be in that address space.
74,294,494
74,294,589
cleanQueue - cleanup function. C++
Hi so I have a task to create a full queue with integers I need to do a clean function like that: `void cleanQueue(Queue* q); ` The Queue form is that: typedef struct Queue { int * arr; } Queue; Thanks alot!
Well if you need the implemenatation to be like: typedef struct Queue { int * arr; } Queue; you could simply do: void cleanQueue(Queue* q) { delete q->arr; } or if you initialise the arr data member as an array like {1, 2, 3, 4}you would do it like this; void cleanQueue(Queue* q) { delete[] q->arr; } So you're program would be: typedef struct Queue { int * arr; } Queue; void cleanQueue(Queue* q) { delete q->arr; } int main() { // ... Do something } Basically what is happening is you are accessing the arr of the Queue using the -> operator and deleting the pointer to int: int* arr.
74,294,590
74,294,753
why we use two conditions in head!=nullptr && head->next != nullptr in floyd cycle detection algorithm?
i want to know that why we use two conditions i am confused.. while head and head->next are not equal to null which means head and head's next will point to null ho is that possible int detectCycle(Node *& head) { Node * fast = head; Node * slow = head; while(fast!=nullptr && fast->next!=nullptr) // i am confused in these two conditions { slow = slow->next; fast = fast->next->next; if(fast == slow) return 1; } return false; }
while head and head->next are not equal to null which means head and head's next will point to null ho is that possible From the code presented, I guess you mean fast where you wrote head. If fast is null then fast!=nullptr evaluates to false. In that case it would produce undefined behavior to evaluate fast->next, but that is not an issue because the && operator has short-circuiting behavior. That is, if the left operand of an && operator evaluates to false, then the right operand is not evaluated. Thus the while condition is safe to evaluate, and it evaluates to true if and only if neither fast nor fast->next is a null pointer. Supposing that head is a pointer to the head node of a linked list, the code seems to assume that the last node can be recognized by having a next pointer whose value is null. This is a very common paradigm, so it is absolutely reasonable to think that as the fast pointer is advanced through the list (two links at a time), it will eventually become the case that either it or its successor will be the last node, and therefore have a null next pointer. If that happens, then the list is proven not to loop. If the list does loop, however, then it will eventually be the case that slow, which advances only one link at a time instead of two, will point to the same node that fast does. When that is detected, the list is known to loop.
74,294,744
74,294,793
Displaying results of methods on the screen
My task is to practice inheritance, putting all the classes in separate files. I have a base class Circle and a derived class Cylinder. What I'm stuck on is trying to display on the screen the result of my calculated area and volume for an object B of a Cylinder type. I found a way to do that for a Circle, though it doesn't work for my Cylinder. circle.h #pragma once #include <iostream> class Circle { public: float r; Circle(); Circle(float r); Circle circumference(); Circle area(); void view(); void getArea(); void getCircum(); }; circle.cpp #include "circle.h" #include <cmath> using namespace std; Circle::Circle() : r(5) { cout << "Default constructor has been called for a circle\n"; } Circle::Circle(float r) { this->r = r; cout << "Constructor with parameters has been called for a circle\n"; } void Circle::view() { cout << "Radius = " << r << endl; } Circle Circle::circumference() { return 2 * M_PI * r; } Circle Circle::area() { return M_PI * pow(r, 2); } void Circle::getArea() { cout << "Area = " << r << " m^2"; } void Circle::getCircum() { cout << "Circumference = " << r << " m"; } cylinder.h #pragma once #include <iostream> #include "circle.h" class Cylinder : public Circle { public: float h; Cylinder(); Cylinder(float r, float h); void view(); double area(); double volume(float r, float h); void getArea(); void getVolume(); }; cylinder.cpp #include "cylinder.h" #include <cmath> using namespace std; Cylinder::Cylinder() : h(7) { cout << "Default constructor has been called for a cylinder\n"; } Cylinder::Cylinder(float r, float h) : Circle(r) { this->h = h; cout << "Constructor with parameters has been called fo a cylinder\n"; } void Cylinder::view() { Circle::view(); cout << "Height = " << h << endl; } double Cylinder::area() { return 2 * M_PI * r * h; } double Cylinder::volume(float r, float h) { return M_PI * pow(r, 2) * h; } void Cylinder::getArea() { cout << "Area = " << h; } void Cylinder::getVolume() { cout << "Volume = " << h; } main.cpp #include <iostream> #include "circle.h" #include "cylinder.h" using namespace std; int main() { Circle A; A.view(); Circle A1(8); A1.view(); Cylinder B; B.view(); Cylinder B1(4, 6); B1.view(); //A.area().getArea(); //cout << endl; //A.circumference().getCircum(); //cout << endl; //A1.area().getArea(); //cout << endl; //A1.circumference().getCircum(); B.area().getArea(); return 0; } The error that I'm getting: main.cpp: In function ‘int main()’: main.cpp:26:14: error: request for member ‘getArea’ in ‘B.Cylinder::area()’, which is of non-class type ‘double’ 26 | B.area().getArea(); | ^~~~~~~ I feel like neither my code in main() for instance B, nor my methods getArea() and getVolume() in class Cylinder, are correct. And there is probably a better approach to do the same for an object A and A1 of a Circle type, though the code I commented out actually works. I know that this is a dumb question, and such things should be quite straightforward, but I am trying to learn and would be grateful for any advice on how I can fix this.
In your getArea() function, instead of saying: cout << "Area = " << endl; Just say: cout << "Area = " << area() << endl; Then in your main.cpp, just call B.getArea(). Hope this helps!
74,295,014
74,323,347
Compile a .cpp file for an Arduino project
I'm trying to start an Arduino project with Arduino IDE and I'd like to use external C++ code outside the .ino main file. In particular, I have the following file: arduino.ino <- main .ino file /HeartSensor HeartSensor.h HeartSensor.cpp /oledScreen oledScreen.h oledScreen.cpp To import the two files in the folders I did the following: #include "HeartSensor/HeartSensor.h" #include "oledScreen/oledScreen.h" The HeartSensor.h file, for example, contains the following code: #ifndef HEARTSENSOR_H #define WINDOWSIZE 50 #define HEARTSENSOR_H #include <Arduino.h> class HeartSensor{ private: float bpm = 0.0; int heartStatus = 0; bool receivingSignal = false; float ecgSignal[WINDOWSIZE]; public: // Constructors HeartSensor(); ~HeartSensor(); // Getters float getBPM(){ return bpm; }; int getHeartStatus(){ return heartStatus; }; bool getReceivingSignal(){ return receivingSignal; }; // Setters void setBPM(const float& newBpm){ bpm = newBpm; }; void setHeartStatus(const int& newHeartStatus){ heartStatus = newHeartStatus; }; void setReceivingSignal(const bool& newReceivingSignal){ receivingSignal = newReceivingSignal; }; void addSample(const float& newSample); }; #endif And the HeartSensor.cpp file contains the following code: #include "HeartSensor.h" HeartSensor::HeartSensor(){ } void HeartSensor::addSample(const float& newSample){ for(int i = 1; i < WINDOWSIZE-1; i++){ ecgSignal[i-1] = ecgSignal[i]; } ecgSignal[WINDOWSIZE-1] = newSample; } If I try to access one the member functions in the header file, I have no problem. However, if I try to access a function that is in the cpp file like so: HeartSensor* myHeartSensor; myHeartSensor->addSample(0.0); then the following error shows up: arduino.ino:36: undefined reference to `HeartSensor::addSample(float const&)' collect2: error: ld returned 1 exit status Do you know how I can compile the cpp files?
Lay out your project as: arduino.ino <- main .ino file /src /HeartSensor HeartSensor.h HeartSensor.cpp /oledScreen oledScreen.h oledScreen.cpp To import the two files in the folders, do the following: #include "src/HeartSensor/HeartSensor.h" #include "src/oledScreen/oledScreen.h"
74,295,100
74,296,946
What's a good alternative to PAUSE for use in the implementation of a spinlock?
I am working on making a fiber-based job system for my latest project which will depend on the use of spinlocks for proper functionality. I had intended to use the PAUSE instruction as that seems to be the gold-standard for the waiting portion of your average modern spinlock. However, on doing some research into implementing my own fibers, I came across the fact that the cycle duration of PAUSE on recent machines has increased to an adverse extent. I found this out from here, where it says, quoting the Intel Optimization Manual, "The latency of PAUSE instruction in prior generation microarchitecture is about 10 cycles, whereas on Skylake microarchitecture it has been extended to as many as 140 cycles," and "As the PAUSE latency has been increased significantly, workloads that are sensitive to PAUSE latency will suffer some performance loss." As a result, I'd like to find an alternative to the PAUSE instruction for use in my own spinlocks. I've read that in the past, PAUSE has been preferred due to it somehow saving on energy usage which I'm guessing is due to the other often quoted factoid that using PAUSE somehow signals to the processor that it's in the midst of a spinlock. I'm also guessing that this is on the other end of the spectrum power-wise to doing some dummy calculation for the desired number of cycles. Given this, is there a best-case solution that comes close to PAUSE's apparent energy efficiency while having the flexibility and low-cycle count as a repeat 'throwout' calculation?
I'm guessing is due to the other often quoted factoid that using PAUSE somehow signals to the processor that it's in the midst of a spinlock. Yes, pause lets the CPU avoid memory-order mis-speculation when leaving a read-only spin-wait loop, which is how you should spin to avoid creating contention for the thread trying to unlock that location. (Don't spam xchg). See also: How does x86 pause instruction work in spinlock *and* can it be used in other scenarios? Does cmpxchg write destination cache line on failure? If not, is it better than xchg for spinlock? - spin read-only (with pause) if the first atomic RMW fails to take the lock. You do want to start with an RMW attempt so you don't get a Shared copy of the cache line and then have to wait for another off-core request; if the first access is an RMW like xchg or lock cmpxchg, the first request the core makes will be an RFO. Locks around memory manipulation via inline assembly a minimal x86 asm spinlock using pause (but no fallback to OS-assisted sleep/wake, so inappropriate if the locking thread might ever sleep while holding the lock.) If you have to wait for another core to change something in memory, it doesn't help much to check much more frequently than the inter-core latency, especially if you'll stall right when you finally do see the change you've been waiting for. Dealing with pause being slow (newer Intel) or fast (AMD and old Intel) If you have code that uses multiple pause instructions between checking the shared value, you should change the code to do fewer. See also Why have AMD-CPUs such a silly PAUSE-timing with Brendan's suggestion of checking rdtsc in spin loops to better adapt to unknown delays from pause on different CPUs. Basically try to make your workload not as sensitive to pause latency. That may also mean trying to avoid waiting for data from other threads as much, or having other useful work to do until a lock becomes available. Alternatives, IDK if this is lower wakeup latency than spinning with pause On CPUs new enough to have the WAITPKG extension (Tremont or Alder Lake / Sapphire Rapids), umonitor / umwait could be viable to wait in user-space for a memory location to change, like spinning but the CPU wakes itself up when it sees cache coherency traffic about a change, or something like that. Although that may be slower than pause if it has to enter a sleep state. (You can ask umwait to only go into C0.1, not C0.2, with bit 0 of the register you specify, and EDX:EAX as a TSC deadline. Intel says a C0.2 sleep state improves performance of the other hyperthread, so presumably that means switching back to single-core-active mode, de-partitioning the store-buffer, ROB, etc., and having to wait for re-partitioning before this core can wake up. But C0.1 state doesn't do that.) Even in the worst case, pause is only about 140 core clock cycles. That's still much faster than a Linux system call on a modern x86-64, especially with Spectre / Meltdown mitigation. (Thousands to tens of thousands of clock cycles, up from a couple hundred just for syscall + sysret, let alone calling schedule() and maybe running something else.) So if you're aiming to minimize wakeup latency at the expense of wasting CPU time spinning longer, nanosleep is not an option. If might be good for other use-cases though, as a fallback after spinning on pause a couple times. Or use futex to sleep on a value changing or on a notify from another process. (It doesn't guarantee that the kernel will use monitor / mwait to sleep until a change, it will let other tasks run. So you do need to have the unlocking thread make a futex system call if any waiters had gone to sleep with futex. But you can still make a lightweight mutex that avoids any system calls in the locker and unlocker if there isn't contention and no threads go to sleep.) But at that point, with futex you're probably reproducing what glibc's pthread_mutex does.
74,295,182
74,295,368
How to fill QAbstractTableModel with another's class attribute (2D array)
I have class, which reads data from file to 2D array. So i need to display that array in qml TableView. I have QVector<QVector> table; to display it as data in my TableModel. The OperatingFiles object creates in main.cpp it contains functions to encode/decode passwords and save them to file. Functions for this object is also called from qml code So what i want is to make "table = passwordsDecoded" somewhere but i don't know how to do it. OperatingFiles.h : class OperatingFiles : public QObject { Q_OBJECT public: OperatingFiles(); public slots: QVector<QVector<QString>> getVector(); // returns passwordsDecoded private: QVector<QVector<QString>> passwordsDecoded; }; #endif // OPERATINGFILES_H TableModel.h: class TableModel : public QAbstractTableModel { Q_OBJECT QVector<QVector<QString>> table; public: explicit TableModel(QObject *parent = nullptr); int rowCount(const QModelIndex & = QModelIndex()) const override; int columnCount(const QModelIndex & = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; QHash<int, QByteArray> roleNames() const override; }; TableModel.cpp: #include "tablemodel.h" TableModel::TableModel(QObject *parent) : QAbstractTableModel{parent} { QVector<QString> mini; // this only for test that it really appears in TableView (it appears) mini.append("rstrst"); mini.append("rstrst"); mini.append("rstrst"); table.append(mini); table.append(mini); table.append(mini); } int TableModel::rowCount(const QModelIndex &) const { return table.size(); } int TableModel::columnCount(const QModelIndex &) const { return table.at(0).size(); } QVariant TableModel::data(const QModelIndex &index, int role) const { switch (role) { case Qt::DisplayRole: return table.at(index.row()).at(index.column()); default: break; } return QVariant(); } QHash<int, QByteArray> TableModel::roleNames() const { return { {Qt::DisplayRole, "display"} }; } qml: TableView { anchors.fill: parent columnSpacing: 1 rowSpacing: 1 clip: true model: TableModel{} delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 border.width: 0 Text { text: display anchors.centerIn: parent } } } main.cpp: #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "controlbuttons.h" #include "operatingfiles.h" #include "tablemodel.h" int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); qmlRegisterType<TableModel>("TableModel", 0,1,"TableModel"); QQmlApplicationEngine engine; ControlButtons *appManager = new ControlButtons(&app); engine.rootContext()->setContextProperty("appManager", appManager); OperatingFiles *fileOperator = new OperatingFiles(); engine.rootContext() -> setContextProperty("fileOperator", fileOperator); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); } I tried to make functions in TableModel that could fill "table" with data from my object which was called directly from qml ("OnClicked:"), tried make constructor which will get object with 2D array. I seen ton of vids and read docs but literally no idea how to do it. So whole chain is: choose file✓ -> read file✓ -> decode✓ -> fill 2D array✓ -> send to model (Somehow) -> appear it in UI✓ Maybe it could be done if i make my 2D array global so i could access to it from anywhere but it not a solution. Thanks!
The easiest modification would be to add a Q_INVOKABLE to your TableModel which allows to set the table class TableModel : public QAbstractTableModel { ... Q_INVOKABLE void setTable(const QVariant& value) { //inline for briefity beginResetModel(); table = value.value<QVector<QVector<QString>>>(); endResetModel(); } } Then from QML you can do <id of TableModel>.setTable(fileOperator.getVector()) Another option would be a Q_PROPERTY with a similar setter method. Then you would use <id of TableModel>.table = fileOperator.getVector() I'm not sure about how you want your structure to look like, but if you don't need TableModel to be instantiatable from QML you could make it available as contextProperty the same way as you did with the fileOperator. Then you will have more control on the TableModel, for instance, you can call a fill function from C++ side when done.
74,295,185
74,295,626
What is the difference between an "enumeration type" and an "enumerated type" in C++?
The Standard "apparently" defines "enumeration type" in [dcl.enum]/1. The term "enumerated type" is defined here.
The first link (http://eel.is/c++draft/dcl.enum#1) explains what an enumeration type in C++ is. This is where C++ officially defines it. The other link (http://eel.is/c++draft/enumerated.types) is about the C++ standard library. This link explains how you have to read the description of the standard library, that comes in the subsequent chapters. For example in chapter 29 there is the description of a type ios_base::seekdir: The type seekdir is an enumerated type (16.3.3.3.3) that contains the elements indicated in Table 120. And then they explain that there are three possible values beg, cur end. This may be intuitive enough for most people who want to use that library of chapter 29. But as this enumeration type is part of the public interface of that library, others may think, that just saying there are three possible values is not precise enough. The reader must precisely know what comes out of a function that returns an seekdir. And therefore your second link clearly explains what they mean, when saying "it is an enumerated type that contains these elements." The wording "synonym of enumeration" means that exactly the same thing (the same bits and bytes), that is provided by an enumeration type, can be also be provided by other types. If for example you have a function that returns an enum with one=1, two=2, three=3, you are free to see the returned value as an element of that enum type or just as an integer. At library level there is no difference between both interpretations of the bits that are coming out of such a function. The interpretation comes only when you include a header file, where the function is precisely defined together with its return type. The reason why in the second link there is not only the definition of the enum type but also the definition of the constants is that at library level the individual elements (the numbers) of the enum are not visible. At library level it is only visible, that there is an integer. But when you want to use a library you must know the individual values. In order to achieve this, the library oxposes them as constants. Comming back to the seekdir type, with your second link it is clarified that it will be this type: enum enumerated { beg, cur, end }; inline const enumerated beg(beg); inline const enumerated cur(cur); inline const enumerated end(end); With these inlined constants you can find out what numbers are actually behind the enum without having the header file.
74,295,409
74,295,422
Why is my variable jumping in value when I add an "if" condition?
The code below, without the if statement, count's up from 1 to infinite and shows this in the console as intended. If I add the if statement, I get what's shown in the screenshot below. Why does this happen? #include <Arduino_MKRIoTCarrier.h> MKRIoTCarrier carrier; int a; int r,g,b; void setup() { // put your setup code here, to run once: Serial.begin(9600); // Initialize serial and wait for port to open: Serial.begin(9600); // This delay gives the chance to wait for a Serial Monitor without blocking if none is found delay(1500); carrier.begin(); carrier.display.setRotation(0); a = 1; } void loop() { // put your main code here, to run repeatedly: Serial.println(a); a = a + 1; if (a = 10) { carrier.leds.setPixelColor(0, 255, 0, 0); carrier.leds.show(); } }
In c++, comparison is ==, so you need to write if (a == 10). When you write, a = 10, that's an assignment: a will have the value of 10 and the evaluation value is also 10 (to be precise, reference to a which is 10), thus in if() it evaluates to true.
74,295,761
74,296,011
Changing the text of the "static text" control and its color at once (a bad behavior occurred)
I am trying to change the text of the "static text" control and its color at once, and I have done that, but the problem is when changing the text first and then changing the color of that text, it takes a little noticeable time between changing the text and its color. bool IsGameOpen = false; INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { SetTimer(hDlg, GAME_STATUS_TIMER, 1000, NULL); return TRUE; } case WM_TIMER: switch (wParam) { case GAME_STATUS_TIMER: if (Mem->FindProcess()) { SetDlgItemTextW(hDlg, GAME_CURRENT_STATUS_LBL, L"Open"); IsGameOpen = true; } else { SetDlgItemTextW(hDlg, GAME_CURRENT_STATUS_LBL, L"Closed"); IsGameOpen = false; } break; } return TRUE; case WM_CTLCOLORSTATIC: { if ((HWND)lParam == GetDlgItem(hDlg, GAME_CURRENT_STATUS_LBL)) { if (IsGameOpen) { SetTextColor((HDC)wParam, RGB(29, 122, 9)); return (BOOL)GetSysColorBrush(COLOR_MENU); } else { SetTextColor((HDC)wParam, RGB(176, 12, 12)); return (BOOL)GetSysColorBrush(COLOR_MENU); } } break; } } return FALSE; } What's wrong with my code that makes the program take a little noticeable time between changing the text and its color?
As stated in comments, the Static control is likely being repainted immediately, and thus sending WM_CTLCOLORSTATIC to you, while SetDlgItemTextW() is being processed, but you haven't updated your IsGameOpen variable yet, so the new color doesn't take effect until the next time the Static control has to be repainted. Try this instead: case GAME_STATUS_TIMER: IsGameOpen = Mem->FindProcess(); SetDlgItemTextW(hDlg, GAME_CURRENT_STATUS_LBL, IsGameOpen ? L"Open" : L"Closed"); break;
74,296,129
74,296,221
RAM, Memory cell and address
I am trying to get a sound understanding about how RAM works in most computers. I am watching videos and reading online but haven't got a straight clear answer. I just have two questions: Is Memory cell the same as memory address? Is there a difference? What is the smallest unit of addressable memory -> Here I am getting conflicting info, some say It is 1 byte, some say it is 1 bit. In C++ byte seems to be the smallest data type. What if I want to store a variable that either has the value 0 or 1, is there no data type that can store just 1 bit ? I see even the boolean data type takes 1 byte, even though it could be just 0 or 1? So would it be fair to say that the smallest unit of addressable memory is a byte and not a bit?
The smallest addressable unit is a byte (in most current computers that you will come accross) To set a variable to 0 or 1 will require that variable to be at least one byte. But you can use individual bits in one byte for different bits You do that using bit fields in structs in c or by bit level operations on bytes (or larger)
74,296,345
74,299,202
How to remove a Python function from a module using C++?
Creating an application in C++, I integrated CPython to facilitate the development of certain top-level logics. The application has a plugin subsystem, which can loaded/unloaded plugins at runtime, this implies to add and remove Python definitions at runtime. I found that I can add functions with PyModule_AddFunctions, and similarly, I can add constants, objects, etc... But I found no equivalent PyModule_RemoveFunction. How to remove a Python function from a module using C++? Note: Ideally, I would like to avoid solutions like: Removing the full module and reloading everything Crafting Python code, that when executed would remove the function. Let see an example: DISCLAIM: I removed most of the error checks for simplicity. #define PY_SSIZE_T_CLEAN #include <Python.h> //before std includes // Just an example function to add/remove from Python static PyObject* log(PyObject* , PyObject* args) { //Do something Py_INCREF(Py_None); return Py_None; } // Setup a "AppModule" module PyMODINIT_FUNC initAppModule() { static PyModuleDef AppModuleInfo{ PyModuleDef_HEAD_INIT, "AppModule", // name of module nullptr, // module documentation, may be NULL -1, // size of per-interpreter state of the module, or -1 if the module keeps state in global variables. nullptr }; const auto AppModule = PyModule_Create(&AppModuleInfo); PyModule_AddFunctions(AppModule, AppModuleMethods); return AppModule; } // Adding a function when a plugin is loaded void PluginAddingAFunction() { static PyMethodDef AppModuleMethods[]{ {"log", log, METH_VARARGS, "Log a message in the standard output."}, {NULL, NULL, 0, NULL} // Sentinel }; PyObject *modName = PyUnicode_FromString("AppModule"); PyObject *mod = PyImport_Import(modName); PyModule_AddFunctions(mod, AppModuleMethods); } // Removing the function when the plugin is unloaded void PluginRemoveAFunction() { PyObject *modName = PyUnicode_FromString("AppModule"); PyObject *mod = PyImport_Import(modName); // How to do this? //PyModule_RemoveFunctions(mod, "log"); } int main(int argn, const char* argv[]) { Py_SetProgramName(argv[0]); PyImport_AppendInittab("AppModule", &initAppModule); Py_Initialize(); PyObject *pmodule = PyImport_ImportModule("AppModule"); PluginAddingAFunction(); // <<===== This is done at any time, when loading a plugin PyRun_SimpleString("import AppModule\n" "AppModule.log('Hi World')\n"); // <== Example code PluginRemoveAFunction(); // <<===== This is done when unloading a plugin Py_FinalizeEx(); }
You can use PyObject_DelAttr C-apis. int PyObject_DelAttr(PyObject *o, PyObject *attr_name) Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement del o.attr_name Reference. So you could do something like this to remove log function void PluginRemoveAFunction() { PyObject *modName = PyUnicode_FromString("AppModule"); PyObject *mod = PyImport_Import(modName); PyObject *funcName = PyUnicode_FromString("log"); PyObject_DelAttr(mod, funcName); }
74,297,266
74,297,898
How do I change the font weight of a specific control on a dialog based window?
I have a dialog-based window that has a "static text" control. I want to change the font weight of that "static text" control. I have read several subjects talking about that subject but I still don't understand how do I achieve that. This is what I have come up with so far: INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { LOGFONT LogFont = {0}; LogFont.lfWeight = FW_BOLD; HFONT hFont = CreateFontIndirectW(&LogFont); SendMessageW(hDlg, WM_SETFONT, (WPARAM) hFont, TRUE); return TRUE; } return FALSE; } How can I do that?
Unlike static control colors, which come from the parent dialog, each control is responsible for remembering its own font. Use WM_GETFONT to get the font the control is currently using: HWND hwndCtl = GetDlgItem(hDlg, IDC_STATIC); // replace with your control ID HFONT hCurFont = reinterpret_cast<HFONT>(SendMessage(hwndCtl, WM_GETFONT, 0, 0)); You can then use GetObject to query the font and fill out a LOGFONT structure: LOGFONT lf; GetObject(hCurFont, sizeof(lf), &lf); You can then make changes to the LOGFONT and create a new font out of it: lf.fwWeight = FW_BOLD; HFONT hNewFont = CreateFontIndirect(&lf); Finally, tell the control about the new font: SendMessage(hwndCtl, WM_SETFONT, reinterpret_cast<WPARAM>(hNewFont), TRUE); If you have multiple controls they can share the same font handle. The important thing to remember is that you now own that font, and it's your responsibility to free it using DeleteObject() when your dialog is destroyed (or else you'll leak the GDI resource associated with it).
74,298,299
74,298,323
compiler reports const instead of const&
Tried to compile following code, can't understand error message. #include<iostream> #include<string> using namespace std; struct S { string a{"abc"}; const string& data() { return a; } }; int main() { S s; int a = s.data(); // error: no viable conversion from 'const std::string' to 'int' return 0; } Question: why does compiler say 'const std::string' instead of 'const std::string&'? Tried with Apple clang 14.0.0 and g++ 12, same error message.
data() returns a reference to a const std::string object, yes. But, you are not converting the reference itself to an int, you are converting the std::string object that it refers to. A reference is just an alias, once a reference has been bound to an object, any access of the reference is really accessing the object instead. That is why the error message does not include &.
74,298,412
74,302,716
Using boost graph library to obtain induced subgraph reachable from vertex v with distance d
I'm having problems in filtering the subgraphs using boost libraries, I want to obtain induced subgraph reachable from v with distance d. Here is the python code using networkx library: def reachable_subgraph(G, v, d): E = nx.bfs_edges(G, v, depth_limit=d) N = set([n for e in E for n in e]) return nx.induced_subgraph(G, N) How can I do it using Boost library? Should I use bfs_visitors? I am not very familiar with the visitor concepts so it would be helpful to know it can be done using the visitor or any other Boost approaches. Thanks! Should I use bfs_visitors?
You might use the filtered_graph adaptor. I like to push c++20 features to get as close to Pythonesque as I can: #include <boost/graph/filtered_graph.hpp> template <typename Graph, typename Nodes, typename V = typename Graph::vertex_descriptor> auto induced_subgraph(Graph& g, Nodes nodes) { std::function f{[n = std::move(nodes)](V v) { return n.contains(v); }}; return boost::filtered_graph(g, boost::keep_all{}, f); } Now, let's write your reachable_subgraph function: #include <boost/graph/breadth_first_search.hpp> template <typename Graph, typename V = typename Graph::vertex_descriptor> auto reachable_subgraph(Graph& g, V source, unsigned depth) { std::vector<unsigned> dist(num_vertices(g)); auto vis = make_bfs_visitor(record_distances(dist.data(), boost::on_tree_edge{})); breadth_first_search(g, source, visitor(vis)); std::set<V> N; for (auto [b, e] = vertices(g); b != e; ++b) if (auto d = dist[*b]; d && d < depth) N.insert(*b); return induced_subgraph(g, std::move(N)); } DEMONSTRATION See it Live On Coliru int main() { boost::adjacency_list g; std::mt19937 prng(77); // manually selected for example generate_random_graph(g, 100, 150, prng); // print_graph(g); fmt::print("g has vertices [0..{}]\n", num_vertices(g) - 1); auto sub = reachable_subgraph(g, 5, 3); //fmt::print("nodes reachable < 3 from 5: {}\n", boost::make_iterator_range(vertices(sub))); print_graph(sub); } Prints g has vertices [0..99] 8 --> 13 --> 22 14 --> 22 8 22 --> 27 --> 22 31 --> 13 63 72 35 --> 50 --> 90 63 --> 72 --> 90 --> 97 --> 35 27
74,299,443
74,343,338
Convert YUV frames to RGB
I'm trying to convert YUV file(UYUV, YUV 422 Interleaved,BT709) to RGB with C++. I've took the example from here: https://stackoverflow.com/a/72907817/2584197 This is my code: Size iSize(1920,1080); int iYUV_Size = iSize.width * (iSize.height + iSize.height / 2); Mat mSrc_YUV420(cv::Size(iSize.width, iSize.height + iSize.height / 2),CV_8UC1); ifstream FileIn; FileIn.open(filename, ios::binary | ios::in); if (FileIn.is_open()) { FileIn.read((char*)mSrc_YUV420.data, iYUV_Size); FileIn.close(); } else { printf("[Error] Unable to Read the Input File! \n"); } Mat mSrc_RGB(cv::Size(iSize.width, iSize.height), CV_8UC1); cv::cvtColor(mSrc_YUV420, mSrc_RGB, COLOR_YUV2RGB_UYVY); cv::imwrite(output_filename, mSrc_RGB); But I get this error: terminating with uncaught exception of type cv::Exception: OpenCV(4.5.5) /build/master_pack-android/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::(anonymous namespace)::CvtHelper<cv::impl::(anonymous namespace)::Set<2, -1, -1>, cv::impl::(anonymous namespace)::Set<3, 4, -1>, cv::impl::(anonymous namespace)::Set<0, -1, -1>, cv::impl::(anonymous namespace)::NONE>::CvtHelper(cv::InputArray, cv::OutputArray, int) [VScn = cv::impl::(anonymous namespace)::Set<2, -1, -1>, VDcn = cv::impl::(anonymous namespace)::Set<3, 4, -1>, VDepth = cv::impl::(anonymous namespace)::Set<0, -1, -1>, sizePolicy = cv::impl::(anonymous namespace)::NONE]' Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1 When I change the CV_8UC1 to CV_8UC2, I don't get error, but this is the result: I was able to do the conversion using the following python code: with open(input_name, "rb") as src_file: raw_data = np.fromfile(src_file, dtype=np.uint8, count=img_width*img_height*2) im = raw_data.reshape(img_height, img_width, 2) rgb = cv2.cvtColor(im, cv2.COLOR_YUV2RGB_UYVY) And this is the result:
The problem was that UYVY is 2 bytes, so I have to double the size of the image. Now with thelines int iYUV_Size = iSize.width * iSize.height * 2; Mat mSrc_YUV420(cv::Size(iSize.width, iSize.height),CV_8UC2); it works well. Thanks, @micka for the help!
74,299,737
74,304,129
How to compile and migrate to DPC++
I have cloned a github repository which has some C++ and OpenCL project to my devcloud account. Is there a way to migrate these opencl files to DPC++? I want to work with jupyter notebook will it be possible?
Yes, you can migrate OpenCL applications to DPC++ because DPC++ includes SYCL, which is a higher-level abstraction layer that builds on OpenCL, when comparing DPC++ and OpenCL, most fundamental concepts are the same with an easy mapping of equivalent constructs between OpenCL and DPC++. Here is the article which gives more details regarding the same https://www.intel.com/content/www/us/en/developer/articles/technical/migrating-opencl-designs-to-dpcpp.html You can use the Intel compilers to run applications, and the Jupyter notebook can also be used to migrate from OpenCL to DPC++.