question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
70,265,274
70,265,838
C ++ using multiple cores breakes output , code for a math problem
So, for start im just starting to learn c++, and i had to resolve this problem: Find the numbers with the propriety : 5 * 5 = 25 , 25 * 25 =625(25squared), 6*6 =36(6squared) ( 25 is the ending of 625, 5 is the the ending of 25 ). So i've got my code to find all the numbers lower than 30k , but then i wanted to push it to it's limit ,so up to lluint_max, but it was really slow, i saw that my 12 core cpu is not utilised so i thought i'd add more cpu cores. I wanted to find the easiest fix and i found openmp, read a little and foun that if i add omp for it should divide the load to multiple cores, but the console doesn't display my numbers anymore.(PS i enabled omp in vs) Here's my code: #include <iostream> #include <cmath> #include <climits> #include <omp.h> using namespace std; int main() { long long int x, i, nc = 0, z = 1, p; #pragma omp for for (x = 1; x <= ULLONG_MAX; x++) { //numarul de cifre a lui x while (x / z != 0) { z = z * 10; nc = nc + 1; } //patratul p = x * x; i = pow(10, nc); if (p % i == x) cout << x << endl; } } And heres my output: C:\Users\Mihai Cazac\source\repos\ConsoleAPP2\Debug\ConsoleAPP2.exe (process 8736) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . . Expected output: 1 5 6 25 76 376 625 9376 90625 109376 890625 2890625 7109376 12890625 //and so on Thanks in advance!!
So i've resolved it , special thanks to Raymond Chen for his comment and the blog he directed me to, http://supercomputingblog.com/openmp/tutorial-parallel-for-loops-with-openmp/ This site explained it really well. I declared the variables as late as possible, also changhed to LLInt_Max as openmp doesnt want to work with unsigned only ,idk why Also schedule dynamic seems to divide the workload,but i may be wrong. My final code: #include <iostream> #include <cmath> #include <climits> #include <omp.h> using namespace std; int main() { #pragma omp parallel for schedule(dynamic) for (long long int x = 1; x < LLONG_MAX; x++) { long long int t = x; int d = 0; while (t > 0) { t = t / 10; d++; } //patratul long long int p = x * x; long long int i = pow(10, d ); if (p % i == x) cout << x << endl; } }
70,265,335
70,265,417
Assert function in C++ using cassert function - How can I declare the variables in the test function?
#include <iostream> #include <string> #include <cassert> using namespace std; void test(); void test() { //my attempted test function in order to ensure the program works correctly string answ1 = "noooooob"; string answ2 = "saaaaaadie"; string answ3 = "trish"; assert(answer(answ1) == "nob"); //this is where i get the compile error that "answer" not declared assert(answer(answ2) == "sadie"); assert(answer(answ3) == "trish"); cout << "All test cases passed!" << endl; } int main() { int i = 0; string output; string input; char x; getline(cin, input); //input output += input[0]; x = input[0]; while (i < input.length()) { i++; if (input [i] != x) { output += input[i]; } x = input[i]; } cout << output << endl; test(); return 0; } All I'm really asking is how to declare the "answer" variable in the assert function. Maybe I'm doing it completely wrong, and my apologies if so. I'm pretty new to the coding scene. Do I need to make a string that would loop through the current for loop in my main function? Any help is much appreciated.
Either you forgot to include a header where you define a class or a function with name answer or you don't need it and just comapre strings: assert(answ1 == "nob"); // operator== kicks in assert(answ2 == "sadie"); assert(answ3 == "trish"); You should be aware that assert is a debug-only feature. It compiles to nothing in release mode. You should probably reevaluate your approach for unit testing as the comments suggest (GTest would be fine).
70,265,716
70,266,355
Can't understand the task of given function
New to Cpp. In the given code, I don't know what change_val(int k) = 0; means and why the compiler prints error: cannot declare variable 'ob1' to be of abstract type 'B' B ob1(10); error: invalid new-expression of abstract class type 'B' ob2 = new B(100); To my knowledge, neither B nor A has been declared abstract. Then why can't I declare a variable of B object? And is it possible to assign object of one class to another object type as in A *ob2; ob2 = new B(100);? The code: #include<iostream> using namespace std; class A{ int x; public: A(){x=0;} explicit A(int x){ cout<<"Constructor of A called"<<endl; this->x = x+100;} virtual void change_val(int k) = 0; void set_x(int k){x = k;} int get_val() const{ return x; } virtual void print_value() { cout<<x<<endl; } }; class B : public A{ public: explicit B(int k):A(k){ cout<<"Constructor of B called"<<endl; } void print_value() override { cout<< get_val()+200<<endl; } }; int main(){ B ob1(10); ob1.print_value (); A *ob2; ob2 = new B(100); ob2->print_value (); ob2->change_val(20); ob2->print_value (); }
We'll start with a quick review of your code: #include<iostream> using namespace std; // Bad practice class A{ int x; public: A(){x=0;} // Bad practice; utilize default member initialization explicit A(int x){ cout<<"Constructor of A called"<<endl; // Bad practice; utilize initialization section this->x = x+100;} // Poor style throughout this code // Missing virtual destructor virtual void change_val(int k) = 0; // Pure virtual function, makes A an abstract class void set_x(int k){x = k;} int get_val() const{ return x; } virtual void print_value() { cout<<x<<endl; // Prefer '\n' over std::endl } }; class B : public A{ public: explicit B(int k):A(k){ // Why use initialization here but not above? cout<<"Constructor of B called"<<endl; } void print_value() override { cout<< get_val()+200<<endl; } // Failed to override pure virtual function change_val(), making B abstract as well }; int main(){ B ob1(10); ob1.print_value (); A *ob2; ob2 = new B(100); // Initialize on same line as declaration ob2->print_value (); ob2->change_val(20); ob2->print_value (); // Missing delete } This is subjective, so I didn't note it above, but it's also possible for the member x to be protected in A so that B can directly access it instead of going through a getter. My code below does this. I see no reason to make implementing children classes more difficult. #include <iostream> // using namespace std; // Bad practice class A { protected: int x = 0; public: A() = default; virtual ~A() = default; explicit A(int x) : x(x + 100) { std::cout << "A ctor" << '\n'; } // Pure virtual function, makes A abstract virtual void change_val(int k) = 0; void set_x(int k) { x = k; } int get_val() const { return x; } virtual void print_value() { std::cout << x << '\n'; } }; class B : public A { public: explicit B(int k) : A(k) { std::cout << "B ctor" << '\n'; } // Simpler function due to x being protected now in A void print_value() override { std::cout << x + 200 << '\n'; } // Overriding the pure virtual function makes B a concrete class now void change_val(int k) override { x = k; } }; int main() { B ob1(10); ob1.print_value(); A *ob2 = new B(100); ob2->print_value(); ob2->change_val(20); ob2->print_value(); delete ob2; } Output: ❯ ./a.out A ctor B ctor 310 A ctor B ctor 400 220 I noted that a virtual destructor was missing. It's important to have this for all base classes so that your derived objects can be properly destroyed. You also called new without a subsequent delete. In bigger programs doing actual work, this would have leaked memory. To avoid this issue, you could use std::unique_ptr from <memory>. It handles the creation and destruction for you. #include <memory> /* * Your code */ int main() { B ob1(10); ob1.print_value(); std::unique_ptr<A> ob2(new B(100)); ob2->print_value(); ob2->change_val(20); ob2->print_value(); }
70,265,748
70,265,844
why is there a race condition in this multithreading snippet
I have this code in c++ using multithreading but I am unsure why I am getting the output I am getting. void Fun(int* var) { int myID; myID = *var; std::cout << "Thread ID: " << myID << std::endl; } int main() { using ThreadVector = std::vector<std::thread>; ThreadVector tv; std::cout << std::thread::hardware_concurrency() << std::endl; for (int i = 0; i < 3 ; ++i) { auto th = std::thread(&Fun, &i); tv.push_back(std::move(th)); } for (auto& elem : tv) { elem.join(); } } I am wondering if there is a race condition for the i variable, and if so, how does it interleave? I tried to compile it and I constantly got the Thread ID printout as 3, but I was surprised because I thought the variable had to be global in order to be accessed by the various new threads? This is what I thought would happen: thread 1 is created, Fun starts to run in thread 1 with myid = 0, main thread continues running and increments i, 2nd thread is created and the myid for that would be myid=1... and so on. And so the printout would be the myID in increments i/e 1,2,3 I know that I can solve this with std::lock_guard but I am just wondering how is the interleaving (LOAD, INCREMENT,STORE) happening that causes this race condition for the i variable. Kind help is appreciated thank you!
I am wondering if there is a race condition for the i variable Yes, most definitely. The parent thread writes to i, which is a non-atomic variable, and the child threads read it, without any intervening synchronization. That's the exact definition of a data race in C++. and if so, how does it interleave? Data races in C++ cause undefined behavior, and any behavior you may observe does not have to be explainable by interleaving. I tried to compile it and I constantly got the Thread ID printout as 3, but I was surprised because I thought the variable had to be global in order to be accessed by the various new threads? No, it doesn't have to be global. Threads can access variables which are local to other threads if they are somehow passed a pointer or reference to such a variable. This is what I thought would happen: thread 1 is created, Fun starts to run in thread 1 with myid = 0, main thread continues running and increments i, 2nd thread is created and the myid for that would be myid=1... and so on. And so the printout would be the myID in increments i/e 1,2,3 Well, nothing at all in your program forces those events to occur (or become observable) in that order, so there is really no basis for expecting that they will. It's entirely possible, for instance, that the three threads all get started, but don't get a chance to actually run until after the loop in main has completed, at which point i has the value 3. (Or rather, the memory where i used to be located, as it is now out of scope and its lifetime has ended - it's a separate bug that you don't prevent that from happening.)
70,266,813
70,267,093
how to implicitly convert a foo<const bar> into a const foo<bar> in C++ template?
I'm making my own vector container and I'm trying to implement an iterator that works like the real one, using the C++98 standard. This is homework so I don't want the answer just a hint as to where I should look and what I should learn to be able to tackle this problem. So basically I'm trying to make this code work: ft::vector<int> v (100, 100); ft::vector<int>::iterator it = v.begin(); ft::vector<int>::const_iterator cit = it; std::cout << (cit == it) << std::endl; //comparison 1 /// works std::cout << (it == cit) << std::endl; //comparison 2 /// doesn't compile std::cout << (cit + 1 == it + 1) << std::endl; //doesn't work std::cout << (it + 1 == cit + 1) << std::endl; //doesn't work iterator and const_iterator are typedefs like this: typedef typename ft::iterator_vector<value_type> iterator; typedef typename ft::iterator_vector<const value_type> const_iterator; And value type being the type passed to the vector template. The first comparison didn't work until I added a user-defined conversion operator in my iterator template to convert iterator<const foo> into iterator<foo> (the other way around actually as pointed out by @TedLyngmo) which is operator iterator_vector<const value_type>() const { return _p; } but the compiler says that I need now to be able to convert a iterator<const foo> into a const iterator<foo> and I have no idea how to proceed. This is the implementation of my iterator: template <class T> class iterator_vector : public ft::iterator<std::random_access_iterator_tag, T> { public: typedef ft::iterator<std::random_access_iterator_tag, T> iterator; typedef ft::iterator_traits<iterator> iterator_traits; typedef typename iterator_traits::difference_type difference_type; typedef typename iterator_traits::value_type value_type; typedef typename iterator_traits::pointer pointer; typedef typename iterator_traits::reference reference; typedef typename iterator_traits::iterator_category iterator_category; /* ** Member functions */ iterator_vector(pointer p = 0) : _p(p) {} ~iterator_vector(void) {} operator iterator_vector<const value_type>() const { return _p; } iterator_vector& operator++() { ++_p; return *this; } iterator_vector operator++(int) { iterator_vector r = *this; ++_p; return r; } iterator_vector& operator--() { --_p; return *this; } iterator_vector operator--(int) { iterator_vector r = *this; --_p; return r; } iterator_vector operator+(size_t n) const { return iterator_vector(_p + n); } iterator_vector operator-(size_t n) const { return iterator_vector(_p - n); } iterator_vector& operator+=(size_t n) { _p += n; return *this; } iterator_vector& operator-=(size_t n) { _p -= n; return *this; } difference_type operator+(iterator_vector rhs) const { return _p + rhs._p; } difference_type operator-(iterator_vector rhs) const { return _p - rhs._p; } reference operator*(void) const { return *_p; } pointer operator->() const { return _p; } reference operator[](size_t n) const { return _p[n]; } bool operator==(const iterator_vector& rhs) const { return _p == rhs._p; } bool operator!=(const iterator_vector& rhs) const { return _p != rhs._p; } bool operator<(const iterator_vector& rhs) const { return _p > rhs._p; } bool operator>(const iterator_vector& rhs) const { return _p < rhs._p; } bool operator<=(const iterator_vector& rhs) const { return _p <= rhs._p; } bool operator>=(const iterator_vector& rhs) const { return _p >= rhs._p; } /* ** Non-member functions */ friend iterator_vector operator+(size_t n, const iterator_vector& rhs) { return iterator_vector(rhs._p + n); } friend iterator_vector operator-(size_t n, const iterator_vector& rhs) { return iterator_vector(rhs._p - n); } private: pointer _p; };
It seems from your comments in your code about what is failing that you are missing a comparison function for when iterator is to the left and the const_iterator is to the right. You could add this free function: template<typename T> bool operator==(const iterator_vector<T>& lhs, const iterator_vector<const T>& rhs) { // just swap the order here and the implicit conversion from `iterator` // to `const_iterator` from `lhs` solves the rest: return rhs == lhs; } I added a user-defined conversion operator in my iterator template to convert iterator<const foo> into iterator<foo> No, you added an implicit conversion the other way around. That is, from iterator to const_iterator - which is good! An alternative could be to make the two iterators friends to not have to implement similar swapping lhs with rhs functions for all your operators. The operators in your template would then become: // define these before your class template (borrowed from C++11): template< class T > struct remove_const { typedef T type; }; template< class T > struct remove_const<const T> { typedef T type; }; //... in your class template: friend class iterator_vector<typename remove_const<T>::type>; friend class iterator_vector<const T>; template<typename U> bool operator==(const iterator_vector<U>& rhs) const { return _p == rhs._p; } template<typename U> bool operator!=(const iterator_vector<U>& rhs) const { return _p != rhs._p; } template<typename U> bool operator<(const iterator_vector<U>& rhs) const { return _p > rhs._p; } template<typename U> bool operator>(const iterator_vector<U>& rhs) const { return _p < rhs._p; } template<typename U> bool operator<=(const iterator_vector<U>& rhs) const { return _p <= rhs._p; } template<typename U> bool operator>=(const iterator_vector<U>& rhs) const { return _p >= rhs._p; }
70,267,209
70,267,258
C++ Compile time specification of array size
I'm attempting to create a struct to hold a file header within the declaration section of a class in a header file. This involves calculation of a value that is known at compile time, and I want to use it to size an array within the header. This is an extract from a header file of what I've most recently been trying: const uint hFreeSiz = (1024 - sizeof(uint32_t) - sizeof (uint16_t)- sizeof (uint16_t) - sizeof(RId))/sizeof (RId); template <const uint freedSiz> struct FBHead { /** A magic number for the file. Indicates both class and version. */ uint32_t fSig; /** The number of data bytes within each block. */ uint16_t blkSize; /** The number of records available for reuse. */ uint16_t freedCnt; /** The id number of the last record written to the file. */ RId lstRec; RId freedRecs[freedSiz]; }; FBHead<hFreeSiz> fbHead; but it tells me: error: invalid use of non-static data member 'FBFile::hFreeSiz' I could calculate this by hand, but I'm trying to understand what's going on here and why this isn't working. Can anyone explain? (I'm guessing that if I moved the constant declaration outside the class, then it would work, but I'd really rather keep it close to the stuff that it's used to modify. In fact, if that's the only answer, then I'll probably calculate it by hand and put in comments about why that particular number.)
The modern way would be to use a constexpr, to tell the compiler it is an actual compile-time constant. See a simpler example: constexpr int Size = sizeof(long) * 7; class Foo { int t[Size]; }; or class Foo { static constexpr int Size = sizeof(long) * 7; int t[Size]; };
70,267,323
70,267,694
Insert integer into the middle of string c++
I am trying to replace the W with the number 5 (in this example). However, when I try, I only get the the ascii value of 5 to replace the W, instead of the number 5 itself. How would I fix this? NOTE: I this is a shortened example from a longer project. I need to access the number in nums[1]. #include <iostream> #include <string> using namespace std; int main() { int nums[3] {4,5,6}; string str = "HELLO WORLD"; cout << str << endl; str[6] = nums[1]; cout << str << endl; return 0; } Output: HELLO WORLD HELLO ♣ORLD
You can convert a digit to an ASCII character: char c = '0' + 5 (gives you '5'). This is your code fixed: #include <iostream> #include <string> using namespace std; int main() { int nums[3] {4,5,6}; string str = "HELLO WORLD"; cout << str << endl; str[6] = '0' + nums[1]; cout << str << endl; return 0; } However, if you intend to insert an integer as you title says, you have to do this: #include <iostream> #include <string> using namespace std; int main() { int nums[3] {4,15,6}; string str = "HELLO WORLD"; cout << str << endl; // str = str.substr(0, 6) + std::to_string(nums[1]) + str.substr(7); str.replace(6, 1, std::to_string(nums[1])); // as Remy Lebeau has mentioned in the comments cout << str << endl; return 0; } (UPD: it is equivalent to std::string::replace) Here is a more sophisticated version which tries to use existing capacity: #include <iostream> #include <string> #include <algorithm> // don't ever do it with std // using namespace std; size_t count_digits(int num) { int digits = 0; do { num /= 10; digits++; } while (num); return digits; } void insert_number(std::string& str, size_t indx, int num) { const size_t digits = count_digits(num), oldSize = str.size(); // insert will reallocate only if capacity is not enough str.insert(str.size(), digits - 1, '0'); // move the end of string right by rotating (rewriting characters) auto iterBegin = std::next(str.begin(), indx), iterNext = std::next(str.begin(), oldSize); std::rotate(iterBegin, iterNext, str.end()); // write our string from integer to the designated space const auto &strInteger = std::to_string(num); for (size_t iStr = indx, iInt = 0; iInt != strInteger.size(); ++iInt, ++iStr) str[iStr] = strInteger[iInt]; } int main() { int nums[3] {4, 48152342, 6}; std::string str = "HELLO WORLD LOOOOONG STRIIING"; str.reserve(str.capacity() + 20); // strings don't preallocate more space after construction std::cout << str << std::endl; std::cout << "capacity before: " << str.capacity() << std::endl; insert_number(str, 6, nums[1]); std::cout << str << std::endl; std::cout << "capacity after: " << str.capacity() << std::endl; return 0; } https://godbolt.org/z/7aPMvcosj
70,267,387
70,278,120
Why is is_trivially_copyable_v different in GCC and MSVC?
When running this simple program, different behaviour is observed depending on the compiler. It prints true when compiled by GCC 11.2, and false when compiled by MSVC 19.29.30137 with the (both are the latest release as of today). #include <type_traits> #include <iostream> struct S { int a; S() = delete; S(S const &) = delete; S(S &&) = delete; S &operator=(S const &) = delete; S &operator=(S &&) = delete; ~S() = delete; }; int main() { std::cout << std::boolalpha; std::cout << std::is_trivially_copyable_v<S>; } Relevant quotes (from the latest C++23 working draft N4901): Given 20.15.5.4 [meta.unary.prop], std::is_trivially_copyable_v<T> is defined to be true if T is a trivially copyable type as defined at 6.8.1/9 [basic.types.general]: Arithmetic types (6.8.2), enumeration types, pointer types, pointer-to-member types (6.8.3), std::nullptr_t, and cv-qualified (6.8.4) versions of these types are collectively called scalar types. Scalar types, trivially copyable class types (11.2), arrays of such types, and cv-qualified versions of these types are collectively called trivially copyable types. where trivially copyable class types is defined at 11.2/1 [class.prop]: 1 A trivially copyable class is a class: — that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator (11.4.4, 11.4.5.3, 11.4.6), — where each eligible copy constructor, move constructor, copy assignment operator, and move assignment operator is trivial, and — that has a trivial, non-deleted destructor (11.4.7). Eligible (11.4.4 [special]): 1 Default constructors (11.4.5.2), copy constructors, move constructors (11.4.5.3), copy assignment operators, move assignment operators (11.4.6), and prospective destructors (11.4.7) are special member functions. 6 An eligible special member function is a special member function for which: — the function is not deleted, — the associated constraints (13.5), if any, are satisfied, and — no special member function of the same kind is more constrained trivial for these functions (as defined at 11.4.5.3/11 [class.copy.ctor], 11.4.6/9 [class.copy.assign], 11.4.7/8 [class.dtor]) generally means: the function is not user-provided. there's nothing virtual to the class each non-static data member has the relevant trivial function As per 9.5.2/5 [dcl.fct.def.default], the deleted functions in the provided program aren't user-provided: ... A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. ... If my understanding is correct, struct S has deleted special member functions making them non-eligible, which doesn't meet the requirements for a trivially copyable class type and trivially copyable type. Therefore the conforming behaviour is MSVC's. Is this correct?
GCC and Clang report that S is trivially copyable in C++11 through C++23 standard modes. MSVC reports that S is not trivially copyable in C++14 through C++20 standard modes. N3337 (~ C++11) and N4140 (~ C++14) say: A trivially copyable class is a class that: has no non-trivial copy constructors, has no non-trivial move constructors, has no non-trivial copy assignment operators, has no non-trivial move assignment operators, and has a trivial destructor. By this definition, S is trivially copyable. N4659 (~ C++17) says: A trivially copyable class is a class: where each copy constructor, move constructor, copy assignment operator, and move assignment operator is either deleted or trivial, that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and that has a trivial, non-deleted destructor By this definition, S is not trivially copyable. N4860 (~ C++20) says: A trivially copyable class is a class: that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator, where each eligible copy constructor, move constructor, copy assignment operator, and move assignment operator is trivial, and that has a trivial, non-deleted destructor. By this definition, S is not trivially copyable. Thus, as published, S was trivally copyable in C++11 and C++14, but not in C++17 and C++20. The change was adopted from DR 1734 in February 2016. Implementors generally treat DRs as though they apply to all prior language standards by convention. Thus, by the published standard for C++11 and C++14, S was trivially copyable, and by convention, newer compiler versions might choose to treat S as not trivially copyable in C++11 and C++14 modes. Thus, all compilers could be said to be correct for C++11 and C++14. For C++17 and beyond, S is unambiguously not trivially copyable so GCC and Clang are incorrect. This is GCC bug #96288 and LLVM bug #39050
70,267,454
70,267,560
Why copy/move assignment operator should be declared non-virtual?
According to CppCoreGuidelines C.60 and C.63, copy assignment operator (e.g Foo& operator=(const Foo& x)) and move assignement operator (e.g Foo& operator=(const Foo&& x)) should be declared non-virtual. Can you explain me the reason of this recommandation ? As suggested by this answer, I imagine that this is to avoid leaks of memory but I don't see exactly how the use of virtual will induce it.
There is no reason why a copy or move assignment operator should be virtual. Making it virtual possibly incurs costs associated with having virtual functions (e.g. the requirement to allocate a vptr within each object of the class) for no benefit. Let's say you have a class Base, which has a virtual copy assignment operator: virtual Base& operator=(const Base&); What will happen when you write a derived class, class Derived : public Base? It will have its own copy assignment operator: Derived& operator=(const Derived&); // possibly also virtual If you don't declare such an operator, the compiler will implicitly declare one with this signature (modulo some details that are not relevant here). Because the derived class's copy assignment operator has a different argument type from that of the base class, there is no overriding relationship between them. And there's no point in writing a virtual function if it's never going to be overridden.
70,267,659
70,286,053
Problem with display function inside circular queue
#include <stdio.h> # define MAX 3 int queue[MAX]; // array declaration int front=-1; int rear=-1; // function to insert an element in a circular queue void enqueue(int element) { if(front==-1 && rear==-1) // condition to check queue is empty { front=0; rear=0; queue[rear]=element; } else if((rear+1)%MAX==front) // condition to check queue is full { printf("Queue is overflow.."); } else { rear=(rear+1)%MAX; // rear is incremented queue[rear]=element; // assigning a value to the queue at the rear position. } } // function to delete the element from the queue int dequeue() { if((front==-1) && (rear==-1)) // condition to check queue is empty { printf("\nQueue is underflow.."); } else if(front==rear) { printf("\nThe dequeued element is %d", queue[front]); front=-1; rear=-1; } else { printf("\nThe dequeued element is %d", queue[front]); front=(front+1)%MAX; } } // function to display the elements of a queue void display() { int i=front; if(front==-1 && rear==-1) { printf("\n Queue is empty.."); } else { printf("\nElements in a Queue are :"); while(i<=rear) { printf("%d,", queue[i]); i=(i+1)%MAX; } } } int main() { int choice=1,x; // variables declaration while(choice<4 && choice!=0) // while loop { printf("\nPress 1: Insert an element"); printf("\nPress 2: Delete an element"); printf("\nPress 3: Display the element"); printf("\nEnter your choice"); scanf("%d", &choice); switch(choice) { case 1: printf("Enter the element which is to be inserted"); scanf("%d", &x); enqueue(x); break; case 2: dequeue(); break; case 3: display(); }} return 0; } I have problem with display function how can i print all element if rear can be in somecases less than front for example in this code i try to enqueue 3 elements 1,2,3 then dequeue two elements which i mean here 1,2 after that i try to enque two elements 1,2 again finaly when i try to display elements i get nothing so what is the perfect way to display queue elements
So... here's a working solution. #include <stdio.h> # define MAX 3 class CircularQueue { private: int queue[MAX]; // array declaration int front; int rear; public: CircularQueue() : front(-1), rear(-1) { } // function to insert an element in a circular queue void enqueue(int element) { if(front==-1 && rear==-1) // condition to check queue is empty { front=0; rear=0; queue[rear]=element; } else if((rear+1)%MAX==front) // condition to check queue is full { printf("Queue is overflow..\n"); } else { rear=(rear+1)%MAX; // rear is incremented queue[rear]=element; // assigning a value to the queue at the rear position. } } // function to delete the element from the queue void dequeue() { if((front==-1) && (rear==-1)) // condition to check queue is empty { printf("Queue is underflow..\n"); } else if(front==rear) { printf("The dequeued element is %d\n", queue[front]); front=-1; rear=-1; } else { printf("The dequeued element is %d\n", queue[front]); front=(front+1)%MAX; } } // function to display the elements of a queue void display() { if(front==-1 && rear==-1) printf("Queue is empty..\n"); else { printf("Elements in a Queue are: "); int i=front; do { if (i != front) printf(","); printf("%d", queue[i]); i=(i+1)%MAX; } while (i != (rear+1)%MAX); printf("\n"); } } }; int main() { CircularQueue cq; unsigned int choice=1; // variables declaration while(choice<4 && choice!=0) // while loop { printf("Press 1: Insert an element\n"); printf("Press 2: Delete an element\n"); printf("Press 3: Display the element\n"); printf("Press any other number to exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: printf("Enter the element which is to be inserted: "); int x; scanf("%d", &x); cq.enqueue(x); break; case 2: cq.dequeue(); break; case 3: cq.display(); } } return 0; } I made a couple of changes to the output, see the positions of the \n. Its always good to give the next print statement a new line to write to if the current output is complete. The biggest change, I put everything in a class. That way you don't have any global variables, which is to 99.999% a bad thing. Your code is very C like, so normally I would use std::cout as well and with std::vector you could easily make you buffer have arbitrary size. Here's some output: Press 1: Insert an element Press 2: Delete an element Press 3: Display the element Press any other number to exit Enter your choice: 1 Enter the element which is to be inserted: 2 Press 1: Insert an element Press 2: Delete an element Press 3: Display the element Press any other number to exit Enter your choice: 3 Elements in a Queue are: 2 Press 1: Insert an element Press 2: Delete an element Press 3: Display the element Press any other number to exit Enter your choice: 4
70,267,685
70,269,309
Generic constructor template called instead of copy/move constructor
I've designed a simpler wrapper class that adds a label to an object, with the intent of being implicitly convertible/able to replace the wrapped object. #include <string> #include <type_traits> #include <utility> template < typename T, typename Key = std::string > class myTag{ T val; public: Key key; template < typename... Args, typename = typename std::enable_if< std::is_constructible< T, Args... >::value >::type > myTag(Args&&... args) : val(std::forward< Args >(args)...) { std::cout << "forward ctor" << std::endl; } myTag(const myTag& other) : key(other.key), val(other.val) { std::cout << "copy ctor" << std::endl; } myTag(myTag&& other): key(other.key), val(other.val) { std::cout << "move ctor" << std::endl; } operator T&() { return val; } operator const T&() const { return val; } }; int main(int argc, char const *argv[]) { myTag< float > foo(5.6); // forward ctor myTag< float > bar(foo); // forward ctor return 0; } However, I am having trouble properly declaring & defining the copy/move constructor. I declared a generic constructor overload template that forwards its arguments to the underlying type, as long as such construction is possible. However, due to the implicit conversion operators, it is capturing every instantiation of myTag, effectively shadowing the copy/move constructors. The point of non-default copy/move semantics was to copy/move the key value vs default-initializing it with constructor template. How do I make the compiler prefer/give precedence to the explicit copy/move constructors vs the generic overload? Is there any additional SFINAE check alternative to is_constructible<> that avoids implicit conversions? EDIT: I should add that I'm looking for a C++14 solution.
It isn't shadowing the copy and move constructors. It is just beating them in overload resolution in some cases. If you pass a myTag<float>&, the forwarding constructor is used. If you pass a const myTag<float>& the copy constructor is used. If you pass a myTag<float>&&, the move constructor is used. If you pass a const myTag<float>&&, the forwarding constructor is used. The copy and move constructors are not templates, so they will win against a template of the same signature. But the forwarding constructor can be a better match in the cases where the deduced signature differs from the copy and move constructors. The idiomatic way to handle this is to remove the forwarding constructor from consideration based on the decayed type of the arguments: template <typename... Args> constexpr myTag(Args&&... args) requires ((sizeof...(Args) != 1 && std::is_constructible_v<T, Args...>) || (sizeof...(Args) == 1 && std::is_convertible_v<Args..., T> && !std::is_same_v<myTag, std::decay_t<Args>...>))
70,267,801
70,267,981
C++ concatenate from two arrays to one dynamic erray that are initialized from 2 input text files using filestream
I'm trying to concatenate two arrays that were initialized from file input into one dynamic array and returning it to an output file but while testing I found out that the returned dynamic array is initialized with random numbers. I'm sorry for my lack of experience as I am a beginner.. These are my input text files Input1.txt 1 2 3 Input2.txt 4 5 6 and this is my code .. #include <iostream> #include <fstream> using namespace std; int * concatenate(int *a1,int *a2,int size); int main() { int size = 3; int arr1[size]; int arr2[size]; ifstream fin; ofstream fout; fin.open("input1.txt"); for(int i = 0; i < size; i++) { int value; fin>>arr1[i]; cout<<arr1[i]<<endl; } fin.close(); fin.open("input2.txt"); for(int j = 0; j < size; j++) { fin>>arr2[j]; cout<<arr2[j]<<endl; } int *arr3 = concatenate(arr1,arr2,size); cout<<arr3[1]; return 0; } int * concatenate(int *a1,int *a2,int size) { int * r = new int[size*2]; for(int i = 0; i > size*2; i++) { if(i < size) r[i] = a1[i]; else r[i] = a2[i-size]; } return r; }
If you're using c++ you should consider using vectors instead of arrays. They make operations like these way easier. Here's for reference: https://en.cppreference.com/w/cpp/container/vector https://www.geeksforgeeks.org/vector-in-cpp-stl/ You can referer to this post to see how to concatenate two vectors. Concatenating two std::vectors If you want to stick to your method there's an error in your concatenate function. You never actually enter the for-loop since your condition for stopping is wrong. The condition in your loop is continue iterating while i > size * 2 but, with i = 0 at the start, that will never be true thus you will never enter the loop. You can fix this just by inverting the comparaison like so i < size * 2. To avoid this kind of errors you can try to setup a debugger and go through your code line by line seeing the values of variables and what lines are actually executed. This method will help you catch a lot of small mistakes like these. As for the random values in your return array it's because C and C++ don't clean the memory being allocated by your program when creating a new array or calling malloc for example.
70,267,950
70,271,188
How can I fix the argument type conversion compiler errors in this method using a lambda function?
I am programming for the ESP32 (a sort of Arduino like chip). However, to easier/faster find compiler errors/warnings and later make a sort of virtualization on the PC, I like to compile the code also on a PC (using Visual Studio). However, I cannot get the following code to compile on a PC (while it compiles in the Arduino IDE for ESP32): server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { request->send_P(200, "text/html", textBuffer, Processor); }); The errors I get are: Severity Code Description Project File Line Suppression State Error (active) E0413 no suitable conversion function from "lambda []void (AsyncWebServerRequest *request)->void" to "AsyncWebServerRequest *" exists RelayBox C:\Users\miche\source\repos\RelayBox2\RelayBox\RelayBox\RelayBoxServer.cpp 203 Error C2664 'void AsyncWebServer::on(const char *,int,AsyncWebServerRequest *)': cannot convert argument 3 from 'RelayBoxServer::Send::<lambda_6ffcff35888ca3a1f1d7d541e1edeba3>' to 'AsyncWebServerRequest *' RelayBox C:\Users\miche\source\repos\RelayBox2\RelayBox\RelayBox\RelayBoxServer.cpp 206 The code is based on the ESP32 library at https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/src/ESPAsyncWebServer.h And the 'stub' classes I created using library above but simplified for my project, with '...' as irrelevant code: class AsyncWebServer { ... void on(const char* something, int httpGet, AsyncWebServerRequest* function); ... } #define HTTP_GET 100 class AsyncWebServerRequest { public: void send_P(int port, const char* textHmlt, STRING text, ProcessorHandlerFunction function); }; class ArduinoStringStub : public std::string { ... } How can I fix the argument type conversion compiler errors in this method using a lambda function?
I've checked your reference github, it seems that the origin AsyncWebServer class has such signature: AsyncCallbackWebHandler& on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest); And ArRequestHandlerFunction is actually: typedef std::function<void(AsyncWebServerRequest *request)> ArRequestHandlerFunction; So it seems to be that the stub/mock AsyncWebServer you create should not take AsyncWebServerRequest* but ArRequestHandlerFunction as the on method's last parameter, corresponding with the original code.
70,268,197
70,268,237
Overloading a function by return type?
One of the most viewed questions here on SO is the question that deals with overloading of various operators. There is something I don't understand about the overloading of brackets operator operator[]. My question is about the following code: class X { value_type& operator[](index_type idx); const value_type& operator[](index_type idx) const; // ... }; Here the operator is overloaded twice, one function which allows the change of members and one which does not. I read that c++ doesn't allow function overloading by return type, but this looks like it. T& is changed to const T&. Can someone explain to me what exactly is this "overloading" called and why does this work? Thanks in advance. PS: If this works because the second const keyword changes the "invisible" this pointer argument to const this then I understand, but still, is there a name for that practice?
For overloading to work the functions need to have different signatures (the return type does not count). In methods the this pointer to the object also counts as an implicit (first) argument. Static methods of course don't have a this pointer, so they can be treated like global functions. In your example the two methods have different arguments. idx is identical in both cases but the first method has a this pointer of type X*, which is a variable pointer. In the second method the this pointer is a constant type: const X* and is thus distinct from the first one, that's why the overloading works. The return value is inconsequential to the overloading. If only the return values were different, overloading would not have been allowed by the compiler. class X { value_type& operator[](index_type idx); const value_type& operator[](index_type idx) const; // -----------------------^^^^^ // This is what makes the overloading possible. };
70,268,201
70,268,246
Techniques for cutting down on verbosity when do polymorphism via std::variant rather than inheritance
Say you have entities in a 2D game framework or something similar -- e.g. a GUI framework -- where there are various types of entities that share common properties like position and rotation but where some of these properties must be handled on a per-entity type basis e.g. rotating a simple sprite is performed differently than rotating a rigged 2D animation skeleton. Obviously this could be handled by a traditional OOP inheritance hierarchy ... However, I'm interested instead in representing such entities using "composition over inheritance" by having a concrete class that nothing inherits from called actor that has vanilla member variables for state that is handled the same way across entity types but also has a has-a relationship with a variant containing the state that must be handled in a per-entity type way. This design can be made to work as below: #include <iostream> #include <variant> struct actor_state_1 { float rotation_; //point position; // etc... void set_rotation(float theta) { rotation_ = theta; // say there are different things that need to happen here // for different actor types... // e.g. if this is an animation skeleton you need to find the // the root bone and rotate that, etc. std::cout << "actor_state_1 set_rotation\n"; } void set_position(const std::tuple<float, float>& pos) { // etc ... } float get_rotation() const { return rotation_; } // get_position, etc... }; struct actor_state_2 { float rotation_; void set_rotation(float theta) { rotation_ = theta; std::cout << "actor_state_2 set_rotation\n"; } void set_position(const std::tuple<float, float>& pos) { // etc ... } float get_rotation() const { return rotation_; } // get_position, etc... }; using state_variant = std::variant<actor_state_1, actor_state_2>; class actor { private: state_variant state_; // common properties... float alpha_transparency; // etc. public: actor(const actor_state_1& state) : state_(state) {} actor(const actor_state_2& state) : state_(state) {} void rotate_by(float theta) { auto current_rotation = get_rotation(); std::visit( [current_rotation, theta](auto& a) { a.set_rotation(current_rotation + theta); }, state_ ); } float get_rotation() const { return std::visit( [](const auto& a) {return a.get_rotation(); }, state_ ); } void move_by(const std::tuple<float, float>& translation_vec); std::tuple<float, float> get_postion() const; // etc. }; int main() { auto a = actor(actor_state_2{ 90.0f }); a.rotate_by(45.0f); std::cout << a.get_rotation() << "\n"; } However I feel as though the level of verbosity and the amount of repeated boilerplate code per property makes such a design unwieldy. I however can't figure out a way to cut down on the boilerplate by using templates. It seems like there should be a way to at least make a template for "pass-through getters" like actor::get_rotation() in the above but I don't know a way of parametrizing on a member function which is what it seems like you would need to do. Does anyone have ideas for a design like this that is less verbose or uses less boilerplate?
Just use a visitor: #include <variant> struct state_a{}; struct state_b{}; struct actor { std::variant<state_a, state_b> state; }; // basically no need to declare them as members. void rotate(state_a, double deg) { // do a } void rotate(state_b, double deg) { // do b } void rotate(actor& a, double deg) { std::visit([deg](auto &state){ rotate(state, deg); }, a.state); } Here is a more scalable version with templates: https://godbolt.org/z/58Kjx9h5W // actor.hpp #include <variant> template <typename ... StatesT> struct actor { std::variant<StatesT...> state; }; template <typename StateT> void rotate(StateT& s, double deg) { return rotate(s, deg); } template <typename ... StatesT> void rotate(actor<StatesT...> &a, double deg) { std::visit([deg](auto &state){ rotate(state, deg); }, a.state); } // other headers #include <iostream> struct state_a{}; struct state_b{}; // basically no need to declare them as members. void rotate(state_a, double deg) { // do a std::cout << "rotating a\n"; } void rotate(state_b, double deg) { // do b std::cout << "rotating a\n"; } int main() { auto actr = actor<state_a, state_b>{state_a()}; rotate(actr, 30); } Be advised, however, that "recursive" template <typename StateT> void rotate(StateT& s, double deg) will not work if you use a namespace for your states because of ADL. You either declare rotate AND state_a in the same namespace.
70,268,250
70,290,923
ImportError when accessing static variables from class in same namespace [C++/pybind11]
First of all, I am relatively new to C++ programming and pybind11. The following example should explain my problem: a.h: namespace test { class A { public: static int something; }; void setSomething(int input); } a.cpp: #include <pybind11/pybind11.h> #include "a.h" int test::A::something; void test::setSomething(int input) { A::something = input; } PYBIND11_MODULE(a, handle) { handle.doc() = "I'm a docstring hehe"; handle.def("setSomething", &test::setSomething); } b.h: namespace test { class B { public: B(); int getSomething() const; }; } b.cpp: #include <pybind11/pybind11.h> #include "a.h" #include "b.h" namespace py = pybind11; // int test::A::something; test::B::B(){} int test::B::getSomething() const { return A::something; } PYBIND11_MODULE(b, handle) { handle.doc() = "I'm a docstring hehe"; py::class_<test::B>(handle, "B") .def(py::init()) .def("getSomething", &test::B::getSomething); } So I have two classes A and B, which are defined in a.cpp and b.cpp that both have header files a.h and b.h. Basically, I am trying to access the static variable from class A in class B. Now if I compile them using CMake and try to run a test.py file I get an ImportError telling me undefined symbol: _ZN4test1A9somethingE. I hope this is not a stupid question. Thanks for your help in advance! Edit: If I define the variable within the class, it doesn't acquire the value set before or after outside the class.
Presumably you have used the above code to build two modules. Something like a.so and b.so that you would import into Python with separate import a and import b statements. That's not going to work: You need to access the static variables through the same binary object. Even if you got the linking to work right, ::test::A::something would have a different addresses in a.so and in b.so. (And if you are using the build system helpers from pybind, you won't even notice, because the "default hidden symbols" will prevent linking errors when you import the two modules.) You'll want to make sure that both a.cpp and b.cpp are linked into the same library object. In pybind, the first argument to the PYBIND11_MODULE is equated to the shared object library that you are building. If you want to arrange your software modularly like this, I would suggest defining the pybind module in a separate source file, and then passing the module object (which you have named handle) to functions that are responsible for adding class bindings. Example: module.cpp PYBIND11_MODULE(m, handle) { handle.doc() = "I'm a docstring hehe"; bind_a(handle); bind_b(handle); } a.cpp: void bind_a(py::module& m) { m.def("setSomething", &test::setSomething); } b.cpp: void bind_b(py::module& m) { py::class_<test::B>(m, "B") .def(py::init()) .def("getSomething", &test::B::getSomething); }
70,268,429
70,268,868
Creating t* array with adresses to t array fields
Can the following code be shortened? size_t n_arr{4}; int arr[4]{1, 4, 5, 6}; int* arr_p[4]; for (; n_arr—; ) arr_p[i] = &arr[i]; The adresses are all chained together, so is there a more efficient way of grabbing a block of adresses and storing them in another array?
You could do #include <numeric> ... std::iota(std::begin(arr_p), std::end(arr_p), arr); where std::iota is typically used to generate a sequential range of integers, it's generic and so generates a sequential range of pointers starting from arr (which itself is short for &arr[0]). More explicitly, #include <algorithm> ... std::transform(std::begin(arr), std::end(arr), arr_p, [](int& x) { return &x; }); which takes each element by reference and populates arr_p with pointers to those elements. https://godbolt.org/z/T8KGshn68
70,268,546
70,328,438
Need a faster way to create an adjacency list in c++
I'm trying to create an adjacency list from an input of vertices, edges and single connections. The input looks like this: 3 2 (vertices, edges) 1 2 (connection) 1 3 Right now, my code is int vertices, edges; scanf("%d %d", &vertices, &edges); vector<vector<int>> storage[vertices+1]; for (int i = 0; i < edges; i++) { int a, b; scanf("%d %d", &a, &b); if (find(storage[b].begin(), storage[b].end(), a) != storage[b].end() == false) { storage[b].push_back(a); } if (find(storage[a].begin(), storage[a].end(), b) != storage[a].end() == false) { storage[a].push_back(b); } } Is there a faster/more efficient way to do this, or is this the best way?
It's nearly impossible to give a general answer to this kind of question, because the execution time is going to depend on factors that may be orders of magnitude apart. For instance, it could be that the cost of populating the data structure is insignificant compared to what you do with it afterwards. See also this answer, whose final recommendation I'll quote: As always, profiling and measuring runtime and memory to find bottlenecks for you actual problem implementation is key if you are implementing a highperf computation program. That answer also mentions some different STL containers you could consider. Here and here are two more questions on this topic. With that said, measure before trying to improve anything. If reading the input piecewise turns out to be a bottleneck, for example, you could consider reading it all into a std::string in one go before further processing. For completeness, I might write your current code in standard C++ like this: #include <algorithm> #include <iostream> #include <vector> // ... // Speeds up std i/o, but don't mix the C and C++ interfaces afterwards std::ios_base::sync_with_stdio(false); int vertices, edges; std::cin >> vertices >> edges; std::vector<std::vector<int>> storage(vertices + 1); // When filling vectors with push_back/emplace_back, it's best to call // reserve first. If using 1-based indexing, skip the first vector: for (auto v = std::next(storage.begin()); v != storage.end(); ++v) v->reserve(vertices - 1); // With C++20 support you can #include <ranges> and write for (auto& v : storage | std::views::drop(1)) v.reserve(vertices - 1); auto found = [](auto const& vector, auto value) { return std::find(vector.begin(), vector.end(), value) != vector.end(); // or, with C++20: std::ranges::find(vector, value) != vector.end() }; for (int a, b, i = 0; i < edges && std::cin >> a >> b; ++i) { if (!found(storage[b], a)) storage[b].push_back(a); // ... }
70,268,598
70,268,915
Should you return a reference using operator+ for adding two classes together?
From the examples I have seen when people use the operator+ when adding two instances of a class, the usual pattern is to return an object. Suppose we have a Vector class with attributes u and v, an implementation of operator+ could be, Vector2 Vector2::operator+(const Vector2& other) { return Vector2(this->u + other.u, this->v + other.v); } Why is the standard pattern not to return a reference? This is returning an object that was created on the Stack, this means that it should be garbage collected later on when we leave the function and could lead to problems from what previously pointed to it. e.g. Vector2 v = Vector(10,20) + Vector(30, 40), would v later be pointing to a garbage collected variable? Because the result of Vector(10, 20) + Vector(30, 40) was created on a Stack (That we have now left). What I am saying is, why should this not be something like, Vector2* Vector2::operator+(const Vector2& other) { return new Vector2(this->u + other.u, this->v + other.v); }
Should you return a reference using operator+ for adding two classes together? No. Why is the standard pattern not to return a reference? Because the binary + operator conventionally returns a new object. Vector2 v = Vector(10,20) + Vector(30, 40), would v later be pointing to a garbage collected variable? No. C++ has no garbage collector, and Vector2 is presumably not a pointer. What I am saying is, why should this not be something like, Vector2* Vector2::operator+(const Vector2& other) { return new Vector2(this->u + other.u, this->v + other.v); } Because: Using bare owning pointers is a horrible idea. Returning bare owning pointer makes the idea even worse. Operator overloads that represent the abstract operation as the fundamental operation (for example, addition in this case) should conform to the same interface and behaviour as the fundamental operation. The type of 1 + 1 is not int*, and so the type of vector + vector shouldn't be Vector2*. There is no need to delete the result of 1 + 1 and so there shouldn't be a need to delete the result of vector + vector.
70,268,804
70,269,188
How does std::visit handle multiple variants?
Related to, but not the same question as How does std::visit work with std::variant? Implementing std::visit for a single variant conceptually looks like this (in C++ pseudocode): template<class F, class... Ts> void visit(F&& f, variant<Ts...>&& var) { using caller_type = void(*)(void*); caller_type dispatch[] = {dispatch_visitor(f, (INDEX_SEQUENCE))...}; dispatch[var.index()](var); }; Basically, we set up a jump table that calls the correct dispatcher for our visitor. For multiple variants, it seems to be more complicated, as for this approach you'd need to compute the Cartesian product of all the variants' alternatives and possibly template thousands of functions. Is this how it's done or is there a better way that standard libraries implement it?
For multiple variants, it seems to be more complicated, as for this approach you'd need to compute the Cartesian product of all the variants' alternatives and possibly template thousands of functions. There are currently two implementations of multi-variant visitation. GCC constructs a multi-dimensional function table at compile time according to the number of alternative types of variants, and access the corresponding visit function through multiple indexes at runtime. // Use a jump table for the general case. constexpr auto& __vtable = __detail::__variant::__gen_vtable< _Result_type, _Visitor&&, _Variants&&...>::_S_vtable; auto __func_ptr = __vtable._M_access(__variants.index()...); return (*__func_ptr)(std::forward<_Visitor>(__visitor), std::forward<_Variants>(__variants)...); MSVC uses recursive switch-case to perform multi-variant visitation: #define _STL_VISIT_STAMP(stamper, n) \ constexpr size_t _Size = _Variant_total_states<_Remove_cvref_t<_Variants>...>; \ static_assert(_Size > (n) / 4 && _Size <= (n)); \ switch (_Idx) { \ stamper(0, _STL_CASE); \ default: \ _STL_UNREACHABLE; \ } This switch-case base implementation has better performance when the number of variants is small or the number of alternatives is small, which also makes GCC use this approach for simple cases in its recent patch to reduce the instantiation of function tables. switch (__v0.index()) { _GLIBCXX_VISIT_CASE(0) _GLIBCXX_VISIT_CASE(1) _GLIBCXX_VISIT_CASE(2) _GLIBCXX_VISIT_CASE(3) _GLIBCXX_VISIT_CASE(4) case variant_npos: // ... } You can refer to the following two blogs by Michael Park for more implementation details: Variant Visitation Variant Visitation V2
70,268,991
70,269,262
What's "pitch" in cudaMemcpy2DToArray and cudaMemcpy2DFromArray
I'm converting the deprecated cudaMemcpyToArray and cudaMemcpyFromArray into cudaMemcpy2DToArray and cudaMemcpy2DFromArray. Rather than size of the deprecated calls, the new API calls for width, height, and pitch. The descriptions of spitch and dpitch are correspondingly "Pitch of source memory" and "Pitch of destination memory". I wonder what are those values: size of data items, something else? More specifically, if I were to copy W*H floats, should I have pitch=sizeof(float), width=W, height=H, or pitch=sizeof(float)*W, width=sizeof(float)*W, height=H, or something else?
It should be: pitch=sizeof(float)*W width = sizeof(float)*W height = H The above is for cudaMemcpy2DToArray, and assumes you are transferring from host to device, which would most likely involve an unpitched allocation in host memory as the source. The pitch of a pitched allocation is the size in bytes of one line of of a 2D allocation, including padding bytes at the end of the line. It is the value returned by cudaMallocPitch, for example. For unpitched allocations, it is still the width of the line, and it is given by W*sizeof(element) where the 2D allocation width is given by W elements each of size sizeof(element). This question and the link it refers to may also be of interest.
70,269,418
70,269,625
Copy all files .doc or .docx in folder and subfolder into another folder
I am new to C++ and winapi, currently working on a project to create a winapi application with a function to copy all files .doc and .docx in one drive to another folder. Below is what I have done and it doesn't seem to work: Can anyone show me how to do this properly ? void cc(wstring inputstr) { TCHAR sizeDir[MAX_PATH]; wstring search = inputstr + TEXT("\\*"); wcscpy_s(sizeDir, MAX_PATH, search.c_str()); WIN32_FIND_DATA findfiledata; HANDLE Find = FindFirstFile(sizeDir, &findfiledata); do { if (findfiledata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (!wcscmp(findfiledata.cFileName, TEXT(".")) || !wcscmp(findfiledata.cFileName, TEXT(".."))) continue; //checking folder or file wstring dirfolder = inputstr + TEXT("\\") + findfiledata.cFileName; cc(dirfolder); } else { wstring FileSearch = findfiledata.cFileName; //.doc or docx if (!wcscmp(FileSearch.c_str(), L".doc") || !wcscmp(FileSearch.c_str(), L".docx")) { TCHAR src[256] = L"D:\\test\\"; wstring dirsrc = inputstr + TEXT("\\") + findfiledata.cFileName; _tprintf(TEXT(" %s \n"), dirsrc.c_str()); wcscat_s(src, findfiledata.cFileName); CopyFile(dirsrc.c_str(), src, TRUE); } } } while (FindNextFile(Find, &findfiledata) != 0); FindClose(Find); } The inputstr here when i call the function is the drive that i want to search like cc(L"D:");
if (!wcscmp(FileSearch.c_str(), L".doc") || !wcscmp(FileSearch.c_str(), L".docx")) This is comparing the whole file name. We only need to compare the file extension. PathFindExtension can be used to find the file extension: const wchar_t* ext = PathFindExtension(findfiledata.cFileName); if (_wcsicmp(ext, L".doc") == 0 || _wcsicmp(ext, L".docx") == 0) { const std::wstring path = inputstr + L"\\" + findfiledata.cFileName; std::wcout << path << '\n'; } findfiledata should be zero initialized. Adding CopyFile inside that recursive function may cause problems. Because FindNextFile could see the new copied file, and the function tries to copy it again. You could instead save the result in a vector of strings, then copy the file once cc is finished. void cc(const std::wstring &inputstr, std::vector<std::wstring> &vec) { std::wstring wildcard{ inputstr + L"\\*" }; WIN32_FIND_DATA find = { 0 }; HANDLE handle = FindFirstFile(wildcard.c_str(), &find); if (handle == INVALID_HANDLE_VALUE) return; do { if (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (!wcscmp(find.cFileName, L".") || !wcscmp(find.cFileName, L"..")) continue; const std::wstring dir = inputstr + L"\\" + find.cFileName; cc(dir, vec); } else { const wchar_t* ext = PathFindExtension(find.cFileName); if (_wcsicmp(ext, L".doc") == 0 || _wcsicmp(ext, L".docx") == 0) { const std::wstring path = inputstr + L"\\" + find.cFileName; vec.push_back(path); } } } while (FindNextFile(handle, &find) != 0); FindClose(handle); } Used as std::vector<std::wstring> result; cc(L"D:\\test", result); for (const auto& e : result) std::wcout << e << '\n'; Note, PathFindExtension requires additional headers and libraries. If it's not available for some reason, and std::filesystem is not available, here is a do it yourself method: std::wstring test = findfiledata.cFileName; auto dot = test.find_last_of(L'.'); if (dot != std::wstring::npos) { auto ext = test.substr(dot); for (auto& e : ext) e = towlower(e); if (ext == L".doc" || ext == L".docx") { std::wstring path = inputstr + L"\\" + findfiledata.cFileName; std::wcout << path << '\n'; } }
70,269,593
70,269,682
C++ Get name of a template function argument
I want to replace all glXXXX calls to GL_CALL(N, ...) so that I can print function and arguments to trace the calls. For example, replace glClearColor(0.0f, 0.0f, 0.0f, 1.0f) to GL_CALL(ClearColor, 0.0f, 0.0f, 0.0f, 1.0f) and in console I get [GL_CALL] glClearColor(0, 0, 0, 1) #include <iostream> template <class T> void GL_TRACE_PRINT(T const &t) { std::cout << t << ","; } template<typename T, typename... Args> void GL_TRACE_PRINT(T n, Args ... args) { GL_TRACE_PRINT(n); GL_TRACE_PRINT(args...); } #define GL_STR(s) #s template <class F, typename ...Args> auto GL_INVOKE(F f, Args && ...args) { std::cout << "[GL_CALL] " << GL_STR(f) << '('; GL_TRACE_PRINT(std::forward<Args>(args)...); std::cout << ")\n"; return f(std::forward<Args>(args)...); } #define GL_CALL(N, ...) \ GL_INVOKE(gl##N, __VA_ARGS__); But how to print the function name in GL_INVOKE? Thanks. Or is there better way to do so? Currently the output is, the glXXX function names are all f. [GL_CALL] f(0,0,0,1,) [GL_CALL] f(0,0,0,1,)
You can pass the string name of the function into GL_INVOKE, something like this: template <class F, typename ...Args> auto GL_INVOKE(const char* fname, F f, Args && ...args) { std::cout << "[GL_CALL] " << fname << '('; GL_TRACE_PRINT(std::forward<Args>(args)...); std::cout << ")\n"; return f(std::forward<Args>(args)...); } #define GL_INVOKE_F(N, ...) \ GL_INVOKE(#N, N, ## __VA_ARGS__) #define GL_CALL(N, ...) \ GL_INVOKE_F(gl##N , ## __VA_ARGS__) Demo. In addition, your GL_TRACE_PRINT can be implemented using C++17 fold expression, which will be much more concise. template <class... Args> void GL_TRACE_PRINT(Args const&... args) { ((std::cout << args << ","), ...); }
70,269,889
70,282,968
How can I back up to an earlier value in Depth-First Search c++?
Here, I'm implementing Depth-First Search (DFS) in c++. However, I can't seem to find a way to back up to the previous place (i.e. 1->2->3 if 3 is end of line go back to 2) Can I use vectors or stacks to track my movements? int searcher(int line[3], int lineNumber) { int value = 0; if (line[0] == 1) { if (hasRunLine[lineNumber+1] != 1) { value = lineNumber + 1; } else { value = -1; // here it needs to go back and check whether it is at the start } } else if (line[0] = 2) { if (hasRunLine[line[1]] != 1) { value = line[1]; } else { value = -1; // here too } } else { if (hasRunLine[line[1]] != 1) { value = line[1]; } else if (hasRunLine[line[2]] != 1) { value = line[2]; } else { value = -1; // here too } } if (value <= maximum && value >= 2) { return value; } else { return -1; // here too } }
Use a vector and add a new movement everytime you switch to a different position.
70,269,944
70,270,105
Casting base class to derived class when derived class only adds non-virtual functions
Suppose I have something along these lines: class Base { public: Base(int value) : value_(value) {} int getValue() const { return value_; } private: int value_; }; class Derived : public Base { public: // Derived only has non-virtual functions. No added data members. int getValueSquared() const { return value_ * value_; } } And I do the following: Base* base = new Base(42); Derived* derived = static_cast<Derived*>(base); std::cout << derived->getValueSquared() << std::endl; Strictly speaking, this is UB. Practically speaking, it works just fine. Actual data members from Base (e.g., int value_) have to be located at the same offsets whether the object is an actual Base or an actual Derived (otherwise, good luck upcasting). And getValueSquared() isn't part of the actual memory footprint of a Derived instance so it's not like it will be "missing" or unconstructed from the in-memory Base object. I know that UB is all the reason I need not to do this but, logically, it seems it would always work. So, why not? I am asking because it seems like an interesting quirk to discuss...not because I plan on using it in production.
In practice, most compilers will convert a non-virtual member function into a static function with a hidden this parameter. As long as the function doesn't use any data members that aren't part of the base class, it will probably work. The problem with UB is that you can't predict it. Something that worked yesterday can fail today, with no rhyme or reason behind it. The compiler is given a lot of latitude on how to interpret anything that's technically undefined, and the race to find better optimizations means that unexpected changes can happen suddenly. Murphy's law says that these changes will be most evident when you're demoing the software to your most important boss or biggest customer.
70,270,325
70,280,019
How to reduce the size of the executable?
When I compile this code using the {fmt} lib, the executable size becomes 255 KiB whereas by using only iostream header it becomes 65 KiB (using GCC v11.2). time_measure.cpp #include <iostream> #include "core.h" #include <string_view> int main( ) { // std::cout << std::string_view( "Oh hi!" ); fmt::print( "{}", std::string_view( "Oh hi!" ) ); return 0; } Here is my build command: g++ -std=c++20 -Wall -O3 -DNDEBUG time_measure.cpp -I include format.cc -o runtime_measure.exe Isn't the {fmt} library supposed to be lightweight compared to iostream? Or maybe I'm doing something wrong? Edit: By adding -s to the command in order to remove all symbol table and relocation information from the executable, it becomes 156 KiB. But still ~2.5X more than the iostream version.
As with any other library there is a fixed cost and a per-call cost. The fixed cost for the {fmt} library is indeed around 100-150k without debug info (it depends on the compiler flags). In your example you are comparing this fixed cost of linking with the library and the reason why iostreams appears to be smaller is because it is included in the standard library itself which is linked dynamically and not counted to the binary size of the executable. Note that a large part of this size comes from floating-point formatting functionality which doesn't even exist in iostreams (shortest round-trip representation). If you want to compare per-call binary size which is more important for real-world code with large number of formatting function calls, you can look at object files or generated assembly. For example: #include <fmt/core.h> int main() { fmt::print("Oh hi!"); } generates (https://godbolt.org/z/qWTKEMqoG) .LC0: .string "Oh hi!" main: sub rsp, 24 pxor xmm0, xmm0 xor edx, edx mov edi, OFFSET FLAT:.LC0 mov rcx, rsp mov esi, 6 movaps XMMWORD PTR [rsp], xmm0 call fmt::v8::vprint(fmt::v8::basic_string_view<char>, fmt::v8::basic_format_args<fmt::v8::basic_format_context<fmt::v8::appender, char> >) xor eax, eax add rsp, 24 ret while #include <iostream> int main() { std::cout << "Oh hi!"; } generates (https://godbolt.org/z/frarWvzhP) .LC0: .string "Oh hi!" main: sub rsp, 8 mov edx, 6 mov esi, OFFSET FLAT:.LC0 mov edi, OFFSET FLAT:_ZSt4cout call std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long) xor eax, eax add rsp, 8 ret _GLOBAL__sub_I_main: sub rsp, 8 mov edi, OFFSET FLAT:_ZStL8__ioinit call std::ios_base::Init::Init() [complete object constructor] mov edx, OFFSET FLAT:__dso_handle mov esi, OFFSET FLAT:_ZStL8__ioinit mov edi, OFFSET FLAT:_ZNSt8ios_base4InitD1Ev add rsp, 8 jmp __cxa_atexit Other than static initialization for cout there is not much difference because there is virtually no formatting here, so it's just one function call in both cases. Once you add formatting you'll quickly see the benefits of {fmt}, see e.g. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0645r10.html#BinaryCode.
70,270,538
70,270,577
Setting all items in an array to a number without for loop c++
Right now, to set all items in an array to, say, 0, I have to loop through the entire thing to preset them. Is there a function or shortcut which can defaultly set all values to a specific number, when the array is stated? Like so: int array[100] = {0*100}; // sets to {0, 0, 0... 0}
If you want to set all the values to 0 then you can use: int array[100] = {0}; //initialize array with all values set to 0 If you want to set some value other than 0 then you can use std::fill from algorithm as shown below: int array[100]; //not intialized here std::fill(std::begin(array), std::end(array), 45);//all values set to 45
70,270,749
70,272,863
Emplace a std::array of non-movable objects that cannot be default constructed
I have a class that contains a std::mutex so it is not movable or copiable. struct MyObject { MyObject(std::string s_) : s(s_) {}; std::mutex lock; std::thread worker; std::string s; }; I can easily add this object to this map: std::map<int, MyObject> my_map; my_map.emplace(std::piecewise_construct, std::forward_as_tuple(5), std::forward_as_tuple("string0")); But I would like to use a std::array to hold several of them like such: std::map<int, std::array<MyObject, 3>> my_map; If MyObject is movable, then I can do: my_map.emplace(4, {MyObject("string0"), MyObject("string1"), MyObject("string2")}); but this doesn't work (as expected) when the MyObject isn't movable. I can't fall back to piecewise construction since the std::array cannot be constructed from a tuple of 3 strings. my_map.emplace(std::piecewise_construct, std::forward_as_tuple(4), std::forward_as_tuple("string0", "string1", "string2")); Is there a way to construct a std::array of non-moveable objects in place in the map? I'm using these questions as a reference. Is there a way to combine the answers? emplace and unordered_map<?, std::array<?, N>> How to allocate a non-copyable and non-movable object into std::map? I've also tried: std::array<MyObject, 3> list = { MyObject("string0"), MyObject("string1"), MyObject("string2") }; my_map.emplace(4, std::move(list)); with the idea that the list should be moveable, but this also does not work.
With custom array, you might do template <typename T, std::size_t N> struct MyArray { template <typename... Us> MyArray(Us&&... args) : arr{ std::forward<Us>(args)...} {} std::array<T, N> arr; }; void foo() { std::map<int, MyArray<MyObject, 3>> my_map; my_map.emplace(std::piecewise_construct, std::forward_as_tuple(4), std::forward_as_tuple(std::string("string0"), std::string("string1"), std::string("string2"))); } Demo
70,270,823
70,278,551
Why don't compilers call destructor automatically when an object is declared using new operator?
#include<iostream> using namespace std; class b { public: int *a; b (int val) { *a = val; } ~b() { cout << "destructor" << endl; delete a; } }; int main() { b *obj = new b(1); cout << "end" << endl; return 0; } Expected output: destructor end Received output: end In above code compiler don't call destructor when i make object using new operator but in case of normal object destructor is called successfully. what is the reason behind it?
There are at least three different reasons for creating an object with new; depending on why you do it, it may or may not be appropriate to delete it when done. The primary one is that you want to manage its lifetime: int *create(int i) { int *result = new int(i); return result; } Here, you don't want to destroy the int object when the function ends. Creating it with new means you have to take care of cleaning it up when you're done: int main() { int *xp = create(3); std::cout << *xp << 'n'; delete xp; // I'm done with it // more code can go here, but don't use xp return 0; } Another reason is that the object is an array, and you don't know its size at compile time, so you can't create it as an auto object: void f(int size) { int my_array[size]; // illegal, although some compilers allow it, sigh int *my_ptr = new int[size]; // okay, creates array with size elements // code that uses my_ptr goes here delete[] my_ptr; } But that one really should be written with std::vector<int>, which relieves you of the burden of having to remember to delete the array when you're done: void f(int size) { std::vector<int> my_array(size); // code that uses my_array // no delete, because no explicit new; my_array destructor handles the memory } And, finally, you might be dealing with an object that's so large you don't want to clutter the stack with it: struct my_large_type { long double filler[32768]; }; Yes, you can create an object like this on the stack: void g() { my_large_type x; } but having many of these things runs the risk of taking up more space than the stack can handle. So you can create them on the free store, with new: void g() { my_large_type *xp = new my_large_type; // code that uses *xp goes here delete xp; } The danger here is that you might forget to delete the memory, or, perhaps worse, that the code between the new and the delete might throw an exception, so the delete doesn't happen -- the memory allocated by new has just leaked. The right solution here is to use a smart pointer, so that you don't have to handle deleting the object yourself: void g() { std::unique_ptr<my_large_type> xp = new my_large_type; // code that uses *xp goes here // no delete; destructor will do it for you } To summarize: the situations where you want to clean up the newed object at the end of the block where it was created are best handled by not explicitly using new, but putting the responsibility into a class whose destructor will handle the cleanup. In these examples that would be std::vector and std::unique_ptr. That leaves the case where you want to explicitly manage the lifetime of the object, because you don't know at the time you create it how long it should hang around. In that case, if you don't clean it up, it simply won't get cleaned up; you told the compiler you'd take care of it, and the compiler trusts you.
70,270,927
70,271,403
How to manage various types of functions as containers
I am trying to manage function list through c++ template. template<typename T, typename... Args> std::map<std::wstring, std::function<T(Args...)>> mFuncs; Above code is not the correct sentence, but like above code concept, I want to manage various types of functions as a List. void RegisterFuncs() { mFuncs.emplace(L"Func1", [&]()->bool{ ... }); mFuncs.emplace(L"Func2", [&](int a, std::string b)->int{ ... }); mFuncs.emplace(L"Func3", [&](std::tuple<int,int>& a){ ... }); ... ... ... mFuncs.emplace(L"Func", [&](args...)->auto{ ... }); } template<typename... TArgs> inline auto CallFunc(const wchar_t* pKey, TArgs&&... pArgs) { ... ... return mFuncs[pKey](std::forward<TArgs>(pArgs)...); } How can I implement the above concept?
use std::any std::map<std::string, std::any> f; int i = 3; void RegisterFuncs() { f.emplace("func1", std::function<double(int)>([&](int k){i = k; return 5.0; })); f.emplace("func2", std::function<bool()>([](){return false; })); // ^^^^^^^^^^^^^^^^ cant use lambda type becuase any_cast doesnt support implicit casting } template<typename R, typename... Args> inline R CallFunc(const std::string& name, Args&&... args) { return std::any_cast<std::function<R(Args...)>>(f[name])(args...); } int main() { RegisterFuncs(); double r = CallFunc<double, int>("func1", 6); std::cout << "r: " << r << " i: " << i << "\n"; bool b = CallFunc<bool>("func2"); std::cout << std::boolalpha << "b: " << b << "\n"; //types must match exactly or bad_any_cast is thrown try { int c = CallFunc<int>("func2"); std::cout << "c: " << c << "\n"; } catch(std::bad_any_cast e) { std::cout << e.what(); } }
70,271,468
70,272,669
c++ enum characher from integer value
So my problem goes like this, i have to enter a number from 1-7 and for each respective number i have to print a letter from the word english(e is for 1, n is for 2, etc.) Here is my idea: #include <iostream> using namespace std; int main() { enum eng {e='e', n='n',g,l,i,s,h} }; int x; cout << "dati x\n"; cin >> x; if (x >= 0 && x <= 7) eng val = static_cast<eng>(x); cout << x; } i want the number ( x ) to be converted to its respective letter from the eng type, but the conversion gives me back the number( if i put 1 it gives me 1, if i put 2 it gives me 2) i tried assigning an char value to e and n in eng , to see what happens ,but its the same result, i know i can use switch,but i want to try to get this working
Discussing enums is somewhat beyond the scope of the question, because an enum is just the wrong tool here. The values of the letters in the word "english" are not consecutive and the names of an enums named constants are not easily accessible, hence the enum does not help to map an index to a character. The tool to map an index to a character is a std::string: std::string english{"english"}; if (x >= 1 && x < 8) std::cout << english[x-1]; Your bounds were wrong. "english" has only 7 characters, while your condition allows 8 different indices. Because array indexing is zero based but the taks asks you to use 1 based indexing, you need to subtract 1 to get the desired character. Moreover, its a matter of style, but it is common to use half open intervals (ie [1,8), lower bound included, upper bound not included).
70,272,799
70,273,923
Cannot create a socket in QT in windows
I am trying to open a socket in QT Creator and it compiles successfully but returns -1 when calling socket function (fails to create the socket). I am using the following code: #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <stdlib.h> int main() { unsigned int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); printf("Code: %d\n", sockfd ); // Creating socket file descriptor if ( sockfd == INVALID_SOCKET ) { perror("socket creation failed"); exit(EXIT_FAILURE); } return 0; } ServerAndClient.pro: QT -= gui core network CONFIG += c++11 console CONFIG -= app_bundle # You can make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ main.cpp # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target LIBS += -lws2_32 I have tried the following: Added QT -= gui core network instead of QT -= gui Used a hotspot instead of the WiFi [Thought it could be a problem with the network] Allowed the app to use private and public network from firewall: Cleaned the project before rebuilding
I was not calling WSAStartup. The following code is working. #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <stdlib.h> // Needed for _wtoi int main() { WSADATA wsaData = {0}; int iResult = 0; SOCKET sockfd; iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if ( sockfd == INVALID_SOCKET ) { perror("socket creation failed"); exit(EXIT_FAILURE); }else{ printf("Succeeded\n"); } return 0; }
70,273,072
70,275,024
How to use c++20 <ranges> in xcode 13?
I'm trying to use c++20 library in Xcode 13.1 #include <ranges> I have set Apple Clang - Languages - C++ to -std=c++20 and compiler default, but it still throws 'ranges' file not found.
According to this feature list https://en.cppreference.com/w/cpp/compiler_support/20 Clang 13 claims "Partial" support, while Apple Clang seems to have none. (Don't be confused by version numbers. Apple 13.1 doesn't have to be later than LLVM 13.0).
70,273,437
70,273,659
C++- Filling a 2D array from user input
I'm new to programming and was finding transpose of a matrix. However, I want the input of the matrix from the user and by writing the following code, the complier doesn't take any input values and immediately stops. I looked into previous questions posted here about the same but found non useful. #include<iostream> using namespace std; int main() { int rows,val; int num[rows][rows]; cin>> rows; for(int i=1; i<= rows; i++) { for(int j = 1; j <= rows; j++) { cin>> val; arr[i][j]= val; } cout<<endl; }
You can't use variables in array length if they aren't defined as one of the comments mentioned. arr[i][j] inside your nested for loop isn't declared so that would also give an error, I guess you wanted to use num array which you declared. The rest is all looking good
70,273,826
70,274,707
Reference Initialisation and Expression expected errors on for loop in cpp
Hoping that someone could provide some insight into the below 'error' that VS code is flagging in my C++ code. I recently got a new laptop (Macbook Pro M1 Pro chip) so I have set up my environment now. Everything looks good, however I seem to be getting reference initialisation and expected expression errors in a for loop that I wasnt previously getting - My other computer (Mac Mini M1 chip) does not have this issue and doesnt flag any errors. To note: The full code compiles fine, so there shouldn't be any issue with it, but interested to hear peoples thoughts and potentially a way to get rid of the error appearing? Example code block (I have a few for loops that are similar but serve different purposes, they are all showing the same error): Wallet &Blockchain::GetChainWallet(string WalletAddress) { for (Wallet &ChainWallet : _vWallets) { if (WalletAddress == ChainWallet.GetWalletID()) { return ChainWallet; break; } } } The errors I'm receiving are: reference variable "ChainWallet" requires an initializer expected an expression Full: [{ "resource": "/Users/carlbrand/Documents/GitHub/BRIK/src/cpp/Blockchain/Blockchain.cpp", "owner": "C/C++", "code": "252", "severity": 8, "message": "reference variable \"ChainWallet\" requires an initializer", "source": "C/C++", "startLineNumber": 70, "startColumn": 30, "endLineNumber": 70, "endColumn": 31 }] [{ "resource": "/Users/carlbrand/Documents/GitHub/BRIK/src/cpp/Blockchain/Blockchain.cpp", "owner": "C/C++", "code": "29", "severity": 8, "message": "expected an expression", "source": "C/C++", "startLineNumber": 70, "startColumn": 41, "endLineNumber": 70, "endColumn": 42 }] Is there anything wrong with what I'm doing? I just want to get rid of the errors :) Thanks in advance.
Apologies for the stupid question - as @molbdnilo advised in the comments, my configuration in vs code was set to too low of a standard - updated to c++11 and all looks good. Thanks I'll try to refrain from stupid questions in future :)
70,273,948
70,276,092
std::remove_reference clarification with code snippet
I am trying to understand how to use the std::remove_reference functionality in type_traits. This is the piece of code that I made template <class T> class example { public: T some_int; example(T inty) : some_int(inty){std::cout << "constructor called!" << "\n";} ~example(){std::cout << "destructor called!" << "\n";} }; template <class T> // return a value, hence return a copy of the object auto function(T ptr_object) -> typename std::remove_reference<decltype(*ptr_object)>::type{ ptr_object -> some_int = 69; return *ptr_object; } int main(){ example<int> classy(20); example<int> *ptr = &classy; auto hello = function<decltype(ptr)>(ptr); std::cout << hello.some_int << std::endl; } so this code compiles successfully however this is the output constructor called! 69 destructor called! destructor called! My aim is to return a copy of the object (and not a reference) therefore in my calculations, once i call the return in the function it should call also the constructor of the object, but this does not happen. Plus it calls the destructor 2 times. Can someone help me understand what I am getting wrong?
When you return a copy of the object, that creates a new object, which is what you want. So one destructor is the for the copy, and one is for the original. In other words your code works, but you can't see the copy constructor, add the line example(const example& cp) : some_int(cp.some_int){std::cout << "copy constructor called!" << "\n";} And the output is constructor called! copy constructor called! 69 destructor called! destructor called! By the way, your code looks a little clunky, but maybe that's the point? The alternative would be ... template <class T> T function(T* ptr_object) { ptr_object -> some_int = 69; return *ptr_object; } Which is more concise EDIT: I just noticed that @Jarod42 beat me to it (again)
70,273,951
70,309,736
How to sign data using ECDSA algorithm, in C++ with OPENSSL?
I have a 32bytes SHA256 digest data and need to sign it with ECDSA. The private key is in a .pem file. I've already made it in console using the command: openssl.exe dgst -sha256 -sign ecc.pem -out %sigfile% %data_file%. Now i need to do it in c++ and the results I have been getting isn't the same as in console. What are wrong in the code below, considering the command I uses in console? bool sign(unsigned char *digest) { BIO *b_pem; EVP_PKEY* pkey2 = nullptr; const char * fileName = "ecc.pem"; pkey2 = EVP_PKEY_new(); b_pem = BIO_new_file(ecFileName, "rb"); PEM_read_bio_PrivateKey(b_pem, &pkey, NULL, NULL)) unsigned char sign[200] = {0}; EVP_MD_CTX *mctx; const EVP_MD *md = EVP_get_digestbyname("SHA256"); size_t signlen = 0; mctx = EVP_MD_CTX_new(); if (EVP_DigestSignInit(mctx, NULL, md, NULL, pkey)<=0) { return false; } if (EVP_DigestSignUpdate(mctx, digest, 32) <= 0) { return false; } if (EVP_DigestSignFinal(mctx, sign, &signlen) <=0) { return false; } EVP_MD_CTX_free(mctx); return true; }
I found the solution I've been searched for. Reading some project examples that used ECDSA from OpenSSL, I realised that I needed to convert the ASN1 encoded signature to raw signature bytes. So, here is the approach I used to get the wished result: After sign the data by EVP_DigestSignFinal() function the code below was included and I could get the bytes in as and ar arrays. ECDSA_SIG * ec_sig; const BIGNUM *er = NULL; const BIGNUM *es = NULL; unsigned char *ar; unsigned char *as; size_t slen = EVP_PKEY_size(pkey); ec_sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&sign, slen); ECDSA_SIG_get0(ec_sig, &er, &es); ar = (unsigned char*)malloc(BN_num_bytes(er)); as = (unsigned char*)malloc(BN_num_bytes(es)); BN_bn2bin(er, ar); BN_bn2bin(es, as);
70,274,134
70,275,010
Merge two bitmask with conflict resolving, with some required distance between any two set bits
I have two integer values: d_a = 6 and d_b = 3, so-called distance between set bits. Masks created with appropriate distance look like below: uint64_t a = 0x1041041041041041; // 0001 0000 0100 0001 0000 0100 0001 0000 // 0100 0001 0000 0100 0001 0000 0100 0001 uint64_t b = 0x9249249249249249; // 1001 0010 0100 1001 0010 0100 1001 0010 // 0100 1001 0010 0100 1001 0010 0100 1001 The goal is to have a target mask, which has bits set with d_b, but simultaneously takes into account bits set in the a mask (e.g. first set bit is shifted). The second thing is that the distance in the target mask is not constant i.e. number of zeros between set bits in the target mask shall be equal to d_b or increased whenever between them is set bit in a uint64_t target = 0x4488912224488912; // 0100 0100 1000 1000 1001 0001 0010 0010 // 0010 0100 0100 1000 1000 1001 0001 0010 The picture to visualize the problem: The blue bar is a, yellow is b. I would rather use bit manipulation intrinsics than bit-by-bit operations. edit: Actually, I have the following code, but I am looking for a solution with a fewer number of instructions. void set_target_mask(int32_t d_a, int32_t d_b, int32_t n_bits_to_set, uint8_t* target) { constexpr int32_t n_bit_byte = std::numeric_limits<uint8_t>::digits; int32_t null_cnt = -1; int32_t n_set_bit = 0; int32_t pos = 0; while(n_set_bit != n_bits_to_set) { int32_t byte_idx = pos / n_bit_byte; int32_t bit_idx = pos % n_bit_byte; if(pos % d_a == 0) { pos++; continue; } null_cnt++; if(null_cnt % d_b == 0) { target[byte_idx] |= 1 << bit_idx; n_set_bit++; } pos++; } }
If target is uint64_t, possible d_a and d_b can be converted into bit masks via look-up table. Like lut[6] == 0x2604D5C99A01041 from your question. Look up tables can be initialized once per program run during initlalization, or in compile time using macro or constant expressions (constexpr). To make d_b spread, skipping d_a bits, you can use pdep with inverted d_a: uint64_t tmp = _pdep_u64(d_b_bits, ~d_a_bits); Then you can convert n_bits_to_set to contiguous bits mask: uint64_t n_bits = (1 << n_bits_to_set) - 1; And spread them using pdep again: uint64_t tmp = _pdep_u64(n_bits, tmp); (See Intrinsic Guide about pdep. Note that pdep is slow on AMD before Zen3. It's fast on Intel CPUs and Zen3, but not Bulldozer-family or Zen1/Zen2)
70,274,287
70,274,328
Is there any method to use 'delete' more efficiently instead of deleting one-by-one?
I'm trying to make function that gets only int parameters. So when other types(double, char, bool) are included I used delete to exclude that like this code: #include <iostream> using namespace std; int add_int(int x, int y){ return x + y; } int add_int(double, double) = delete; int add_int(int, double) = delete; int add_int(double, int) = delete; int add_int(bool, int) = delete; // need much more code.. very inefficient int main(void){ cout << add_int(1, true) << endl; // error should happen } But I think this is so inefficient. Is there any method like 'only int possible' or 'exclude double, char, bool(I mean input only one parameter)'?
Yes, you can use a function template that deletes everything. template<class X, class Y> int add_int(X, Y) = delete; Now, when the compiler is resolving a function call, it will select the template unless there is a function overload where implicit type conversion is not required. An overload that requires no conversions will be selected in preference to a template function. More information here: Overload resolution If you like, you can also make your implementations part of this template by adding specializations: template<> int add_int(int x, int y) { return x + y; }
70,274,364
70,274,933
Generate constexpr array (error: the value of 'sum' is not usable in a constant expression)
The Problem I need to generate all possible partitions of an integer m into the sum of j elements a_k, where each a_k can be -1, 0, or 1. This is a deterministic algorithm and as such it should be able to implement it at compile time. I would like to return a std::array with all possible combinations as constexpr. My Algorithm Plain and simple, there are 3^j combinations in total. So we loop over all of them and check if the sum is m. The total number of valid combinations will be \sum_{k=m}^{\lfloor (m+j)/2\rfloor}\binom{j}{k}\binom{j-k}{k-m} Thus we can calculate the size of the array (which is j times the number above) and simply queue in all the number combinations we obtain by brute force. My Code Check it on Godbolt I obtain the error error: the value of 'sum' is not usable in a constant expression 88 | if constexpr( sum == m ) I fail to see however, how sum is not known at compile time. How can I fix this? #include <array> #include <iostream> #include <utility> /** constexpr for loop **/ template <auto Start, auto End, auto Inc, class F> constexpr void constexpr_for(F&& f) { if constexpr (Start < End) { f(std::integral_constant<decltype(Start), Start>()); constexpr_for<Start + Inc, End, Inc>(f); } } /** constexpr binomials **/ template<std::size_t n, std::size_t k> struct Binomial { constexpr static std::size_t value = (Binomial<n-1,k-1>::value + Binomial<n-1,k>::value); }; template<> struct Binomial<0,0> { constexpr static std::size_t value = 1; }; template<std::size_t n> struct Binomial<n,0> { constexpr static std::size_t value = 1; }; template<std::size_t n> struct Binomial<n,n> { constexpr static std::size_t value = 1; }; template<std::size_t n, std::size_t k> constexpr std::size_t binomial() { return Binomial<n,k>::value; } /** formula from the picture **/ template<std::size_t j, std::size_t m> constexpr std::size_t n() { std::size_t result = 0; constexpr_for<m, (j+m)/2+1, 1>([&result](auto k){ result += binomial<j, k>() * binomial<j-k, k-m>(); }); return result; } /** constexpr power function **/ template<std::size_t i, std::size_t j> struct pow_t { constexpr static std::size_t value = i * pow_t<i, j-1>::value; }; template<std::size_t i> struct pow_t<i, 0> { constexpr static std::size_t value = 1; }; template<std::size_t i, std::size_t j> constexpr std::size_t pow() { return pow_t<i, j>::value; } /** actual function in question **/ template<std::size_t j, std::size_t m> constexpr std::array<int, j*n<j,m>()> integer_compositions() { std::array<int, j*n<j,m>()> result; std::size_t i = 0; constexpr_for<0, pow<3, j>(), 1>([&](auto k) { std::array<std::size_t, j> partition; std::size_t sum = 0; constexpr_for<0, j, 1>([&](auto l) { partition[l] = -((k/static_cast<std::size_t>(pow<3,l>()))%3-1); sum += partition[l]; }); if constexpr( sum == m ) // line 88 { constexpr_for<0, j, 1>([&](auto l) { result[j*i + l] = partition[l]; }); ++i; } }); return result; } int main() { constexpr auto list = integer_compositions<3, 1>(); return EXIT_SUCCESS; }
You're confusing the purpose of constexpr function. A constexpr function can be executed both at runtime and as part of constant expression, that depends on how you use the function (and probably if the compiler wants to optimize things at compile time). You don't need all these templated functions, since the whole purpose of constexpr functions is to avoid them for clarity, e.g., your binomial function can simply be: constexpr std::size_t binomial(std::size_t n, std::size_t k) { if (k == 0 || n == k) { return 1; } else { return binomial(n - 1, k - 1) + binomial(n - 1, k); } } And you can then do: // binomial(3, 2) is evaluated at compile-time std::array<int, binomial(3, 2)> x; static_assert(x.size() == 3); This can be done for all of your functions, except the last one (integer_compositions) because the return type depends on the parameter, so you need a template here. There are other issues in your code, for instance, you need to initialize your std::array in constexpr function, so std::array<..., ...> result{}(note the {} here). Below is a working version of your code that does not use all of these templates (this requires C++20, but only because operator== for std::array is only constexpr since C++20): #include <array> #include <iostream> /** constexpr binomials **/ constexpr std::size_t binomial(std::size_t n, std::size_t k) { if (k == 0 || n == k) { return 1; } else { return binomial(n - 1, k - 1) + binomial(n - 1, k); } } /** formula from the picture **/ constexpr std::size_t n(std::size_t j, std::size_t m) { std::size_t result = 0; for (std::size_t k = m; k <= (j + m) / 2; ++k) { result += binomial(j, k) * binomial(j - k, k - m); } return result; } /** constexpr power function **/ constexpr std::size_t pow(std::size_t a, std::size_t n) { std::size_t r = 1; while (n--) { r *= a; } return r; } /** actual function in question **/ template<std::size_t j, std::size_t m> constexpr std::array<int, j*n(j, m)> integer_compositions() { std::array<int, j*n(j, m)> result{}; std::size_t i = 0; for (std::size_t k = 0; k < ::pow(3, j); ++k) { std::array<std::size_t, j> partition{}; std::size_t sum = 0; for (std::size_t l = 0; l < j; ++l) { partition[l] = -((k/static_cast<std::size_t>(::pow(3, l)))%3-1); sum += partition[l]; } if (sum == m) // line 88 { for (std::size_t l = 0; l < j; ++l) { result[j*i + l] = partition[l]; } ++i; } } return result; } int main() { static_assert(integer_compositions<3, 1>() == std::array<int, 18>{}); } Note: The static assertion obviously fails because I have no clue what the 18 values are.
70,274,623
70,275,067
I have problem with least privilege principle. incrementing a member when an object is created
I want to keep track of the number of students in my system so, My idea was to make a static datamember in the "StudentController" class called "_numOfStudents" and increment it with the Student's constructor but it didn't work so, I moved it into the "Student" class and made that when a Student object is created the number increment by the help of the constructor. The problem is: isn't it not the Student class's business to know how many students are there thus breaking the principle of least privilege. what can I do better to keep track of the student objects' count. Student(string firstName, string lastName, int age,vector<float>&subjects)//Student conctructor { SetFirstName(firstName); setLastName(lastName); SetAge(age); SetMarks(subjects); this->m_id++; StudentController::_numberOfStudents++; } class StudentController//this is where i declared the static data member { private: list<Student> _students; public: static int _numberOfStudents; StudentController() {}; StudentController(list<Student>& st) :_students(st) {}; } } }; int StudentController::_numberOfStudents = 0;
When you try to do StudentController::_numberOfStudents++; in the constructor, the StudentController class is not yet defined, therefore the compiler doesn't know about that class and its static member.
70,275,112
70,275,240
C++-Output multiplication of two matrices using 2D matrix
I am new in programming and was doing a question about multipliaction of two matrix which are inputted from the user. I think I wrote the correct code for it. However, the output is a null matrix and I cannot pin point the mistake. #include<iostream> using namespace std; int main(){ int row1,col1,row2,col2,val; cin>>row1>>col1>>col2; int arr1[row1][col1]; int arr2[row2][col2]; int arr3[row1][col2]; row2=col1; for(int i=1;i<=row1;i++){ for(int j=1;j<=col1;j++){ cin>>val; arr1[row1][col1]=val; } cout<<endl; } for(int i=1;i<=row2;i++){ for(int j=1;j<=col2;j++){ cin>>val; arr1[row2][col2]=val; } cout<<endl; } for(int i=1;i<=row1;i++){ for(int k=1;k<=col2;k++){ for(int j=1;j<=col1;j++){ arr3[i][k]+=arr1[i][j]*arr2[j][k]; cout<<arr3[i][k]<<" "; } cout<<endl; } } }
When you are setting up your matrices (arr1 and arr2) you are using an incorrect index. for(int j=1;j<=col1;j++){ arr1[row1][col1] should be for(int j=1;j<=col1;j++){ arr1[i][j] Also, as mentioned, indices in C and C++ go from 0 to N-1, so you are accessing one value out-of-bounds. You should use: for (int j = 0; j < col1; j++) { arr1[i][j] Also, you are setting up arr1 twice, but forgetting to set up arr2.
70,275,235
70,275,897
C++ - Implicit conversion of unsigned long long to signed long long?
I'm having a rather strange warning being reported by clang-tidy 12.0.1. In the following code: #include <vector> int main() { std::vector<int> v1; const auto a = v1.begin() + v1.size(); return 0; } I see this warning being triggered: error: narrowing conversion from 'std::vector<int>::size_type' (aka 'unsigned long long') to signed type 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>::difference_type' (aka 'long long') is implementation-defined [bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions,-warnings-as-errors] const auto a = v1.begin() + v1.size(); ^ It was my understanding that when operating two integers with the same size but different signedness, the signed integer is converted to unsigned, not the other way around. Am I missing something here?
To show the actual types involved : // Operator+ accepts difference type // https://en.cppreference.com/w/cpp/iterator/move_iterator/operator_arith // constexpr move_iterator operator+( difference_type n ) const; #include <type_traits> #include <vector> #include <iterator> int main() { std::vector<int> v1; auto a = v1.begin(); auto d = v1.size(); // the difference type for the iterator is a "long long" static_assert(std::is_same_v<long long, decltype(a)::difference_type>); // the type for size is not the same as the difference type static_assert(!std::is_same_v<decltype(d), decltype(a)::difference_type>); // it is std::size_t static_assert(std::is_same_v<decltype(d), std::size_t>); return 0; }
70,276,228
70,276,348
Why does for cycle in vector of unique_ptr require default delete?
I am working in vs2019 and following code worked fine: std::vector<Foo*> foos; // fills vector for (Foo* foo : foos) { //do stuff } However, if i try to use unique_ptr like this: std::vector<std::unique_ptr<Foo>> foos; // fills vector for (std::unique_ptr<Foo> foo : foos) { //do stuff } then both vs and compiler are complaining (if I understand correctly) about Foo not having default delete. But std::unique_ptr<Foo> is used without problems in other parts of the codebase. Why is this happening and how to fix/circumvent this?
Try changing: for (std::unique_ptr<Foo> foo : foos) to for (std::unique_ptr<Foo>& foo : foos) because as mentioned in the comments by @drescherjm and @dave, the compiler should be complaining about the copy constructor being deleted (aka copying a unique_ptr is not allowed). The loop tries to copy each vector element hence the error. You can however iterate using a reference to the elements instead.
70,276,314
70,276,792
Erasing the first entry of a vector, after the maximum is reached
I have a vector in which i save coordinates. I perform a series of calculations on each coordinate, thats why i have a limit for the vector size. Right now i clear the vector, when the limit is reached. I'm searching for a method, that let's me keep the previous values and only erases the very first value in the vector. Simplified, something like this (if the maximum size of the vector would be 4). vector<int> vec; vec = {1,2,3,4} vec.push_back(5); vec = {2,3,4,5} Is this possible?
As suggested by @paddy, you can use std::deque, it is most performant way to keep N elements if you .push_back(...) new (last) element, and .pop_front() first element. std::deque gives O(1) complexity for such operations, unlike std::vector which gives O(N) complexity. Try it online! #include <deque> #include <iostream> int main() { std::deque<int> d = {1, 2, 3, 4}; for (size_t i = 5; i <= 9; ++i) { d.push_back(i); d.pop_front(); // Print for (auto x: d) std::cout << x << " "; std::cout << std::endl; } } Output: 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 6 7 8 9
70,276,777
70,277,008
specialization of variadic template function for std::tuple as return type
I'm implementing a template function which parses a string and returns a tuple of objects, like template <typename... Objects> std::tuple<Objects...> convert2data(const std::string_view& input) { return std::tuple<Objects...>{ internal::popNext<Objects>(input)... } ; } // usage auto data = convert2data<int, double>("1, 0.01") ; I specify the expected types as template arguments. Now I'd like to get the types "directly" from a named tuple type, perhaps more convenient for a user: using MyData = std::tuple<int, double> ; // included from some header auto data = convert2data<MyData>("1, 0.01") ; std::cerr << std::get<int>(data) ; // or better MyData data2 = convert2data("1, 0.01") ; I'm stuck in attempts to specify a specialization for this case, e.g. this code template <typename... Objects, class std::tuple<Objects...>> std::tuple<Objects...> convert2data(const std::string_view& input) { return convert2data<Objects...>(input) ; } does not get compiled. Is there a way to define such specialization for a template function where template type is used in the return value?
Something along these lines, perhaps: template <typename Tuple, size_t... Is> Tuple convert2dataHelper(const std::string_view& input, std::index_sequence<Is...>) { return std::make_tuple( internal::popNext<std::tuple_element_t<Is, Tuple>>(input)...); } template <typename Tuple> Tuple convert2data(const std::string_view& input) { return convert2dataHelper<Tuple>( input, std::make_index_sequence<std::tuple_size_v<Tuple>>{}); } This permits convert2data<std::tuple<int, double>>("1, 0.01"); syntax. Another approach based on partial specialization, that allows both convert2data<int, double>(...) and convert2data<std::tuple<int, double>>(...) to be called and do the same thing. template <typename... Ts> struct Convert2dataHelper { static std::tuple<Ts...> Do(const std::string_view& input) { return std::make_tuple(internal::popNext<Ts>(input)...); } }; template <typename... Ts> struct Convert2dataHelper<std::tuple<Ts...>> { static std::tuple<Ts...> Do(const std::string_view& input) { return Convert2dataHelper<Ts...>::Do(input); } }; template <typename... Ts> auto convert2data(const std::string_view& input) { return Convert2dataHelper<Ts...>::Do(input); }
70,276,951
70,278,076
Why doesn't automatic move work with function which return the value from rvalue reference input?
I already know automatic move is not woking with the function which return value from Rvalue Reference input. But why? Below is example code which automatic move is not working with. Widget makeWidget(Widget&& w) { .... return w; // Compiler copies w. not move it. } If the function input is from copy by value, automatic move works. Widget makeWidget(Widget w) { .... return w; // Compiler moves w. not copy it. }
Relevant part of the C++17 standard [class.copy.elision/3]: In the following copy-initialization contexts, a move operation might be used instead of a copy operation: If the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function... This does not hold for: Widget makeWidget(Widget&& w) { return w; } since w does not name an object with automatic storage duration (within the function). In C++20, the situation is different: An implicitly movable entity is a variable of automatic storage duration that is either a non-volatile object or an rvalue reference to a non-volatile object type. In the following copy-initialization contexts, a move operation might be used instead of a copy operation: If the expression in a return or co_­return statement is a (possibly parenthesized) id-expression that names an implicitly movable entity declared in the body or parameter-declaration-clause of the innermost enclosing function... Here, the reference w satisfies those requirements since it is an rvalue reference declared in the parameter-declaration-clause. Why the same was not until C++20? I cannot say; likely nobody proposed such a change before.
70,277,307
70,277,530
64-bit version of GCC not compiling 64-bit exe
I am beginner regarding gcc command line compilation. I need a help regarding -m64 flag. I installed gcc compiler using MinGW. I checked for gcc version by following, gcc -v command, which shows Target: x86_64-w64-mingw32. So I assume, 64-bit version of gcc is installed. Objective: I wrote a small program to check, if the main.exe is generated for 32 or 64 bit. #include<stdio.h> int main(void) { printf("The Size is: %lu\n", sizeof(long)); return 0; } I compiled using following command, gcc -o main main.c. When I execute the main.exe, it outputs, The Size is: 4. But I expected the output to be `The Size is: 8'. So i modified the command as gcc -m64 -o main main.c. When I executed the main.exe again, still it outputs `The Size is: 4' How to compile for 64-bit version exe?
As others have said in the comments, the size of long can be 8 or 4 bytes on a 64bit system. You can try sizeof(size_t) or sizeof(void*). Even this might not be reliable on every system (but should work for Windows, Linux, macOS).
70,277,378
70,277,617
Use of const and & in functions C++
I am trying to understand the useage of 'const' and '&' in the following function declaration. I know that the last 'const' means the function cannot change member variables in the class and that 'const std::string& message' means the variable passed to the function cannot be changed, but I don't understand the meaning of 'const Logger&'. What is the purpose of this first 'const' and why is there an '&' following 'Logger'? Is this function meant to return an address or a pointer? const Logger& log(const std::string& message) const;
So const Logger& is the return type of log. const means you will not be able to edit the return value at all. The return type Logger& means you'll get a reference to a Logger and not a copy of it.
70,277,561
70,277,658
Will asigning a variable to another variable result in it using a copy constructor or being a reference?
I am a little confused with the copy constructor and references in c++. Kat kat("hello kitty"); Kat newKat = kat; Will Kat use its copy constructor or will newKat just become a reference to Kat. Edit: sorry for the confusion, I mean for custom types.
Kat kat("hello kitty"); Kat newKat = kat; Will use the copy constructor Kat kat("hello kitty"); Kat& newKat = kat; Will create a reference
70,279,213
70,279,605
C++ [Error] invalid conversion from 'int' to 'int (*)[2]' [-fpermissive]
I am a beginner and I keep getting an error when I am calling my function. I am trying to get the user to input a value for the array and then get it to display it in a table format. Also, I am trying to display a 3x3 matrix in the end. void DMMatrix(int DM[2][2]){ int number; cout << "Input 0's and 1's to the DM[2][2]\n\n"; for (int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ cout << "DM[" << i << "]"<< "[" << j << "]: "; cin >> number; DM[i][j] = number; } } } int main(){ int i, j, sum = 0; int DM[2][2]; DMMatrix(DM[2][2]); cout << "\n\nOutput (table format)\n\n"; for(i = 0;i < 3;i++){ for(j = 0;j < 3;j++){ cout << " " << DM[i][j] << " "; } cout << "\n"; } sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] + DM[2][0] + DM[2][1] + DM[2][2]; if (sum % 2 == 0){ cout << "\nSum is " << sum; } }
There are 3 problems in your program. Mistake 1 You are calling the function DMMatrix incorrectly. The correct way to call DMMatrix would be: DMMatrix(DM);//CORRECT WAY OF CALLING DMMatrix Mistake 2 Your 2D array DM has 2 rows and 2 columns and you're accessing 3rd row and 3rd column of the array DM. But since the 3rd row and 3rd column doesn't exist, you have undefined behavior in your program. To solve this you can create a 3x3 2D array as shown below: #include <iostream> using namespace std; void DMMatrix(int DM[3][3]){//2 CHANGED TO 3 int number; cout << "Input 0's and 1's to the DM[2][2]\n\n"; for (int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ cout << "DM[" << i << "]"<< "[" << j << "]: "; cin >> number; DM[i][j] = number; } } } int main(){ int i, j, sum = 0; int DM[3][3]; //2 CHANGED TO 3 DMMatrix(DM); cout << "\n\nOutput (table format)\n\n"; for(i = 0;i < 3;i++){ for(j = 0;j < 3;j++){ cout << " " << DM[i][j] << " "; sum += DM[i][j];//CALCULATE SUM HERE } cout << "\n"; } cout << "\nSum is " << sum; } Mistake 3 You don't need to calculate the sum by writing each element of the array explicitly. You can calculate the sum inside the for loop in my modified above program. Also note that in your original code, while calculating the sum you were going out of bounds which leads to undefined behavior. The above shown program corrected this.
70,280,141
70,280,294
How to figure out the length of the result of `fmt::format` without running it?
While answering this question about printing a 2D array of strings into a table, I realized: I haven't found a better way to determine the length of the result of a fmt::format call that to actually format into a string and check the length of that string. Is that by design, or is there a more efficient way to go about that? I don't know the internals of fmtlib all too well, but I imagine, the length of the result is known before memory allocation happens. I'd especially like to avoid the memory allocation.
Straight from the API documentation: template<typename ...T> auto fmt::formatted_size(format_string<T...> fmt, T&&... args) -> size_t Returns the number of chars in the output of format(fmt, args...).
70,280,595
70,280,779
How to bind numbers together into an integer without addition?
For example: If I end up with multiple digits and all of those numbers are generated randomly (1-9) up to 7 digits total and I want them all to end up as a whole integer, how do I go by doing this? Here is something I have tried: static void generate_key(std::map<std::string, int>& key, std::string c_user) { unsigned int hold[7]{}; // will hold all the random integers seperate to add onto final int *final = new int; // will store a complete 7 digit integer here later on for (int i = 0; i < 7; i++) { unsigned int num = rand() % 9; hold[i] = num; } *final = hold[0] + hold[1] + hold[2] + hold[3]; // I know this sums everything but how do I get it to just add all the numbers into a single integer?! key.emplace(c_user, final); std::cout << "Key created: " << *final << '\n'; delete final; } Hold all integers seperate from eachother: unsigned int hold[7]{}; Create random digits: for (int i = 0; i < 7; i++) { unsigned int num = rand() % 9; hold[i] = num; } Store and add all integers into *final integer int *final = new int; I want to generate a 7 digit key and each of every single digit is randomized. I then want to add them all up to make a whole integer that gets put into a map where a string has already been created and that key will represent the string. Do you get what I'm saying here? Sorry if my explanation is terrible I'm just too lost here.. Here is the full code if thats helpful: #include <iostream> #include <string> #include <map> #include <vector> #include <stdlib.h> class Account { private: std::string username; std::string password; public: Account(std::string username, std::string password) { this->username = username; this->password = password; } ~Account() {}; std::string get_username()const { return username; } std::string get_password()const { return password; } }; static void create_account(std::string user, std::string pass, std::vector<Account> &acc) { Account *account = new Account(user, pass); acc.push_back(*account); delete account; } static void generate_key(std::map<std::string, int>& key, std::string c_user) { unsigned int hold[7]{}; int *final = new int; for (int i = 0; i < 7; i++) { unsigned int num = rand() % 9; hold[i] = num; } *final = hold[0] + hold[1] + hold[2] + hold[3]; key.emplace(c_user, final); std::cout << "Key created: " << *final << '\n'; delete final; } std::vector<Account> accounts; std::map<std::string, int> keys; int main() { srand(time(NULL)); create_account("random", "triathlon", accounts); generate_key(keys, accounts[0].get_username()); return 0; } static void create_account(std::string, std::string, std::vector<Account> &acc); static void generate_key(std::map<std::string, int>&, std::string);
If you want to generate a 7 digit number where all of the digits are unique, then you can store the valid digits in a vector and then shuffle that vector and take the first 7 elements as the digit to make the number with. That could be done like: std::vector<char> digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} std::random_device rd; std::mt19937 g(rd()); std::suffle(digits.being(), digits.end(), g); std::string number{digits.begin(), digits.begin() + 7} and now number is a 7 digit string where each digit only appears once. If you want to not have a leading zero, then you would need to check if the first element is a zero and if so, shuffle again or just takes elements 1 through 7. If you just want to generate a 7 digit number, but you don't care if there are duplicate digits, then you can do that with a std::string and a simple for loop like: std::random_device rd; std::mt19937 g(rd()); std::uniform_int_distribution<> dist(0, 9); std::string number; for (int i = 0; i < 7; ++i) { number.push_back('0' + dist(g)) }
70,280,815
70,280,890
What is calculated earlier in vector element assignment
If i have that line of code: vec[f1(x, y)] = f2(a, b); What would compiler run first: f1(x, y) or f2(a, b)?
f2(a, b) is computed first, per [expr.ass#1]1 (emphasis is mine): [...] In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand. [...] Note 1: that this is only true for C++17 onward, for previous standards, the order of evaluation was implementation-specific. Note 2: This is not specific to vector item assignment (there is no such thing in the standard), any assignment (or compound assignment) follows these rules. 1 This is from the C++17 latest draft (section 8.18), but the wording has not changed (yet), see [expr.ass#1] in the latest draft.
70,280,839
70,298,657
Getting a signed angle value
I'm having an issue with finding an angle between two vectors. I have this code (pic below) in blueprints, which uses dot product in order to find cos of the angle between two vectors. However, it seems that this method does not give me full information - I still cannot determine if the object, which position I am tracking, is left or right from me. I believe it is because cos is even function and does not provide information about angle's sign. Is there any way to determine angle's signed value? May be some C++ magic? I would really appreciate some help in this case.
Dot product will only give you the cosine of the angle formed by the two vectors. It is positive of they are facing the same direction, negative for opposite directions and 0 if they are perpendicular. Simply check the "RightDirection" to get the sign that corresponds to the original dot product. By doing this, you will exclude the zeros given by the cardinal directions, so substitute the opposite axis when zero. Here is the Blueprint pseudocode: Vector TargetDirection = Normalize(Player.GetActorLocation - Object.GetActorLocation); float LR = dot(TargetDirection, Player.GetActorRotation.GetRightVector); float SignLR = Sign(LR); // returns -1,0,1 float Angle = dot(TargetDirection,Player.GetActorRotation.GetForwardVector); // catch the dot product zeros at(0,90,180,270...) // if is a float comparison object with the bool output passed to a branch if(Angle == 0) Angle = LR; // pick a direction (90 degrees left or right) if(SignLR == 0) SignLR = Angle; //pick a direction float Signed Angle = SignLR * Angle; Note: The variables are not needed, when implementing this code, the output pin is wired directly to the multiple inputs.
70,281,216
70,281,906
IEntity* wLocalEntity pointer example code snipet
what does this C++ code snippet do? IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef()); if(wLocalEntity!=0){ mEntitySpeed=wLocalEntity->getSpeed(); } I'm not sure how it's related to a template creation. Can someone explain to me what this code does? Thank you.
Here's the code. IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef()); if(wLocalEntity!=0){ mEntitySpeed=wLocalEntity->getSpeed(); } If you actually get asked about this code, the first thing I'd do is complain about the if-clause. that 0 should be nullptr as so: if (wLocalEntity != nullptr) { mEntitySpeed = wLocalEntity->getSpeed(); } Also, please tell me you know you shouldn't compress your code so tightly. Bugs hide when you shove all those operators together with no whitespace. Now, let's look at line 1: IEntity* wLocalEntity = const_cast<IEntity*>(BaseSimSystem::getEntityRef()); Clearly, wLocalEntity is a pointer to an IEntity. I hope you understood that. The const_cast<> bit is ridiculous and possibly a bug. We don't know what BaseSimSystem::getEntityRef() returns, but I suspect it returns a const pointer, and now you're trying to assign that back to a non-const variable. The const_cast<> is getting rid of the constness. The correct code is almost certainly: const IEntity * wLocalEntity = BaseSimSystem::getEntityRef(); However, it's possible that IEntity has methods that aren't flag const that really should be, so you might have to do this because some other programmer didn't apply const when he should have. So the const_cast<IEntity *> says "take the return value in those parenthesis and yes, I know they're not a non-const IEntity *, but don't warn me about it because supposedly I know what I'm doing. How's that?
70,281,393
70,281,449
How to store an instance of class in a vector?
I have made a class for a student with course and grade, the program keeps asking for a new student until the name given is stop. To store these instances I want to use a vector, but I didn't find any other way to store them than creating an array for the instances first and then pushing them back into the vector. Is it possible to have room for one instance and delete the values stored in Student student after use so it can be reused? int i=0; Student student[20]; vector<Student> students; cout << "Name?" << endl; getline(cin,student[i].name); while((student[i].name) != "stop") { student[i].addcoursegrade(); students.push_back(student[i]); i++; cout << "Name?" << endl; getline(cin,student[i].name); if((student[i].name) == "stop") break; }; I also use vectors inside the class to store the values for course and grade, since they are also supposed to be growing. The code for the class is here: class Student { public: string name; void print() { cout << name ; for (int i = 0; i < course.size(); i++) cout << " - " << course[i] << " - " << grade[i]; cout<<endl; } void addcoursegrade() { string coursee; string gradee; cout << "Course?" << endl; getline(cin, coursee); course.push_back(coursee); while (coursee != "stop") { cout << "Grade?" << endl; getline(cin, gradee); grade.push_back(gradee); cout << "Course?" << endl; getline(cin, coursee); if (coursee != "stop") course.push_back(coursee); else if(coursee == "stop") break; } }; private: vector<string> course; vector<string> grade; };
Instead of creating an array then pushing back, simply keep one instance around and reassign it: Student student; vector<Student> students; cout << "Name?" << endl; getline(cin,student.name); while((student.name) != "stop") { student.addcoursegrade(); // this line copies the student in the vector students.push_back(student); // then, reassign the temp student to default values student = {}; cout << "Name?" << endl; getline(cin,student.name); if((student.name) == "stop") break; };
70,281,420
70,283,383
QRegExp a filename but its not matching
I'm trying to parse date time from a PNG file but can't quite get it with QRegExp this_png_20211208_1916.png QDateTime Product::GetObstime() { QDateTime obstime; QString filename = FLAGS_file_name.c_str(); QString year, month, day, hour, minute, second; QRegExp regexp = QRegExp("^.*\\w+_(\\d{4}\\d{2}\\d{2})_(\\d{2}\\d{2})\\.png$"); VLOG(3) << " filename: " << filename.toStdString(); if(regexp.indexIn(filename) !=-1) { VLOG(3) << " filename: " << filename.toStdString(); QStringList dt_bits = regexp.capturedTexts(); if(dt_bits.size() >=2) { year = dt_bits.at(1).mid(0, 4); month = dt_bits.at(1).mid(5, 2); day = dt_bits.at(1).mid(8, 2); hour = dt_bits.at(2).mid(0, 2); minute = dt_bits.at(2).mid(3, 2); second = dt_bits.at(2).mid(3, 2); VLOG(3) << " Year: " << year.toStdString() << " Month: " << month.toStdString() << " Day: " << day.toStdString() << " Hour: " << hour.toStdString() << " Min: " << minute.toStdString() << " Sec: " << second.toStdString(); QString datetime_str = year + "-" + month + "-" + day + "T" + hour + ":" + minute + second + "00Z"; obstime = QDateTime::fromString(datetime_str, Qt::ISODate); if (obstime.isValid()) { VLOG(3)<<"Date iS VALID: "<<obstime.toString(Qt::ISODate).toStdString(); } else { LOG(ERROR)<<" Error! Date Time bits did not match format."; } } } return obstime; } been using tools like https://regex101.com/ but to no avail. am I missing something?
You have the following errors in your code: month = dt_bits.at(1).mid(5, 2); should be month = dt_bits.at(1).mid(4, 2); because the index is 0-based, not 1-based day = dt_bits.at(1).mid(8, 2); should be day = dt_bits.at(1).mid(6, 2); minute = dt_bits.at(2).mid(3, 2); should be minute = dt_bits.at(2).mid(2, 2); second = dt_bits.at(2).mid(3, 2); should be second = "00"; because your filenames do not contain seconds Generally I would recommend doing all of the work in the regex instead of doing some fancy splitting using QString::mid(): QRegExp regexp = QRegExp("^.*\\w+_(\\d{4})(\\d{2})(\\d{2})_(\\d{2})(\\d{2})\\.png$"); This gives you all the fields in separate groupings, no need for QString::mid() at all.
70,281,499
70,281,593
how to use emplace_back to insert a new element into a vector of vector?
I'm confused by the syntax of some C++ concepts. Let's say I have a vector of vector: vector<vector<int>> data; I can use push_back() to insert a new element: data.push_back({1, 1}); In this way, I list initialized a new element, then a copy of this element is pushed to data? I can also do it in this way: vector<int> tmp{1, 1}; data.emplace_back(tmp); But if I directly call emplace(), like in this way: data.emplace_back(1, 1); It does not give me the expected result. Did I misunderstand something here? ---update: sorry, what I mean is emplace_back. My question is how to initialize directly using emplace_back instead of initializing a tmp vector first, vector<int> tmp{1, 1};.
I can use push_back to insert a new element: data.push_back({1, 1}); In this way, I list initialized a new element, then a copy of this element is pushed to data? exactly. data.emplace(1, 1); vector<Type>::emplace_back forwards its arguments to the constructor of Type. Now, std::vector<int> has a constructor that takes two integer arguments! The one specifying length (1) and fill element (1). You can, however, inform the compiler you actually mean list initialization! #include "fmt/format.h" #include "fmt/ranges.h" #include <initializer_list> #include <vector> int main() { std::vector<std::vector<int>> a; a.emplace_back(std::initializer_list<int>{1, 1}); a.emplace_back(std::initializer_list<int>{2, 2}); fmt::print("{}\n", fmt::join(a.begin(), a.end(), ";")); } yields the expected {1, 1};{2, 2} To show it really does the in-place construction: Follow this link to gcc.godbolt.org, and observe how push_back({3,3,3,3}); actually calls the vector<int> constructor and then the insert of the vector<vector>, while emplace_back really just calls the initializer-list constructor.
70,281,683
70,281,937
Inherit from boost::matrix
I would like to inherit from boost::matrix to enrich with some methods. I started with this : #include <boost/numeric/ublas/matrix.hpp> using namespace boost::numeric::ublas; class MyMatrix : public matrix<double> { public: MyMatrix() : matrix<double>(0, 0) {} MyMatrix(int size1, int size2) : matrix<double>(size1, size2) {} MyMatrix(MyMatrix& mat) : matrix<double>(mat) {} MyMatrix(matrix<double>& mat) : matrix<double>(mat) {} MyMatrix& operator=(const MyMatrix& otherMatrix) { (*this) = otherMatrix; return *this; } }; that allows me do to stuff like: MyMatrix matA(3, 3); MyMatrix matB(3, 3); MyMatrix matC(matA); but I may missed something because I am not able do to: MyMatrix matD(matA * 2); MyMatrix matE(matA + matB); that causes: error: conversion from 'boost::numeric::ublas::matrix_binary_traits<boost::numeric::ublas::matrix<double>, boost::numeric::ublas::matrix<double>, boost::numeric::ublas::scalar_plus<double, double> >::result_type {aka boost::numeric::ublas::matrix_binary<boost::numeric::ublas::matrix<double>, boost::numeric::ublas::matrix<double>, boost::numeric::ublas::scalar_plus<double, double> >}' to non-scalar type 'MyMatrix' requested How can I use the methods from boost::matrix without redefining all of them inside MyMatrix ?
You don't need any of your additions to make this work: MyMatrix matA(3, 3); MyMatrix matB(3, 3); MyMatrix matC(matA); MyMatrix matD(matA * 2); MyMatrix matE(matA + matB); You only need to bring the boost::numeric::ublas::matrix<double> constructors and assignment operators into your derived class: #include <boost/numeric/ublas/matrix.hpp> class MyMatrix : public boost::numeric::ublas::matrix<double> { public: using matrix<double>::matrix; // use the constructors already defined using matrix<double>::operator=; // and the operator=s already defined // put your other additions here (except those you had in the question) }; Demo
70,281,975
70,282,519
Steal the 3 least significant bits from a double?
I am working on a programming language and in short I need to steal the 3 least significant bits from a double, when working with an integer I can do the following long long int make(long long int x) { return x << 3; } long long int take(long long int x) { return x >> 3; } However when doing that to doubles (first converting into a long long binary representation of course) it simply makes the number not anywhere like it was. Worth to mention that my code will only ship to platforms where CHAR_BIT == 8. Ideas?
Since type punning isn't allowed in C++, here's a version copying the double to a unsigned char array and clears the 3 least significant bits in it and then copies it back into the double: #include <bit> #include <cstring> #include <limits> double take(double x) { static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big); static_assert(std::numeric_limits<double>::is_iec559); unsigned char buf[sizeof x]; std::memcpy(buf, &x, sizeof x); if constexpr(std::endian::native == std::endian::little) buf[0] &= 0b11111000; else buf[sizeof buf - 1] &= 0b11111000; std::memcpy(&x, buf, sizeof x); return x; } Demo
70,282,341
70,282,592
How do I read in a string and transfer to an array?
In this c++ code, I am taking a string from std::cin and transferring each char item into a char array. int length; // length of the string cin >> length; char charList[length]; // list of the characters string sequence; // string sequence cin >> sequence; for (int i = 0; i < length; i++) { charList[i] = sequence[i]; } I am not sure if this is the right way to do this or if I am getting something wrong. Are the items out of the indexed string char or string type?
First of all, to answer your doubt about the type: sequence[i] is of type char. Next, concerning your implementation: to start with, as many people have suggested in the comments, I recommend not getting the length of the string separately from the string itself, because the length of the input string may be different from the declared length, and this may cause all sort of problems (ever heard of the infamous bug heartbleed?) So, this is the minimum I would do: string sequence; // string sequence cin >> sequence; char charList[sequence.length()]; // list of the characters for (int i = 0; i < sequence.length(); i++) { charList[i] = sequence[i]; } However, this is still not satisfactorily enough because the above code is not conformant. In other words it is not valid C++ because C++ does not really allow variable-length arrays. Depending on the compiler you may get away with it, for instance g++ accepts it, see https://stackoverflow.com/a/15013295/12175820 But even with g++, if you compile with the -pedantic flag you'll get the following warning: str2arr.cpp:10:8: warning: ISO C++ forbids variable length array ‘charList’ [-Wvla] 10 | char charList[sequence.length()]; // list of the characters which compounded to -Werror gives a full-blown compilation error: str2arr.cpp:10:8: error: ISO C++ forbids variable length array ‘charList’ [-Werror=vla] 10 | char charList[sequence.length()]; // list of the characters Plus you might have trouble with more advanced usage, for instance I've just discovered that typeid(charList) won't compile with a variable-length array... So the real way to do this in C++ would be using pointers and dynamic-memory allocation, in the heap, using operator new: string sequence; // string sequence cin >> sequence; char* charList = new char[sequence.length()]; // list of the characters for (int i = 0; i < sequence.length(); i++) { charList[i] = sequence[i]; } the above code is valid C++ accepted by any compiler.
70,282,443
70,283,169
How can one construct an object from a parameter pack in a C++ template?
Given the following, how can I correctly construct an object of an unknown type from a parameter pack? template < typename... Types > auto foo( Types&&... types ) { auto result = Types{ }; // How should this be done? // Do stuff with result return result; } I expect the template function to only be called with matching types, so everything in the parameter pack should be of the same type. It doesn't matter which individual item I reference if I need to use decltype, for example (relevant code in the commented out section will cause compilation errors otherwise).
Since all the types in the parameter pack are the same, you can first use the comma operator to expand the parameter pack, then use decltype to get the type of the last operand. template<typename... Types> auto foo(Types&&... types) { auto result = decltype((Types{}, ...)){ }; // Do stuff with result return result; } Demo.
70,282,477
70,316,577
Partially updating D3D11 constant buffer
In my spare time, I am working on a 3D engine using D3D11. To get the 3D effect, I use the typical model view projection matrix multiplication in my HLSL shaders. These matrices are uploaded to a d3d11 constant buffer. The projection matrix only changes when the viewport is resized but the model and view matrix can change on a frame per frame basis (when the model or camera is moved). These changes in the matrices must be uploaded to the same constant buffer in order to be used in the shaders. When uploading these changes, the projection matrix is (generally) not changed so I do not want to reupload this matrix. So in short, I need to partially update my constant buffer by only updating specific parts (offsets) in my buffer. In openGL, we have uniform buffers and these work (I think) in the same way as a d3d11 constant buffer does. However, if you want to update a specific part of the uniform buffer, you can use the openGL function glBufferSubData. I tried looking for a similar way to do this in D3D11 but I did not found anything. I did find someone with a similar issue but he was using D3D11.1. link to original post: How to partially update constant buffer in DirectX 11.1. Someone also said that in D3D11, you need to upload all the data in to the constant buffer if you want to change a specifi portion. But this could result in keeping an entire copy of my buffer on the CPU side (RAM). There must be a better way right? tldr; How can I update my d3d11 constant buffer on a specific offset?
You have several options to manage those. The simplest ones is to create one constant buffer per update rate (so you would have one buffer for world matrices, which changes per object, one for view which would update once per frame, and one for projection which updates very sporadically. That said, I never found the fact of splitting view and projection matrices to be that beneficial (I mean we speak about a 64 bytes extra data update per frame, which is really nothing, specially considering constant buffers are aligned on a 256 bytes boundary). This is also even more true if you will start to add shadow maps (if you do frustum fitting your shadow camera projection matrix can change every frame). Also if you plan to other post effects later on (like ao, depth of field...), you will also need to add extra data for camera (position, view inverse, view projection inverse, projection inverse), so it's generally more beneficial to update all that camera data once per frame (I normally use a reserved cbuffer slot for camera buffer, so I don't have to rebind it all the time).
70,282,521
70,283,786
Error decomposing gcc command into separate compile and link steps
I am getting a linker error building a simple project using scons. The example commands show integrated compiling and linking of program binaries, which scons does not do (though I probably could force it to, I'd rather not if possible). This command works fine: gcc -o main.exe main.cpp C:\raylib\raylib\src\raylib.rc.data -s -static -Os -IC:\raylib\raylib\src -DPLATFORM_DESKTOP -lraylib -lopengl32 -lgdi32 -lwinmm Whereas these two fail: g++ -o main.o -c -DPLATFORM_DESKTOP -Os -static -IC:\raylib\raylib\src main.cpp ld -o mains.exe c:\raylib\raylib\src\raylib.rc.data -s -static main.o -LC:\raylib\raylib\src -lraylib -lopengl32 -lgdi32 -lwinmm Resulting in: c:\raylib\w64devkit\bin\ld: cannot find -lopengl32 c:\raylib\w64devkit\bin\ld: cannot find -lgdi32 c:\raylib\w64devkit\bin\ld: cannot find -lwinmm Any insights? I'm not particularly familiar with the .rc.data files.
I would try to get gcc's library search path: ]$ gcc -x cpp-output -E -v /dev/null 2>&1 | grep LIBRARY_PATH | sed 's/:/\n/g' LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/ /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/ /usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/ /lib/x86_64-linux-gnu/ /lib/../lib/ /usr/lib/x86_64-linux-gnu/ /usr/lib/../lib/ /usr/lib/gcc/x86_64-linux-gnu/11/../../../ /lib/ /usr/lib/ see if the missing libraries are in any of those directories, and if they are then add them to the ld invocation as -L<path> option. EDIT To see ld search path when it is called on its own, I think this should work: ]$ ld --verbose | grep SEARCH_DIR | sed 's/;/\n/g' SEARCH_DIR("=/usr/local/lib/x86_64-linux-gnu") SEARCH_DIR("=/lib/x86_64-linux-gnu") SEARCH_DIR("=/usr/lib/x86_64-linux-gnu") SEARCH_DIR("=/usr/lib/x86_64-linux-gnu64") SEARCH_DIR("=/usr/local/lib64") SEARCH_DIR("=/lib64") SEARCH_DIR("=/usr/lib64") SEARCH_DIR("=/usr/local/lib") SEARCH_DIR("=/lib") SEARCH_DIR("=/usr/lib") SEARCH_DIR("=/usr/x86_64-linux-gnu/lib64") SEARCH_DIR("=/usr/x86_64-linux-gnu/lib") When you eliminate duplicates you'll notice that /usr/lib/gcc/x86_64-linux-gnu/11/ is an additional directory that is being searched when linking with gcc (your first command) but not when linking directly with ld. But that's on my machine. On yours it will probably be a bit different.
70,282,552
70,283,249
How to erase certain element of a vector of pointers
Hello i'm curently coding a fonction that erase element from a vector of pointer(to class object), but i cant quite make it work. I get this error error: no matching function for call to ‘std::vector<biblio::Reference*>::erase(biblio::Reference*&)’ std::vector<Reference*> m_vReferences; //Reference is a class for ( auto iter : m_vReferences) //Loop for on every pointer to a class object { if (iter->reqId () == p_id) //Check if the id of the class object is the id we want { m_vReferences.erase (iter); //Erase the pointer in the vector of pointer } else { throw EmptyReferenceException (iter->reqFormatedReference ()); //An exception } }
Don't use auto-range loops when you want to delete the element from the container. I would use std::remove_if as it is available in standard library. m_vReferences.erase(std::remove_if(m_vReferences.begin(),m_vReferences.end(),[p_id](Reference* x){ return x->reqId() == p_id; }),m_vReferences.end()); or you may loop through vector find at which index is the element you want to delete and use erase function from vector.
70,282,687
70,282,772
How to reconstruct a 4 byte uint8 array into a uint32 integer
I have a web app (javascript) that needs to send a arduino(ESP32) a 12bit value (0x7DF). I have a websocket connection that only accepts a Uint8_t payload, so I split the value into 4 bytes (Uint8_t). I can send the array to the arduino, but how do i reconstruct it back into a 32bit value? This is the code i am using to turn it into bytes: const uInt32ToBytes = (input) => { const buffer = Buffer.alloc(4) buffer.writeUInt32BE(input, 0) return [ buffer[0], buffer[1], buffer[2], buffer[3] ] } //With an input of 0x7DF i get an output of [0, 0, 7, 223] I have tried a lot of options given in other questions but none work. This is what they suggested: uint32_t convertTo32(uint8_t * id) { uint32_t bigvar = (id[0] << 24) + (id[1] << 16) + (id[2] << 8) + (id[3]); return bigvar; } //This returns an output of 0. Any help is appreciated EDIT: My convert function has a test variant and not the original solution. fixed that.
On Arduino, ints are 16 bit, so id[0] << 24 (which promotes id[0] from uint8_t to int) is undefined (and wouldn't be able to hold the value anyways, making it always 0). You need some casts beforehand: return (static_cast<uint32_t>(id[0]) << 24) | (static_cast<uint32_t>(id[1]) << 16) | (static_cast<uint32_t>(id[2]) << 8) | (static_cast<uint32_t>(id[3]));
70,283,216
70,283,451
Correct way to use WideCharToMultiByte when using unicode
I asked a question recently about using unicode and the problems that arose here: argument of type "WCHAR *" is incompatible with parameter of type "LPCSTR" in c++ In solving one problem, I encountered another one that has taken me now a literal rabbit hole of differences between ansi and unicode. I have learnt a lot but I still cannot seem to solve this problem after almost a week of trying. I looked at How do you properly use WideCharToMultiByte as I think this is what I need to convert the find_pid from unicode wchar back to char otherwise I get erros but to no avail. All help little or small is appreciated as this is driving me mad. Here is what I am trying to solve: DWORD find_pid(const wchar_t* procname) { // Dynamically resolve some functions HMODULE kernel32 = GetModuleHandleA("Kernel32.dll"); using CreateToolhelp32SnapshotPrototype = HANDLE(WINAPI *)(DWORD, DWORD); CreateToolhelp32SnapshotPrototype CreateToolhelp32Snapshot = (CreateToolhelp32SnapshotPrototype)GetProcAddress(kernel32, "CreateToolhelp32Snapshot"); using Process32FirstPrototype = BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32); Process32FirstPrototype Process32First = (Process32FirstPrototype)GetProcAddress(kernel32, "Process32First"); using Process32NextPrototype = BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32); Process32NextPrototype Process32Next = (Process32NextPrototype)GetProcAddress(kernel32, "Process32Next"); // Init some important local variables HANDLE hProcSnap; PROCESSENTRY32 pe32; DWORD pid = 0; pe32.dwSize = sizeof(PROCESSENTRY32); // Find the PID now by enumerating a snapshot of all the running processes hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hProcSnap) return 0; if (!Process32First(hProcSnap, &pe32)) { CloseHandle(hProcSnap); return 0; } while (Process32Next(hProcSnap, &pe32)) { if (lstrcmp(procname, pe32.szExeFile) == 0) { pid = pe32.th32ProcessID; break; } } // Cleanup CloseHandle(hProcSnap); return pid; } //changing to std::wstring does not work, already tried std::string parentProcess = "C:\\hello.exe" DWORD pid = find_pid(parentProcess.c_str());
Most likely your problem is that you're compiling with UNICODE defined. In this case PROCESSENTRY32 will actually be PROCESSENTRY32W. But you're calling the ASCII-Version of Process32First instead of the unicode-version Process32FirstW. Most of the winapi functions that accept both ascii & unicode arguments have 2 separate versions: the ascii one, those usually end with A (or nothing) the unicode on, those usually end with W A macro that switches between the ascii and unicode versions depending on wether UNICODE is defined or not. In your case that would be: #ifdef UNICODE #define Process32First Process32FirstW #define Process32Next Process32NextW #define PROCESSENTRY32 PROCESSENTRY32W #define PPROCESSENTRY32 PPROCESSENTRY32W #define LPPROCESSENTRY32 LPPROCESSENTRY32W #endif // !UNICODE Also keep in mind that Process32First will also populate your PROCESSENTRY32 (with the first found entry). So with your current implementation you'll always skip over the first process. If you're building a windows app it's best to decide from the start if you want to use ascii or unicode. (there's also the option to make both compile with TCHAR & friends) Mixing them within a single app will lead to a lot of conversion problems (since not every unicode character can be represented in your ascii code page) Also it'll make your life a lot easier if you just rely on the linker to import the functions instead of using GetProcAddress(). If you want to stick with unicode (the default for new projects), you could write your function like this: #include <windows.h> #include <tlhelp32.h> DWORD find_pid(const wchar_t* procname) { // Init some important local variables HANDLE hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); // Find the PID now by enumerating a snapshot of all the running processes if (hProcSnap == INVALID_HANDLE_VALUE) return 0; if (!Process32First(hProcSnap, &pe32)) { CloseHandle(hProcSnap); return 0; } do { if (lstrcmp(procname, pe32.szExeFile) == 0) { CloseHandle(hProcSnap); return pe32.th32ProcessID; } } while (Process32Next(hProcSnap, &pe32)); // not found CloseHandle(hProcSnap); return 0; } and call it like this: std::wstring parentProcess = L"C:\\hello.exe"; DWORD pid = find_pid(parentProcess.c_str()); // or just: DWORD pid = find_pid(L"C:\\hello.exe"); If you want your application to be able to compile for both unicode & ascii, you'll have to use TCHAR: #include <windows.h> #include <tlhelp32.h> #include <tchar.h> DWORD find_pid(const TCHAR* procname) { // Init some important local variables HANDLE hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); // Find the PID now by enumerating a snapshot of all the running processes if (hProcSnap == INVALID_HANDLE_VALUE) return 0; if (!Process32First(hProcSnap, &pe32)) { CloseHandle(hProcSnap); return 0; } do { if (lstrcmp(procname, pe32.szExeFile) == 0) { CloseHandle(hProcSnap); return pe32.th32ProcessID; } } while (Process32Next(hProcSnap, &pe32)); // not found CloseHandle(hProcSnap); return 0; } and call it like this: DWORD pid = find_pid(_T("C:\\hello.exe"));
70,283,504
70,283,574
Program doesn't run functions repeatedly (C++)
I am making an autoclicker. The "ClickLoop" function I found on another SO post works, but I am trying to add a key to toggle the autoclicker on and off. This is my code so far: #include <windows.h> #include <iostream> #include <chrono> #include <thread> #include <random> bool on = false; void tick () { if(GetKeyState('x') & 0x8000) { on = !on; } tick(); }; void WINAPI ClickLoop(int delay) { std::cout << "test" << std::endl; while ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) == 0) { Sleep(1); } int nCurrKeyState = GetKeyState(VK_LBUTTON); int nPrevKeyState; do { if (on) { INPUT Input; ZeroMemory(&Input, sizeof(INPUT)); Input.type = INPUT_MOUSE; Input.mi.dwFlags = MOUSEEVENTF_LEFTUP; SendInput(1, &Input, sizeof(INPUT)); Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN; SendInput(1, &Input, sizeof(INPUT)); // Delay in MS Sleep(delay); nPrevKeyState = nCurrKeyState; nCurrKeyState = GetKeyState(VK_LBUTTON); if ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) == 0) break; } else { break; } } while (nCurrKeyState != nPrevKeyState); ClickLoop(delay); } int main() { int delay; std::cout << "Delay in milliseconds: "; std::cin >> delay; tick(); ClickLoop(delay); return 0; } I then use G++ to compile the code: g++ main.cpp -o main After running the "main" executable, I find that it starts up, asks me for the delay and then stops after a couple of seconds. Why does this happen?
void tick () { ... tick(); } This is an endless recursion loop. Once main() calls tick(), the program is stuck in this loop and never reaches ClickLoop(). void WINAPI ClickLoop(int delay) { ... ClickLoop(delay); } This is also an endless recursion loop. You need to get rid of these recursive loops. Another problem I see is that you are using GetKeyState() in places, but GetKeyState() depends on the calling thread having a message loop to process WM_(L|M|R)BUTTON(DOWN|UP) window messages to update the thread's internal keyboard state. But there is no window or message loop in this code. GetAsyncKeyState() does not depend on a window or a message loop.
70,284,279
70,284,362
Overriding a virtual function but not a pure virtual function?
I'm attempting to derive a class C from two classes, A and B; after reading this answer, I attempted to write using B::<function> in order to override a pure virtual function in A with the implementation in B. However, the approach in that answer does not work for pure virtual functions; in that case, I found that I needed to be more explicit. So evidently using can resolve ambiguity, but it can't introduce an implementation? I was just hoping to better understand what is going on here. struct A { // this would result in ambiguity: //virtual void e(void) const {} // ERROR: member 'e' found in multiple base classes // resolving ambiguity with 'using' virtual void f(void) const {} // OK // this would result in an unimplemented method: //virtual void g(void) const = 0; // ERROR: variable type 'C' is an abstract class // *** why doesn't this work? *** //virtual void h(void) const = 0; // ERROR: variable type 'C' is an abstract class // resolving ambiguity by explicitly defining what I want virtual void i(void) const = 0; // OK }; struct B { void e(void) const {} void f(void) const {} void g(void) const {} void h(void) const {} void i(void) const {} }; struct C : public A, public B { using B::f; // sufficient to pin down 'f' using B::h; // not sufficient to pin down 'h' void i(void) const { B::i(); } // sufficient to pin down 'i' }; int main() { C X; X.e(); X.f(); X.g(); X.h(); X.i(); }
I attempted to write using B::<function> in order to override a pure virtual function in A with the implementation in B. You misunderstood. It is not possible to override a function this way. All that using B::h; does: it introduces B::h into the scope of struct C, so that X.h(); in main() becomes equivalent to X.B::h();. So, A::h() remains pure virtual, thus you cannot instantiate struct C.
70,284,505
70,284,611
Is possible to create Java generics class depending on int value?
We can create a generic class in Java like this public class MyClass<T> { ... but, now that i'm translating a (very large) C++ code to Java, i need a class to be different from other depending on its size, like in this c++ code: template<size_t size> class MyClass { ... so every class is a different type, there static members are different, and members like "compare" can only be used with objects with the same size. Is possible to do this in Java? if not, how would you handle this?
No, you can't use values as parameters instead of a generic type in Java. You should probably just take the size as a parameter in the constructor and implement safety checks taking the size into account.
70,285,043
70,286,649
the n should be inclusive or exclusive when using std::nth_element?
Hi I have a question on the usage of std::nth_element. If I want to obtain the k-th largest element from a vector, should it inclusive or exclusive? int k = 3; vector<int> nums{1,2,3,4,5,6,7}; std::nth_element(nums.begin(), nums.begin()+k-1, nums.end(), [](int& a, int& b){return a > b;}); int result = nums[k-1] or int k = 3 vector<int> nums{1,2,3,4,5,6,7}; std::nth_element(nums.begin(), nums.begin()+k, nums.end(), [](int& a, int& b){return a > b;}); int result = nums[k-1] It reminds me that when we get a subarray using iterator, it should be exclusive? for example, vector<int> sub(nums.begin(), nums.begin()+k); So, the n for nth_element is also exclusive?
This is the type of question that is best to figure out and understand by playing around with a bunch of examples on your own. However, I'll try to explain why you're getting the same answer in both of your examples. As explained in cppreference, std::nth_element is a partial sorting algorithm. It only guarantees that, given an iterator to an element n as its second argument: All of the elements before this new nth element are less than or equal to the elements after the new nth element. ("Less than or equal to" is the default behavior if you don't pass a special comparison function.) That means if you use nums.begin()+k-1 in one case and nums.begin()+k in another case as the second argument to std::nth_element, then in the latter case the partial sorting algorithm will include one additional item in the sort. In that case, you are dividing the vector between larger and smaller items at a spot one index higher than in the first case. However, the (default) algorithm only guarantees that each of the items in the "small half" of the vector will be smaller than each of the items in the "large half," not that the two halves are sorted within themselves. In other words, if you've done a partial sort through nums.begin()+k, there is no guarantee that nums[k-1] will be the next-smallest (or in your case, the next-largest) number in the entire vector. With certain inputs, like your {1, 2, 3, 4, 5, 6, 7}, or {9, 4, 1, 8, 5}, you do happen to get the same answers. However, with many others, like {1, 4, 9, 8, 5}, the results do not match: int k = 3; vector<int> nums{1,4,9,8,5}; auto numsCopy = nums; // First with +k - 1 std::nth_element(nums.begin(), nums.begin()+k-1, nums.end(), [](int& a, int& b){return a > b;}); // Then with only +k std::nth_element(numsCopy.begin(), numsCopy.begin()+k, numsCopy.end(), [](int& a, int& b){return a > b;}); cout << nums[k-1]; // 5 cout << numsCopy[k-1]; // 9 Demo Can you figure out why that is? Also, to clearly answer your question about inclusive vs exclusive, as @Daniel Junglas pointed out in the comments, the second argument to std::nth_element is meant to point directly to the item you wish to be changed. So if it helps you, you can think of that as "inclusive." This is different from the third argument to std::nth_element, the end iterator, which is always exclusive since .end() points beyond the last item in the vector.
70,285,762
70,286,123
Perform Operations like add, sub, mul, div, mod on 2 integers with their bytes
I have got the bytes of 2 integers (say 32 bit int) now is it possible to add them using the bytes? I have like char b1[4], b2[4]; int a= 2311; int b= 233134; memcpy(b1, &a, 4); memcpy(b2, &b, 4); My question is is there any algorithm to add, mul, sub the numbers from bytes and the number of bytes of number is not fixed it may be 32 bit, 64 bit, 128 bit. Note i do not want any library or framewprk just c++
Your question is in its heart not about the implementation in C++, but about algorithms to do simple arithmetic. For all the operation you mention, remember how you did it in primary school. Apply that algorithms, replacing single decimal digits by bytes. The principle stays the same. It's all mathematics. You need to think how you detect carries and borrows between the bytes. Because you mentioned int as data type, you need to take the sign into account. It is easier if the values are unsigned.
70,285,888
70,287,213
SDL2: Sometimes make segement fault while Rendering and Event Polling in the different thread
So in my project I make a Event thread to catch the sdl event and may be pass it to the main thread to rander. But sometimes I get the Segementfault. this is my test code. #include "SDL2/SDL.h" #include <SDL2/SDL_timer.h> #include <iostream> #include <thread> using namespace std; int main() { SDL_Init(SDL_INIT_EVERYTHING); bool running = true; /* this is my event thread */ auto run = [&] { for (; running; ) { SDL_Event event; SDL_PollEvent(&event); // ... SDL_Delay(10); } }; thread t(run); /* and the main is the randering thread */ for (int i = 0; i < 10; ++i) { SDL_Window *window = SDL_CreateWindow("cycle. ", 100, 100, 600, 600, SDL_WINDOW_SHOWN); SDL_Renderer *screen = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); // ... do some rander ... // may be i will get some task to rander use the blocking queue SDL_Delay(500); SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); } running = false; t.join(); SDL_Quit(); } I want to know why I get the segement fault. Should I make the Event listening and the rander in the same thead? (This will cause another problem: If placed in the same thread, when I set the loop to only 60 times per second, it also means that I can only render 60 times per second. This will cause my program to become stuck.)
Fundamentally, you should try to call SDL from a single thread. Even if you decide you need to multithread your program, you should do work in other threads and then synchronize that work to the main thread, which should use SDL to render / event-handle / etc. Your program may be segfaulting because you're attempting to join() a thread that already join()-ed, so you want to at least check joinable() before you do so. You also need to call PollEvent in a loop, since multiple events may be queued here. But, especially since you're using Delays, it seems like you won't need the possible performance gained by multithreading your events. I would therefore suggest something like this: #include <SDL2/SDL.h> #include <iostream> #include <thread> using namespace std; int main() { SDL_Init(SDL_INIT_EVERYTHING); bool running = true; SDL_Window *window = SDL_CreateWindow("cycle. ", 100, 100, 600, 600, SDL_WINDOW_SHOWN); SDL_Renderer *screen = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); /* and the main is the randering thread */ while (running) { SDL_Event event; while (SDL_PollEvent(&event)) { // TODO: handle events // for example, set `running` to false when the window is closed or // escape is pressed // ... } // TODO: render here // ... } SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); SDL_Quit(); } I'm not going to assume what you do and don't need, so here's a possible solution where you multithread the events (but you really, really, really should only use this if you absolutely need it). This does the same as your code, except it calls PollEvent in the same thread as the rendering (the main thread), but handles the events somewhere else. For this we use a queue of events, and a mutex to make sure it's thread-safe. I'm just putting this here for completeness' sake, and you probably (definitely) don't need this. #include <SDL2/SDL.h> #include <iostream> #include <mutex> #include <queue> #include <thread> using namespace std; int main() { SDL_Init(SDL_INIT_EVERYTHING); bool running = true; std::mutex eventQueueMutex; std::queue<SDL_Event> eventQueue; auto handleEvents = [&running, &eventQueue, &eventQueueMutex] { while (running) { { // scope for unique_lock std::unique_lock<std::mutex> lock(eventQueueMutex); if (!eventQueue.empty()) { auto event = eventQueue.front(); eventQueue.pop(); lock.unlock(); // TODO: handle the event here } } // end of scope for unique_lock std::this_thread::sleep_for( std::chrono::milliseconds(16)); // adjust this to your needs } }; std::thread eventHandlerThread = std::thread(handleEvents); SDL_Window *window = SDL_CreateWindow("cycle. ", 100, 100, 600, 600, SDL_WINDOW_SHOWN); SDL_Renderer *screen = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); /* and the main is the randering thread */ while (running) { SDL_Event event; eventQueueMutex.lock(); while (SDL_PollEvent(&event)) { eventQueue.push(event); // copy event into queue } eventQueueMutex.unlock(); // TODO: render here // ... } if (eventHandlerThread.joinable()) { eventHandlerThread.join(); } SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); SDL_Quit(); } In both of these examples, check for my TODO comments to see where you write your code.
70,285,938
70,286,275
Unknown string from Dynamic Loaded Golang to CPP
So, I tried to run my go code on C++ project with dynamic loading. It's working great, except there is some unwanted string on returned value. As I explained down, I got some information from Go that unwanted. My go code: package main import "C" func main() {} //export GetTestString func GetTestString() string { return "test" } I build it with: go build -buildmode=c-shared -o test.so test.go Dynamically load it on my CPP project with this function: typedef struct { const char *p; ptrdiff_t n; } GoString; void getTestString() { void *handle; char *error; handle = dlopen ("./test.so", RTLD_LAZY); if (!handle) { fputs (dlerror(), stderr); exit(1); } // resolve getTestString symbol and assign to fn ptr auto getTestString = (GoString (*)())dlsym(handle, "GetTestString"); if ((error = dlerror()) != NULL) { fputs(error, stderr); exit(1); } // call GetTestString() GoString testString = (*getTestString)(); printf("%s\n", testString.p); // close file handle when done dlclose(handle); } Output is: "testtrue ...\n H_T= H_a= H_g= MB, W_a= and cnt= h_a= h_g= h_t= max= ptr siz= tab= top= u_a= u_g=, ..., fp:argp=falsefaultgcingpanicsleepsse41sse42ssse3 (MB)\n addr= base code= ctxt: curg= goid jobs= list= m->p= next= p->m= prev= span= varp=(...)\n, not SCHED efenceerrno objectpopcntscvg: selectsweep (scan (scan) MB in dying= locks= m->g0= nmsys= s=nil\n, goid=, size=, sys: GODEBUGIO waitSignal \ttypes \tvalue=cs fs gctracegs panic: r10 r11 r12 r13 r14 r15 r8 r9 rax rbp rbx rcx rdi rdx rflags rip rsi rsp runningsignal syscallunknownwaiting etypes goalΔ= is not mcount= minutes nalloc= newval= nfree..."
When passing strings via pointer to C you need either use length (n) in GoString to fetch right number of characters as string at p is not \0 terminated. Or you can return *C.char instead of string and use C.CString() to allocate copy on C heap (which you then are responsible for freeing after use). See Cgo documentation here. What is happening in your code is that printf() simply prints all characters starting from location pointed to by string.p until it hits \0 terminator - that's why you see contents of memory after test. So you can do either something like: printf("%.*s\n", testString.n, testString.p); (but note that most functions that operate on C strings which are expected to be \0 terminated will not work on this pointer unless they also take length of string) or change Go part to something like this and then free() pointer after use on C side: func GetTestString() *C.char { return C.CString("test") // CString will allocate string on C heap }
70,285,955
70,291,536
Advantages of aggregate classes over regular classes
In my use case I needed to initialize a class variable using an initializer list. I learnt that an aggregate class is a class that just has user defined data members in it. The advantage of aggregate is that we can use initializer list like this struct fileJobPair { int file; int job; }; fileJobPair obj = {10, 20}; But if I add a constructor to it, the class no longer remains an aggregate struct fileJobPair { int file; int job; fileJobPair() { file = job = 0; } fileJobPair(int a, int b) { file = a; job = b; } }; But I see that the initializer list advantage that we had for aggregate classes can still be used over here. fileJobPair obj = {10, 20}; So my question is why do we even need an aggregate if the same thing can be acieved by regular class. What are the advantages and real life use case of aggregates.
What are the advantages <...> of aggregates Unlike "usual" classes, aggregate types: have pre-defined "constructor" (your example) need no tuple-like interface boilerplate for structured bindings: struct { int field1, field2; } aggregate; auto&& [_1, _2] = aggregate; have designated initializers: Aggregate{.something = 42, .something_else = "whatever"}; Maybe there's something else I didn't think about. What are the <...> real life use case of aggregates E.g. you can (de)serialize them with no boilerplate thanks to #2, see also Boost.PFR. You can easily merge them (like tuples), "foreach" their fields etc. An example for #3: replace tons of the Builder pattern code with struct Foo { struct Builder { std::string_view a, b, c; }; constexpr Foo(Builder); // TODO } example{{.a = "cannot set a field twice", .c = "can skip fields"}}; the same thing can be acieved by regular class As you can see, it either cannot or requires extra boilerplate.
70,286,284
70,314,730
clang-format: how to change behavior of line break
Using clang-format, I want the result somewhat like this: value = new MyClass(variable1, variable2, mystring + "test", another_variable); But I don't want the result below: value = new MyClass(variable1, variable2, mystring + "test", another_variable); How can I do?
You could try the following parameters in your .clang-format file (How do I specify a clang-format file?): AlignOperands: true PenaltyBreakAssignment: 21 PenaltyBreakBeforeFirstCallParameter: 1 AlignOperands: you want to align the operands after a break line (as you align another_variable below) PenaltyBreakAssignment: 21 because is the shortest value suitable for your case (you have available a playground here) PenaltyBreakBeforeFirstCallParameter: as documentation describes: The penalty for breaking a function call after call(., so it should be greater than 0. You can learn more on what a penalty is on clang-format: In clang-format, what do the penalties do? Another related and insightful answer: Clang-format: How to avoid new line breaks PS: consider using smart pointers in C++ ;)
70,286,610
70,286,971
invalid initializer for structured binding declaration
How should I fix this error? Should I use a const std::tuple<int, int, char> instead? constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' }; This gives errors like: error: structured binding declaration cannot be 'constexpr' 434 | constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' }; error: invalid initializer for structured binding declaration 434 | constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' }; Y_AxisLen and X_AxisLen should be of type int and fillCharacter should be a char.
structure binding isn't allowed to be constexpr now. structure binding can only be applied to the following cases. array tuple-like structure data members ref: https://en.cppreference.com/w/cpp/language/structured_binding If you must use structure binding, use std::make_tuple const auto [ Y_AxisLen, X_AxisLen, fillCharacter ] = std::make_tuple(36, 168, ' ');
70,286,980
70,287,110
Iterate through a vector of shared_ptr
I have two classes (sheep and wolf) derivating from one (animal). I created a vector of shared pointer like that: std::vector<std::shared_ptr<animal>> animals; for (int i = 0; i < n_sheep; i++) { auto my_sheep = std::make_shared<sheep>(); animals.push_back(std::move(my_sheep)); } for (int i = 0; i < n_wolf; i++) { auto my_wolf = std::make_shared<wolf>(); animals.push_back(std::move(my_wolf)); } What is the best way to iterate through this vector and to know the difference between those smart_ptr ? Something like that: for (int i = 0; i < animals.size(); i++) { if (animals[i] == sheep) //TODO if (animals[i] == wolf) //TODO Thank you all.
"The best" depends on several things. For example, who controls the definition of the class Animal? I really like to do something akin to: class Animal { public: virtual std::string what() = 0; }; class Wolf : public Animal { public: virtual std::string what() { return "wolf"; } }; class Sheep : public Animal { public: virtual std::string what() { return "sheep"; } }; You can also define an enum to get rid of the need to compare strings, but of course, this would mean that you will lose the ability to add more animals without editing that enum. If you are unable to alter Animal, you can just do something like: if( typeid(*animals[i]) == typeid(Wolf) ) { // do wolfy things } else if( typeid(*animals[i]) == typeid(Sheep) ) { // do sheepish things }
70,287,188
70,288,201
Linking together dlls built with different gcc, error : file not recognized: File format not recognized
I am trying to build with GCC 4.6.1 a project in C++0x that links with a C++17 dll generated with GCC 11.2.0. I am using Netbeans IDE 7.4 (I think it doesn't matter). So, the compiling (with GCC 4.6.1) output is the following: libdriver17.dll: file not recognized: File format not recognized. libdriver17.dll is indeed my dll generated with GCC 11.2.0. My driver driver17.h: #ifndef DRIVER_H #define DRIVER_H #include <stdarg.h> #ifdef __cplusplus extern "C" { #endif const char* __stdcall init_driver(void); #ifdef __cplusplus } #endif #endif /* DRIVER_H */ driver17.cpp: #include <string> #include "driver17.h" std::string my_str; const char* init_driver(){ int x = 45; my_str = std::to_string(x); return my_str.c_str(); } main_cpp0x.cpp: #include "../dependencies/driver17.h" #include <iostream> int main(){ std::cout<<init_driver()<<std::endl; } my c++0x Makefile: g++ -std=c++0x main_cpp0x.cpp -o test -I../dependencies -L../dependencies -ldriver17 dependencies is indeed where my dependencies are... (driver17.h and libdriver17.dll). I think it is possible to link together different gcc built dlls but I have no idea what I am doing wrong. I am using Windows btw. Thank you.
I was compiling driver17 in 64bits, and main_cpp0x.cpp in 32bits.
70,287,257
70,288,129
What are the adavantages and use cases of CRTP compiletime polymorphism?
I see we could introduce some sort of compiletime polymorphism using CRTP, however I wonder how this can be better than good old virtual functions. In the end we have to call static_cast<const T*>(this)->implementation(); which is one level of indirection exactly like a vtable does. How are they different? Are there any advantages? I see only the downside that they cannot be destroyed by baseclass. To me it looks nice as an academic examlpe, but dominated by regular polymorphism.
The reason is performance. static_cast<const T*>(this)->implementation(); is resolved at compile-time to the address of the corresponding T::implementation() overload: CALL <fixed-address> A virtual member call on the other hand, is generally resolved at run-time using an indirect call via an offset in a vtable. In the simplest cases the optimizer can transform this to compile-time, but there is no way to do this reliably. So generally you can expect the code to look like this: MOV rax, <vtable-ptr> MOV rax, [rax+<offset>] ; Indirection via a vtable CALL rax This type of call will most likely take a pipeline stall on the first invocation due to the data dependency on the target address, and subsequent invocations will rely heavily on the quality of the branch predictor. The static call on the other hand is very fast as it does not involve a pipeline stall.
70,287,259
70,287,537
How Precedence of Relational Operator handled in C++
According to precedence rules <, >, <=, >= has precedence over !=, == I am so confused that how the following statement will be executed int a=3, b=3; cout<< (a != b || a <= b); I know short circuit evaluation and according to precedence rules I guess that compiler will execute a <= b first as it has precedence over != but it is not doing so. I did little experiment with above statement by changing a <= b-- and changing order of above conditions and it seems that <= and != have same precedence as compiler execute whichever occurred first. Or I am missing something?
Precedence of operators is only relevant to how expressions are bound, not to how they're executed. Execution order is dependent on the "happens-before" relationship and otherwise subject to arbitrary reordering by the compiler. Relative precedence of two operators also only matters if they are directly adjacent. In a == b <= c, you get a == (b <= c), not (a == b) <= c. In a == b || c <= d, the adjacent pairs are == and || and || and <=. In both cases the comparison operators bind more strongly, so you get (a == b) || (c <= d), making the relative precedence of == and <= irrelevant. If you have a == b + c <= d instead, you first get a == (b + c) <= d, and now you need to compare == and <= again, getting you a == ((b + c) <= d). As for order of evaluation, || has a rule that its left side is sequenced before its right side (assuming it's not overloaded), because the right side might not get evaluated at all. So the == is executed first. But precedence plays no part at all in this. If you instead had written the non-short-circuiting a != b | a <= b, both sides would eventually get executed (with caveats, see below), but there are no guarantees which side gets evaluated first; precedence does not play a part here. Caveat: the compiler can still just optimize your code and realize that a != b || a <= b is tautological, and simply replace the entire thing with true.
70,287,587
70,292,047
Type definitions dependent on template parameters
I am currently working with template classes in C++. In these classes, I am using types that are again dependent on the template parameters. In order to not type the parameters all the time, I did something along the lines of template<typename T> class A { using someName = someClass<T>; } There are some more examples in the actual code but this should illustrate the idea. This worked fine, as long as I only needed someName in class A. But my project has since grown and I have added other templated classes that should use someName as well. My question is: What is the best way to define (several) types as above that depend on some template parameters and use them in multiple other classes (at best without having the write out all of the parameters constantly)? My ideas so far: Of course, I can simply copy using someName = std::someClass<T>; to all the classes using it. But this is not very elegant and both adding classes and adding such types becomes increasingly cumbersome. An alternative would be to write all the usings into a file and let the compiler do the copy & pasting for me via include. But I am not sure whether this would actually work and it seems to be a very brute force approach and in general not good practice. I also tried different approaches involving using but none of them worked so far. Still, it seems to me that this might be the most promising route to the solution. Maybe I am making things way too complicated and there is an easier and more straightforward solution to this.
Create a struct which defines each common alias: template<typename T> struct Aliases { using value_type = T; using reference = T&; }; ...and inherit from it: template<typename T> class Foo: public Aliases<T> {}; template<typename T> class Bar: public Aliases<T> {}; template<typename T> class Baz: public Aliases<T> {}; Some tests: static_assert(std::same_as<Foo<char>::value_type, char>); static_assert(std::same_as<Bar<int>::reference, int&>); static_assert(std::same_as<Baz<int>::reference, int&>);
70,287,726
70,292,336
QStateMachine is not emitting started() signal in release mode
I am using QStateMachine framework for a device controller class. It works fine in debug mode. But, in the release mode QStateMachine::started() signal is not being emitted. A simple widget project for the problem (form is empty) is below. Qt Version 5.14.1 Compiler : MSVC 2017, MinGW (both are 64-bit and results are same) Test.pro QT += core gui widgets CONFIG += c++11 DEFINES += QT_DEPRECATED_WARNINGS SOURCES += main.cpp mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui main.cpp #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QStateMachine> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public slots: void stateMachineStarted(); public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; QStateMachine *stateMachine; }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> void MainWindow::stateMachineStarted() { qDebug() << "MainWindow::stateMachineStarted()"; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { qDebug() << "MainWindow::MainWindow()"; ui->setupUi(this); stateMachine = new QStateMachine; QState *closed = new QState; QState *setup = new QState; QState *opened = new QState; QState *closing = new QState; stateMachine->addState(closed); stateMachine->addState(setup); stateMachine->addState(opened); stateMachine->addState(closing); Q_ASSERT(connect(stateMachine, &QStateMachine::started, this, &MainWindow::stateMachineStarted)); stateMachine->setInitialState(closed); stateMachine->start(); } MainWindow::~MainWindow() { qDebug() << "MainWindow::~MainWindow()"; delete ui; } Application output in debug mode (I closed the form after few seconds.) 12:39:09: Starting C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Debug\debug\Test.exe ... MainWindow::MainWindow() MainWindow::stateMachineStarted() MainWindow::~MainWindow() 12:39:11: C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Debug\debug\Test.exe exited with code 0 Application output in release mode (I closed the form after few seconds.) 12:27:51: Starting C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Release\release\Test.exe ... MainWindow::MainWindow() MainWindow::~MainWindow() 12:27:53: C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Release\release\Test.exe exited with code 0
In release mode, it is likely that the connection is not made because you wrapped it inside a Q_ASSERT macro. See Q_ASSERT release build semantics for more informations.
70,287,876
70,292,244
Why are member variables modifyable even after object is destroyed?
If the shared_ptr is destroyed, what happens to "this" if captured in a lambda to be run on a thread? Shouldn't it have thrown an exception in the below case since the object Test was destroyed before the thread could finish running. #include <iostream> #include <thread> #include <chrono> using namespace std; using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono; // nanoseconds, system_clock, seconds class Test { private: int testInt = 0; public: std::thread TestMethod() { auto functor = [this]() ->void { sleep_until(system_clock::now() + seconds(1)); ++testInt; cout<<testInt<<endl; }; std::thread t1(functor); testInt = 6; return t1; } ~Test() { cout<<"Destroyed\n"; testInt = 2; } }; int main() { cout<<"Create Test\n"; auto testPtr = std::make_shared<Test>(); auto t = testPtr->TestMethod(); testPtr = nullptr; cout<<"Destroy Test\n"; t.join(); return 0; } Output is Create Test Destroyed Destroy Test 3 How is the lambda able to access testInt of a destroyed object ?
In practice, The hardware that executes your program knows nothing about objects or member variables or references or pointers. What was a variable in your C++ source code becomes a virtual memory location in the executable, and what was a reference or a pointer becomes a virtual memory address. When an object is "destroyed" by your program, that means nothing to the machine. The program just stops using that part of virtual memory for that purpose, and if the program continues to run, it quite likely will re-allocate that memory for some other purpose soon after. If your program keeps a dangling reference/pointer to an object that previously was "destroyed," then any access through that pointer/reference will be an access to a memory location that either now is unused, or now is part of some entirely different object from the one that was there before. This typically leads to incorrect behavior of the program (a.k.a., "bugs") that can be especially difficult to diagnose. Shouldn't it have thrown an exception in the below case since the object Test was destroyed? Requiring every program to detect the use of a dangling reference or pointer would have a huge, detrimental impact on the performance of most programs. To fetch the value of some variable through a reference, on most CPU architectures, might be a single machine instruction. Detecting whether the reference was valid could require the program to execute tens or hundreds of instructions. The language standard deems use of a dangling reference or pointer to be undefined behavior. That's their way of saying, you shouldn't do it, but it's your responsibility to ensure that your program doesn't do it.
70,288,446
70,289,317
Keep boost asio io_service
I usually keep one io_service object for the whole application and use a number of threads to call run on them. Creating sockets or timers use the io_service by reference. What happens when all threads finish at application exit and there is, lets say a shutdown or cancel operation called on a tcp socket. The io_service is no longer available. Is there a copy of the io_service when passing that to any asio related classed or is that undefined behavior?
There is never a copy of io_service (or the more recent io_context that replaces the deprecated io_service). That's because it's not copyable. If you don't maintain the lifetime while async operations have not completed, the behaviour is indeed undefined. However, it's not too hard to make sure no async operations/completions happen by stopping the service forcibly gracefully awaiting for it to complete any pending operations. I suggest the latter approach for production quality code.
70,289,221
70,299,077
Ignore 'long' specifier for custom type in c++
I have a type and a template class #ifdef USE_QUAD using hybrid = __float128; #else using hybrid = double; #endif template<typename T> struct Time { int day; long T dayFraction; // This is an example, I need both in here, T and long T; }; And to make things complicated: A nesting class template<typename T> struct State { Time<T> time; std::vector<T> position; } Now I want to use the class in my code as hybrid and double simultaneously, like State<hybrid> stateH; // sometimes precision needed State<double> stateD; // precision never needed and let the preprocessor take care of what hybrid is supposed to be. The code, however, perfectly compiles if hybrid = double, but not so much, if hybrid = __float128, because of the long T dayFraction; in the Time class. Is there a workaround to define an alias like using long __float128 = float128; ? I had a workaround with defining a longHybrid like: #ifdef USE_QUAD using hybrid = __float128; using longHybrid = __float128; #else using hybrid = double; using longHybrid = long double; #endif But forwarding two template parameters would affect a bit of code and feels kind of redundant. I would love to hear any ideas.
You can't actually write long T and expect that to be interpreted as long double when T is double. If it works for you, that's a non-portable quirk of your compiler. If you want "regular" and "long" versions of a type, different for double but the same for float128, one way to do it would be to define a template like this: template <typename T> struct Longer { using type = T; }; template <> struct Longer<double> { using type = long double; }; Instead of long T in struct Time, use typename Longer<T>::type.
70,289,544
70,290,080
Confusion about _Lock_policy in libstdc++
I'm reading the implements of std::shared_ptr of libstdc++, and I noticed that libstdc++ has three locking policies: _S_single, _S_mutex, and _S_atomic (see here), and the lock policy would affect the specialization of class _Sp_counted_base (_M_add_ref and _M_release) Below is the code snippet: _M_release_last_use() noexcept { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_use_count); _M_dispose(); // There must be a memory barrier between dispose() and destroy() // to ensure that the effects of dispose() are observed in the // thread that runs destroy(). // See http://gcc.gnu.org/ml/libstdc++/2005-11/msg00136.html if (_Mutex_base<_Lp>::_S_need_barriers) { __atomic_thread_fence (__ATOMIC_ACQ_REL); } // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count); _M_destroy(); } } template<> inline bool _Sp_counted_base<_S_mutex>:: _M_add_ref_lock_nothrow() noexcept { __gnu_cxx::__scoped_lock sentry(*this); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, 1) == 0) { _M_use_count = 0; return false; } return true; } my questions are: When using the _S_mutex locking policy, the __exchange_and_add_dispatch function may only guarantee atomicity, but may not guarantee that it is fully fenced, am I right? and because of 1, is the purpose of '__atomic_thread_fence (__ATOMIC_ACQ_REL)' to ensure that when thread A invoking _M_dispose, no thread will invoke _M_destory (so that thread A could never access a destroyed member(eg: _M_ptr) inside the function '_M_dispose'? What puzzles me most is that if 1 and 2 are both correct, then why there is no need to add a thread fence before invoking the '_M_dispose'? (because the objects managed by _Sp_counted_base and _Sp_counted_base itself have the same problem when the reference count is dropped to zero)
Some of this is answered in the documentation and at the URL shown in the code you quoted. When using the _S_mutex locking policy, the __exchange_and_add_dispatch function may only guarantee atomicity, but may not guarantee that it is fully fenced, am I right? Yes. and because of 1, is the purpose of '__atomic_thread_fence (__ATOMIC_ACQ_REL)' to ensure that when thread A invoking _M_dispose, no thread will invoke _M_destory (so that thread A could never access a destroyed member(eg: _M_ptr) inside the function '_M_dispose'? No, that can't happen. When _M_release_last_use() starts executing _M_weak_count >= 1, and _M_destroy() function won't be called until after _M_weak_count is decremented, and so _M_ptr remains valid during the _M_dispose() call. If _M_weak_count==2 and another thread is decrementing it at the same time as _M_release_last_use() runs, then there is a race to see which thread decrements first, and so you don't know which thread will run _M_destroy(). But whichever thread it is, _M_dispose() already finished before _M_release_last_use() does its decrement. The reason for the memory barrier is that _M_dispose() invokes the deleter, which runs user-defined code. That code could have arbitrary side effects, touching other objects in the program. The _M_destroy() function uses operator delete or an allocator to release the memory, which could also have arbitrary side effects (if the program has replaced operator delete, or the shared_ptr was constructed with a custom allocator). The memory barrier ensures that the effects of the deleter are synchronized with the effects of the deallocation. The library doesn't know what those effects are, but it doesn't matter, the code still ensures they synchronize. What puzzles me most is that if 1 and 2 are both correct, They are not.
70,290,311
70,290,339
What is the use case for c++20 template lambdas?
We had the generic lambdas before C++20 and could write something like this. auto l = [](auto a, auto b) { return a+b; }; And then C++20 introduced template lambdas where we can write something like this auto l = []<typename T>(T a, T b) { return a+b; }; Or this auto l = []<typename T>(T a, auto b) { return a+b; }; Can someone explain what is the difference? To be more specific, what template lambdas can achieve that was impossible with pre C++20 generic lambdas?
auto l = [](auto a, auto b) This lambda can be called with two completely different parameters. a can be an int, and b can be a std::string. auto l = []<typename T>(T a, T b) This lambda must be called with two parameters that have the same type. T, like in a regular template, can only be a single, specific, type. This is the main difference. Pre-C++20 you can probably achieve mostly the same thing with a static_assert, but this simplifies it.
70,290,457
70,290,487
Accessing elements in a vector of tuples C++
I have the following body of code. #include <iostream> #include <vector> #include <tuple> int main() { std::vector<std::tuple<int, int>> edges(4,{1,2}); for (auto i = std::begin (edges); i != std::end (edges); ++i) { std::cout << std::get<0>(i) << " "<< std::get<1>(i)<< " "; } } In my eyes this makes sense, I have a vector of tuples which I'm initialising. I then iterate through the vector printing each of the two elements of the tuple individually. However the code doesn't work returning 8:26: error: no matching function for call to 'get' std::cout << std::get<0>(i) << " "<< std::get<1>(i)<< " "; ^~~~~~~~~~~ Could someone please explain why?
I would change to a range-based for loop for (auto const& edge : edges) { std::cout << std::get<0>(edge) << " "<< std::get<1>(edge)<< " "; } Otherwise to access each edge, you need to dereference your iterator using * to get the actual tuple itself for (auto iter = std::begin(edges); iter != std::end(edges); ++iter) { std::cout << std::get<0>(*iter) << " "<< std::get<1>(*iter)<< " "; }
70,290,957
70,291,237
std::copy doesn't copy vector in C++
To find all sequences of fixed length which contain only 0 and 1 I use this code: #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; void print_array(vector<string> arr) { cout << '['; int n = arr.size(); for (size_t i = 0; i < n; i++) { cout << arr[i]; if (i < (n - 1)) { cout << ", "; } } cout << ']' << endl; } vector<string> get_variants(int n) { vector<string> result = {"0", "1"}; vector<string> temp; temp.reserve(2); result.reserve(2); for (int i=0; i < (n - 1); ++i) { copy(result.begin(), result.end(), temp.end()); // [1] for (int j=0; j < result.size(); ++j) { temp[j] += "0"; result[j] += "1"; } copy(temp.begin(),temp.end(), result.end()); temp.clear(); } return result; } int main(int argc, char const *argv[]) { int n; cin >> n; vector<string> maybe = get_variants(n); print_array(maybe); return 0; } But vector temp is empty, before copying in line which I marked [1] and after. So, my program's output was [0111, 1111]. What I'm doing wrong?
You are writing to temp.end() and result.end(). These iterators represent "one past the end", and therefore writing to these iterators is Undefined Behavior. You seem to be looking for std::back_inserter. This will create an iterator that will insert a new element to your container when it is written through. std::copy(result.begin(), result.end(), std::back_inserter(temp)); While this answers the posted question, there remain other errors in your code leading to Undefined Behavior.
70,291,281
73,419,766
GetPixel Function Doesn't Work in Qt C++ LNK2019 undefined reference to __imp_GetPixel
I tried to use some win32 function in Qt Application but all of them work except GetPixel function I tried to use MSVC 2019 compiler MSVC Compiler has problems with all the functions (error LNK2019) but when I added win32:LIBS += -luser32 to the .pro file all of them work except GetPixel function, here is my code: #include "mainwindow.h" #include <QApplication> #include <Windows.h> #include <wingdi.h> // For GetPixel int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); POINT p; HDC dc = GetDC(NULL); GetCursorPos(&p); COLORREF color = GetPixel(dc, 0, 0); QString colorRGB = "background-color: rgb(255,0,0);"; w.setStyleSheet(colorRGB); ReleaseDC(NULL, dc); return a.exec(); } I want to use GetPixel function to get red value of a pixel in my browser and set it to background color of Qt Edit: fixed by adding win32:LIBS += -lGdi32 to .pro file
add win32:LIBS += -lGdi32 to .pro file
70,291,690
70,292,255
Why QPainterPath::contains() is not thread-safe, despite being const?
While I understand that QT states that only specifically stated classes are thread-safe, I'd like to understand why a "const" marked method - QPainterPath::contains() - breaks when it is being called in a parallel loop without any concurrent write operation: #include <QPainterPath> #include <omp.h> #include <iostream> int main(int argc, char *argv[]) { QPainterPath path; path.addRect(-50,-50,100,100); #pragma omp parallel for for(int x=0; x<100000; ++x) if(!path.contains(QPoint(0,0))) std::cout << "failed\n"; return 0; } The above code randomly outputs "failed", when it shouldn't. My understanding is that it is changing its internal state somehow, despite the method being "const": https://code.woboq.org/qt5/qtbase/src/gui/painting/qpainterpath.cpp.html#_ZNK12QPainterPath8containsERK7QPointF I need to compare if points are inside the path from multiple threads (in order to speed up processing), but it just does not work with QPainterPath. Even if I create a copy of the object for each thread, QT does Copy On Write and unless I change the derived object (to force it to detach), the result is still the same misbehaviour since it is still using the same shared data. How can I do that in a safe manner without this ugly hack?
The answer is in the first line of code you linked to: if (isEmpty() || !controlPointRect().contains(pt)) controlPointRect() has the following: if (d->dirtyControlBounds) computeControlPointRect(); and computeControlPointRect() does the following: d->dirtyControlBounds = false; ... d->controlBounds = QRectF(minx, miny, maxx - minx, maxy - miny); In other words, if you call controlPointRect() in parallel, the following can occur: Thread T1 sees d->dirtyControlBounds and enters computeControlPointRect() which clears it. It gets to work computing the bounds. Thread T2 enters controlPointRect() and sees that d->dirtyControlBounds is false. It checks whether d->controlBounds (at this point an empty set of points) contains that specific point. It does not, so it returns false. Thread T1 finishes and updates d->controlBounds. All threads from now on are in sync. The obvious fix for this specific instance is to make sure all dirty bits are cleared before you enter a massively parallel computation, but that might not be possible with all objects.
70,291,939
70,292,379
C++ new keyword in inheritance with different types
I recently started learning OOP. Forgive me if this is a noob question. My question is, I have thought new keyword is used with only same datatypes such as: char* p = new char; // OR int* myArr = new int[i] //etc... While studying inheritance and virtual functions I've come across this: #include <iostream> using namespace std; class Human { public: virtual void className() { cout << "Human" << endl; } }; class Asian : public Human { public: void className() { cout << "Asian" << endl; } }; int main() { Human* h1 = new Asian(); h1->className(); } In the main function, we initialize the pointer with the base class and then there is the derived class after new keyword? What do those 2 datatypes represent, how am I supposed to use them?
Note that in your case, the class Human is accessible class of Asian and $11.2/5 states - If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11). [ Note: it follows that members and friends of a class X can implicitly convert an X* to a pointer to a private or protected immediate base class of X. —end note ] According to the above quoted statement, you can convert a pointer to the derived class Asian to a pointer to the base class Human(which means from Asian* to Human*), which is what you did when you wrote: Human* h1 = new Asian(); In the above statement, on the left hand side we have a pointer named h1 of type Human and on the right hand side by using the keyword new we are creating an object of type Asian on the heap. But note that using new has a second effect which is that after the object of type Asian is created on the heap then a pointer to that object is returned. So essentially, on the right hand side we get a pointer to Asian (Asian*). Now as i have already explained(quoted) at the beginning of the answer, you can convert a pointer to Asian to a pointer to Human which is what has happened here. Now when you wrote: h1->className(); There are 3 important facts that you have to consider: className is a virtual function/method h1 is a pointer Asian inherit Human publicly and according to virtual function documentation a virtual function is a member function you may redefine for other derived classes, and can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, even if you call that function with a pointer or reference to a base class of the object. And so the result is that the derive class' function named className is called at run-time and we see Asian printed on the console.
70,292,760
70,293,090
C++ vector insert implementation crash
I'm trying to reproduce the behavior of vector and a weird crash occurs when I try to use vector::insert(iterator, size_type, const T &), my code looks like this: iterator insert(iterator pos, size_type count, const T &value) { return _M_insert_size(pos, count, value); } //with iterator _M_insert_size(iterator pos, size_type count, const T &value) { const size_type size = _size + count; // get the new size if (_capacity < size) reserve(size); // reserve if larger than capacity // here `end()` is still using old size std::copy(pos, end(), pos + count); // move [pos;end()[ to (pos + count) std::fill(pos, pos + count, value); // fill [pos;(pos + count)[ with value _size = size; // set the new size return pos; } //and void reserve(size_type new_cap) { if (new_cap > max_size()) throw std::length_error(std::string("vector::") + __func__); if (new_cap > _capacity) { T *ptr = _allocator.allocate(new_cap); std::copy(begin(), end(), ptr); _allocator.deallocate(_array, _capacity); _capacity = new_cap; _array = ptr; } } //and iterator begin(void) { return _array; } iterator end(void) { return _array + _size; } My code seems legit but I get this crash munmap_chunk(): invalid pointer [1] 3440 abort (core dumped) ./build/test and with valgrind I get an invalid read at std::copy, but I struggled for the past four hours but didn't find which value or parameter was wrong. The crash occured at this test: ft::vector< int > v(10, 42); std::vector< int > r(10, 42); v.insert(v.begin(), 5UL, 1); r.insert(r.begin(), 5UL, 1);
if (_capacity < size) reserve(size); // reserve if larger than capacity // here `end()` is still using old size std::copy(pos, end(), pos + count); // move [pos;end()[ to (pos + count) If you're debugging this, you should know whether you called reserve() here, right? Because you're single-stepping through the function. If you didn't already know this, that's something you should look out for when debugging. If you did, it should have been in the question. And since you're writing your own own std::vector::reserve you know it invalidated all iterators including pos, because your implementation always allocates new storage. If you want to add a debug mode to detect this kind of stuff, you can add a generation counter to the container and to your iterator, and increment the container's generation counter on every invalidating operation. If you get an invalid read in valgrind, it should also tell you where the memory was originally allocated and where it was released. If it didn't, check its options. If it did, that information should also be in the question. So, the proximate fix is to write const auto pos_offset = pos - begin(); before (maybe) calling reserve(), and then use pos_offset to recover the correct iterator. Other issues are: identifiers with a leading underscore followed by an upper-case letter (like _M) are reserved for the implementation. The std::vector provided in your standard library is part of the implementation, but your code is not. _allocator.deallocate does not destroy the array elements, and _allocator.allocate does not construct them. See the use of std::construct_at and std::destroy_n in the std::allocator example code: S* s = allocator.allocate(n); // may throw for (std::size_t i{}; i != n; ++i) { // allocator.construct(&s[i], i+42); // removed in C++20 std::construct_at(&s[i], i+42); // since C++20 } std::destroy_n(s, n); // or loop over allocator.destroy(&s[i]); before C++17 allocator.deallocate(s, n);
70,292,795
70,294,331
How to convert variant to string in C++
I'm new in C++, and I wanted to know how to convert a variant to string: variant<string, int, float> value; if (!value.empty()) { // do something }
Well, you will need custom code for the different cases... The following function would do as you want: string stringify(variant<string, int, float> const& value) { if(int const* pval = std::get_if<int>(&value)) return to_string(*pval); if(float const* pval = std::get_if<float>(&value)) return to_string(*pval); return get<string>(value); }
70,292,905
70,294,473
VS code - Hide build/echo task for cpp
I'm using VS Code for running c++ code. Whenever I Ctrl + Shift + B to build my .cpp file, an 'echo' tab pops up, which makes the entire bottom panel appear and then I am asked to "Terminal will be reused by tasks, press any key to close it." I don't want the tab or the panel to pop up at all and want the entire build process to happen in silence, nothing pops up. This is my tasks.json file { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "echo", "type": "shell", "command": "gcc", "args":[ "main.cpp","-lstdc++","-o" ,"main.exe" ], "group": { "kind": "build", "isDefault": true } } ] }
This can be configured using "presentation": {...}. Following worked for me: { "version": "2.0.0", "tasks": [ { "label": "Test task", "type": "shell", "command": "echo Hello world", "presentation": { "echo": true, "reveal": "never", "showReuseMessage": false, } } ] }
70,293,264
70,293,591
Would it be possible to run the same C++ code simultaneously?
Say I compile some code and make it run. It will take 10 minutes to finish. In the meantime, if I change some parameters in the code and compile it again using a separate terminal window and run it too (so there's now two programs running simultaneously using the same code), does the second run affect the first running program as the first compiled output is replaced by the second compiled output?
There are three possible scenarios: On Windows, an executable file will get locked for writing and removal while it is being executed so the build will just fail. On Linux, an executable file is not necessary protected from modification or removal while it is being executed. 2.1. If a file is deleted from the file system and then a new file is created with the same name then the old file content will still remain until already running executable exits while the new executable will use the new file. So the old executable will continue to run normally while the new one will be ready to work as well. 2.2. If a file is opened for writing and overwritten with new content then the already-running executable will be using the new machine code which is most likely be incompatible with the existing program state and will lead to crashes.
70,293,337
70,293,467
How to #include <whatever.h> installed with apt in Ubuntu
I have just installed hidapi in my Ubuntu 20.04 following the instructions, i.e. by doing sudo apt install libhidapi-dev I wrote my program in the file mwe.cpp which contains only this line: #include <hidapi.h> and now I want to compile it with g++ -o mwe.o mwe.cpp but I get mwe.cpp:1:10: fatal error: hidapi.h: No such file or directory How am I supposed to use this module? Sorry for such a basic question but cannot find out.
On Ubuntu based systems, the system package libhidapi-dev installs the include files to /usr/include/hidapi, so either include this (-I/usr/include/hidapi) in your command line or #include <hidapi/hidapi.h>
70,293,605
70,294,188
Debugging the use of std::string in a thread pool C++
I'm in the process of trying to figure out multithreading - I'm pretty new to it. I'm using a thread_pool type that I found here. For sufficiently large N, the following code segfaults. Could you guys help me understand why and how to fix? #include "thread_pool.hpp" #include <thread> #include <iostream> static std::mutex mtx; void printString(const std::string &s) { std::lock_guard lock(mtx); std::hash<std::thread::id> tid{}; auto id = tid(std::this_thread::get_id()) % 16; std::cout << "thread: " << id << " " << s << std::endl; } TEST(test, t) { thread_pool pool(16); int N = 1000000; std::vector<std::string> v(N); for (int i = 0; i < N; i++) { v[i] = std::to_string(i); } for (auto &s: v) { pool.push_task([&s]() { printString(s); }); } } Here's the thread sanitizer output (note the ===> comments where I direct you to appropriate line"): SEGV on unknown address 0x000117fbdee8 (pc 0x000102fa35b6 bp 0x7e8000186b50 sp 0x7e8000186b30 T257195) 0x102fa35b6 std::basic_string::__get_short_size const string:1514 0x102fa3321 std::basic_string::size const string:970 0x102f939e6 std::operator<<<…> ostream:1056 0x102f9380b printString RoadRunnerMapTests.cpp:37 // ==> this line: void printString(const std::string &s) { 0x102fabbd5 $_0::operator() const RoadRunnerMapTests.cpp:49 // ===> this line: v[i] = std::to_string(i); 0x102fabb3d (test_cxx_api_RoadRunnerMapTests:x86_64+0x10001eb3d) type_traits:3694 0x102fabaad std::__invoke_void_return_wrapper::__call<…> __functional_base:348 0x102faba5d std::__function::__alloc_func::operator() functional:1558 0x102fa9669 std::__function::__func::operator() functional:1732 0x102f9d383 std::__function::__value_func::operator() const functional:1885 0x102f9c055 std::function::operator() const functional:2560 0x102f9bc29 thread_pool::worker thread_pool.hpp:389 // ==> [this](https://github.com/bshoshany/thread-pool/blob/master/thread_pool.hpp#L389) line 0x102fa00bc (test_cxx_api_RoadRunnerMapTests:x86_64+0x1000130bc) type_traits:3635 0x102f9ff1e std::__thread_execute<…> thread:286 0x102f9f005 std::__thread_proxy<…> thread:297 0x1033e9a2c __tsan_thread_start_func 0x7fff204828fb _pthread_start 0x7fff2047e442 thread_start
Destructors are called in the order opposite to variable declaration order. i.e. v will be destructed earlier than pool, therefore at the moment when some threads from pool will call to printString(), the argument string will not be a valid object, because v and its content are already destroyed. To resolve this, I'd recommend to declare v before pool.