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,139,565
70,141,674
c++: error: unrecognized command-line option ‘-target’
Im compiling a program I made using make and I get this error c++: error: unrecognized command-line option ‘-target’ make[3]: *** [libs/system/CMakeFiles/system.dir/build.make:76: libs/system/CMakeFiles/system.dir/src/system/syscalls.cpp.o] Error 1 make[2]: *** [CMakeFiles/Makefile2:504: libs/system/CMakeFiles/system.d...
In my case, c++ was the g++ compiler instead of the clang compiler, if you are having a similar issue try updating g++ or clang++(on older macs you may need to have to use brew to install those) or going in your /usr/bin directory(for mac and linux, I never used windows cant help you) and replacing the files(though onl...
70,140,233
70,143,000
C++ Vector not changing value after being altered in a method
I'm trying to create a class for a node in a directed graph (I don't know much about them so forgive if I've messed up any terms). Whenever I add a pointer to n2 to n1's outNodes vector, I want a pointer to n1 to be added to n2's inNodes vector. I hope that made sense and here is my code. #include <iostream> #include <...
You are providing the methods setInNodes and setOutNodes with copies of the original Node object. The pointer you're pushing into the vector is the address of that copy, not of the original object. To push the address of the original Node object, you need to pass a Node-pointer to the function. Code: ... // Your Node c...
70,140,320
70,140,356
While loop repeats for every word in a string in C++
I am trying to make a magic 8 ball that provides a random preset answer to any input except "bye". Each time the void function magic8ball() is called, it generates a random number from 0 - 19 and prints a corresponding response to the console. int main() { string question; cin >> question; while (question...
std::cin stops reading when it sees whitespace. Space also counts as a whitespace. If you want your string to have space, use std::getline() int main() { string question; std::getline(std::cin, question); while (question != "bye") { magic8ball(); cout << "~Ask another question.\n"; ...
70,140,551
70,140,565
Both variables end up having same value when trying to swap them using references
I'm trying to swap two variables' contents. I did it just fine using pointers. But trying to implement it using references is not working. #include <iostream> //Implementing a reference based swap void RefSwap(int& x, int& y) { int extra; extra = x; //automatically de-referenced x = y; y = extra; } in...
int& ref_a = a, ref_b = b; This is int& ref_a = a; int ref_b = b; Not: int& ref_a = a; int& ref_b = b; Change: int& ref_a = a, ref_b = b; To: int& ref_a = a; int& ref_b = b; will produce the correct result.
70,140,674
70,140,802
Why is a pointer being returned in function?
I am trying to take a file of a 2d array of grades (for example, file "grades2.txt") and store it into a 2d array. I am not sure how pointers work, as I haven't got that far yet, so I am not sure why a pointer is being returned. So far, I have a main function that just plugs in values to the parameters, and I have my r...
Note that you don't necessarily have to use arrays for storing the information(like double values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input...
70,141,439
70,141,540
User-defined object containing pointer breaks when stored in array
When I store a plain int in A and perform a simple get function: #include <iostream> class A { int p; public: void setint(int p_x); int getint(); }; void A::setint(int p_x) {p = p_x;} // set p (type int) int A::getint() {return p;} // get p (type int) int main() { A arr_a[5]; arr_a[0].getint(); }...
In your 2nd case A arr_a[5] just create a array that contains 5 A. but for every A, the pointer is an undefined number (maybe 0x0), so *p is a undefined behavior. You should add A::A() and A::~A() to manage your pointer in your class just like this: #include <iostream> class A { int *p; public: A(); ~A(); ...
70,141,699
70,141,768
Template class initialization in main
class Q { Q(const Q &obj) {} // copy constructor Q& operator= (const Q& a){} // equal op overload } template <class T> class B{ public : T x; B<T>(T t) { // x = t; } } int main() { Q a(2); a.init(1,0); a.init(2,1); B <Q> aa(a); // this line gives error } How to initialize template cl...
To solve the mentioned error just add a default constructor inside class Q as shown below class Q { Q() //default constructor { //some code here if needed } //other members as before }; The default constructor is needed because when your write : B <Q> aa(a); then the template paramter T is dedu...
70,142,090
70,142,235
How to know if compiler is taking advantage of the pch.h.gch file?
Is there a way to check to see if GCC uses the precompiled header or not? Also, I generate pch.h.gch file like this: g++ -std=c++20 -Wall -O3 -flto pch.h -o pch.h.gch But the generated file is always named as pch.h and without the .gch extension. Why is this happening? It used to automatically add the extension. But n...
The question is: How to know if compiler is taking advantage of the pch.h.gch file? With the following source files: ==> f.hpp <== static inline int f() { return 1; } ==> main.cpp <== #include "f.hpp" int main() { return f(); } We can inspect system calls made by gcc to see if it opens the precompiled header: $...
70,142,196
70,142,302
How do you bring all enum constants into scope?
Is there a way to bring all enum constants into scope? I don't mean the type, I mean the constants themselves. struct Foo { enum Bar { A = 1, B = 2, C = 4, D = 8 }; }; int main() { using E = Foo; int v = E::A | E::B | E::C | E::D; // But is it possible to instead do... using Foo::Bar::...
// This already works, of course. using E = Foo; Foo::Bar v = E::A | E::B | E::C | E::D; Well, not really, because E::A | E::B | E::C | E::D is an int and you can't implicitly convert an int to an enum. But that's not stopping you from using c++20's using enum (unless you can't use C++20): struct Foo { enum Bar ...
70,142,451
70,142,498
Overloading << operator for my own class why is this not working?
I have a class and I wanna overload the << operator in it: class Vector3 { int x; int y; int z; public: Vector3(int a, int b, int c) : x{a}, y{b}, z{c} {} Vector3 operator+(const Vector3& v); friend std::ostream& operator<<(std::ostream& ost, const Vector3& v); }; But basically I want t...
A a; B b; a << b; The compiler looks for the member operator<< in A here, i.e. if A::operator(B const&) exists, the code snipped above uses it, but B::operator<<(A&) is not considered. For your code this means the member operator required is std::ostream::operator<<(Vector3 const&) which you cannot add, since std::ost...
70,142,784
70,142,918
How to make sure input into a char isn't too long?
So I'm trying to make sure the user enters only one charcter. Like if the input is "ab", the code will throw an exception. char ch = ' '; std::cin >> ch; // I'm stuck here
You can enter the input into an entire string, and process just the first character: #include <string> #include <iostream> int main() { std::string input; std::cin >> input; char ch = ' '; if ( input.size() > 1 ) { // Entered more than 1 character } else ch = input[0]; }
70,143,030
70,143,422
I want to output 1 4 2 3 5 odd number ascending order and even numbers in descending order
I want to output odd numbers in ascending order and even numbers in descending order my code is here. When I give input n=5 array 5 2 4 3 1, I want to output 1 4 2 3 5, but I got output 4 2 1 3 5. I don't want the position of array. #include <iostream> using namespace std; int main() { int n; cin >> n; int...
We, beginners, should help each other.:) The task is not easy for such beginners as you and me. I can suggest an approach based on the bubble sort method. Here you are. #include <iostream> #include <utility> template <typename UnaryPredicate> void conditional_bubble_sort( int a[], size_t n, ...
70,143,449
70,143,777
Reading a text file in c++ after taking a file name from user
I am just trying to take a file name(example: file.txt) from user and reading it out. But getting some error. Can any body please help me out to perform this task successfully. If their is any other way of doing this please let me know. And please check your solution before answering. ifstream myfile; string myline, fi...
If you have an old compiler then as commented by @πάνταῥεῖ .open() function may have no support for std::string filename, then you can use .open(filename.c_str()) to pass const char *. This correction is present in following code. Also if you have older compiler, still you may solve your issue if you try to specify com...
70,143,471
70,143,526
Why use an initializer list when it initializes nothing?
In this snippet: struct Result { Result() : output1(){}; int output1[100]; } What does Result() : output1(){}; do? I know that : output1() is the initializer list, but why even mention it when it does nothing?
It does something: It zero-initializes output1 instead of leaving it uninitialized. To elaborate, this is called value initialization and is explained in detail here: https://en.cppreference.com/w/cpp/language/value_initialization The effects of value initialization are: if T is a class type with no default construct...
70,143,856
70,144,073
How to convert hex color string to RGB using regex in C++
How to convert the hex color string to RGB using regex? I am using the regex but it is not working. I am not familiar with regex. Is it the correct way? Below is the sample code: int main() { std::string l_strHexValue = "#FF0000"; std::regex pattern("#?([0-9a-fA-F]{2}){3}"); std::smatch match; if (std...
You can use std::regex pattern("#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})"); Here, the FF, 00 and 00 are captured into a separate group. Or, you can use a bit different approach. std::string l_strHexValue = "#FF0000"; std::regex pattern("#([0-9a-fA-F]{6})"); std::smatch match; if (std::regex_match(l_strHexValu...
70,145,190
70,145,449
What all are considered in the Class scope?
Just trying to grab the concept revolving around the scope of the Class in C++. If we take an example something like: #include <iostream> using namespace std; string barValue="OUTSIDE CLASS"; class foo { public: void print_bar() { cout<<barValue<<endl; } }; int main() { foo...
Question 1 Is the barValue variable is in the class scope? barValue is a global variable since you have defined it outside any function and class. Therefore barValue can be used inside the class as you did. Question 2 Can the barValue be accepted even if it is defined in one of the included files? Yes even if barVa...
70,145,202
70,147,883
Avoid reading punctuation from a file in C++
I'm trying to find the longest word on a file in c++. I have the solution for that but the code is also considering the punctuation and I don't know how to avoid this. This is the function "get_the_longest_word()": string get_the_longest_word(const string &file_name){ int max=0; string s,longest_word; ifstream inputFil...
In c++ we have since long a good method to specify patterns of characters, that form a word. The std::regex. It is very easy to use and very versatile. A word, consisting of 1 or many alphanum characters can simply be defined as \w+. Nothing more needed. If you want other patterns, then this is also easy to create. And...
70,146,392
70,146,425
std::function & std::forward with variadic templates
Recently I was reading about variadic templates and based on an example I've seen online I was trying to implement a basic event-system. So far it seems to work fine but I was trying to go a step further and allow N number of arguments to be passed to an event handler function / callback, unfortunately the build error ...
Well, you need to expand it. return std::any_cast<std::function<R(Args...)>>(eventCallback)(std::forward<Args>(args)...); ^^^^^^^
70,146,539
70,146,666
check if map contains a certain value
Hello I am currently facing a problem or maybe I thinking too complicated. I have a map that looks like this: std::map<int,int> mymap; and I insert values doing this std::map<char,int>::iterator it = mymap.begin(); mymap.insert (it, std::pair<int,int>(1,300)); now I want to find out if the map contains the val...
You can use std::find_if to find if a value exists in a std::map or not shown below: #include <iostream> #include <map> #include <string> #include <algorithm> int main() { // Create a map of three strings (that map to integers) std::map<int, int> m { {1, 10}, {2, 15}, {3, 300}, }; int value = 300; ...
70,146,860
70,146,971
glCopyImageSubData gives me GL_INVALID_VALUE
I have made a minimal code example that reproduces a bug in my game. I'm trying to copy a region of a TEXTURE_1D_ARRAY to another one. u32 tex0; glGenTextures(1, &tex0); glBindTexture(GL_TEXTURE_1D_ARRAY, tex0); glTexImage2D(GL_TEXTURE_1D_ARRAY, 0, GL_RGBA8, 64, 2, 0, GL_RGBA, GL_FLOAT, initTexData); glTexParameteri(GL...
You get the INVALID_VALUE error, because the srcHeight argument of glCopyImageSubData exceeds the boundaries of the corresponding image object. The height of an one dimensional texture is always 1. However the depth of an on dimensional texture array can be grater than 1: glCopyImageSubData( tex0, GL_TEXTURE_1D_ARR...
70,146,951
70,173,849
OpenGL: How to fix missing corner pixel in rect (lines or line loop)
Take a look at the bottom-left corner of the green rectangles in the middle: They're missing one pixel at the bottom left. I drew those like this: class Rect: public StaticModel { public: Rect() { constexpr glm::vec2 vertices[] { {-0.5,0.5}, // top left {0.5,0.5}, // ...
OpenGL gives a lot of leeway for how implementations rasterize lines. It requires some desirable properties, but those do not prevent gaps when mixing x-major ('horizontal') and y-major ('vertical') lines. First thing, the "spirit of the spec" is to rasterize half-open lines; i.e. include the first vertex and exclude ...
70,146,977
70,147,073
My C++ program behaves strange with wrong output?
I want to view all solution for: X^12≡1(mod27) So I wrote the following C++ program which outputs only 1 even though 8 and 10 are possible values for x too. Why is that? #include <iostream> #include <cmath> int main() { for (int i = 0; i <= 2700000; ++i) { if (int(pow(i, 12))% 27 == 1) { std::c...
The inbuild pow() function is not capable of handling so large number. Rather we have to use custom function to achieve that. Here it is #include <iostream> #include <cmath> long long binpow(long long a, long long b, long long m) { a %= m; long long res = 1; while (b > 0) { if (b & 1) r...
70,147,043
70,147,192
Creating a vector of all instances of a class when objects are being instantiated in a loop?
I am trying to keep a pointer to all of the instances of a class inside of a static member variable. #include <iostream> #include <vector> class Person { public: static std::vector<Person*> allPeople; int age; Person(int a) { age = a; allPeople.push_back(this); } }; std::vector<Person*> Person::allPeo...
children.push_back(Person(i)); This is what happens here: Person(i) creates a temporary object. Person's constructor saves a pointer to this object in its private allPeople vector. The temporary object gets push_backed into the children vector. This copies/moves this object into the vector. The vector holds a copy ...
70,147,485
70,147,525
How can I create an array of member function pointers coupled with different objects?
Say I have class A with function foo(int i) and class B with function bar(int i), as well as objectA (of class A) and objectB (of class B). I can call the functions like so objectA.foo(10); objectB.bar(20); What I would like to do is have them both as function pointers in an array arr and calling them like so arr[0](1...
You could store std::function objects in a std::vector that you create from lambda functions capturing objectA or objectB. Calling std::function objects comes with a little overhead so if time is critical, you'll have to measure if it's good enough. Example: #include <functional> #include <iostream> #include <vector> ...
70,147,830
70,148,555
C++ Weird File Line Read
I'm new to C++ programming and trying to figure out a weird line read behavior when reading a line from a text file. For this specific program, I have to wait for the user to press enter before reading the next line. If I hard code the file name, the file read starts at line 1 as expected: #include <iostream> #include ...
by default cin operator>> reads data up to the first whitespace characte and whitespace characte is not extracted reference. So if you read file name like this cin>>file; file variable will contains only first part of your string without whitespace. So that when reading you do not have such problems use getline #includ...
70,147,832
70,148,060
My vector elements keep changing themselves after each input
char* name = (char*)malloc(sizeof(char)); char* highscore = (char*)malloc(sizeof(char)); char* password = (char*)malloc(sizeof(char)); player* c = new player(name, highscore, password); int i; int j = 0; int score = 0; vector <player*> players; vector <char*>* names = new vector <char*>;...
The reason you are getting the same values everywhere is because you only allocate your storage memory once, then push the same memory address in to your vectors over and over. Basically, you always have only one object. To fix this, you must allocate new objects inside the loop, like so: vector <player*> players; vect...
70,147,879
70,147,932
Getting incorrect sum while using a recursive function and a do-while loop
I just finished coding a small function for a school project and got the right answer. However, after adding a do-while loop (as it is required), I started running into issues. The first loop works just fine and I get the right answer (i.e., if I input 20 into the function, it outputs 210 which is correct), but if I in...
You could try the following code for sum: int sum(int n) { if (n == 1) { return 1; } else { return n + sum(n - 1); } }
70,148,520
70,148,535
Question regarding polymorphiic functions in C++
I am new to C++ and currently I am studying polymorphism. I have this code: #include <iostream> class Base { public: void say_hello() { std::cout << "I am the base object" << std::endl; } }; class Derived: public Base { public: void say_hello() { ...
For polymorphic behavior you need 2 things: a virtual method overridden in a derived class an access to a derived object via a base class pointer or reference. Base* ptr = new Derived(); Those are bad tutorials. Never use owning raw pointers and explicit new/delete. Use smart pointers instead.
70,148,525
70,149,012
Cpp/C++ Output allingment in one line from right AND left
I need to write ints from the right and strings from the left into a single line and have them line up properly (view output below the code). Basically I just need a way to write a table only using iostream and iomanip and change the allingment from right for ints to left for strings and back. Other tips are also appre...
Using left and right in the same line isn't a problem. It looks like the issue you have is not allowing for space after the first value. It looks like the setw(5) may have been for that, but since there's nothing printed after it there's no effect. I used 7 to match the 15 total used for the string width. Maybe somethi...
70,148,912
70,149,448
User-defined literals
In "User-defined literals" on cppreference.com, what does it mean by this? b) otherwise, the overload set must include either, but not both, a raw literal operator or a numeric literal operator template. If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function ...
unsigned long long operator "" _w(unsigned long long); unsigned operator "" _u(const char*); int main() { 12_w; // calls operator "" _w(12ULL) 12_u; // calls operator "" _u("12") } A little bit changes based on the example in your link. Here 12_w calls operator "" _w(12ULL) since there is a literal operator ...
70,149,108
70,149,155
false expression must have a constant value in visual studio 2022 c++
hello there i was writing a code in a compiler but my compiler had this error :"false expression must have a constant value" in one of the program lines i used other compilers but they didn't say this and i could write my program , but in visual studio 2022 it gives me the error the sample of the program is : stack<c...
Variable-length arrays is not C++ standard, see here. Because str.length() is known at runtime, but the size of the array has to be known at compile-time, this will cause an error. You should use std::vector instead: Replace: char ch[str.length()]; With: std::vector<char> ch(str.length());
70,149,189
70,208,825
vector assign issue in template of c++
I am writing a program to implement queue using vectors. I am using the class as template. And in main function am trying to create both string vector and int vector based on template data type. However am getting compilation error from vector assign method. template <class T> class queueWithArray { private: vector...
Thank you so much VainMan. queryArray.assign(n, T{}); solves the issue. Hi Louis, please find the complete program with include statements here. /* * queueUsingArray.cpp * * Created on: 02-Nov-2021 * Author: Admin */ #include <iostream> #include <ctype.h> #include <bits/stdc++.h> #include <vector> #include ...
70,149,246
70,149,965
I have an error creating a top down shooter C++ project in Unreal, Compilation error
I get an error when trying to create a top-down shooter c++ project in Unreal. I think it might have something to do with paging files but I'm not sure. I have visual studio 2022 community installed for the compiler and use Rider for Unreal Engine as an actual IDE, it's the default. If anybody knows how to fix this, th...
Just too many symbols or template instantiations. Use /Zm to adjust the compiler heap limit and follow other recommendations here: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/fatal-error-c1076?view=msvc-170
70,149,296
70,149,322
How to avoid multiple -l in C++ compiling when using libraries
I really have met lots of problems while using external libraries in c++. The library includes a include file of header files, and a lib file which includes all .la, .so files. I added the library in to usr/local/include and usr/local/lib, and also edited the ld.so.conf file. After all these is done, I supposed that my...
The linker knows which functions you are calling. It does not know which libraries those functions are contained in, and it's not going to go searching through many hundreds or thousands of libraries to find them. With gcc, more so than with Visual C++, the order of the libraries can be important, so they don't even s...
70,149,710
70,149,787
Why is decltype'ing members of the parent class forbidden if it's a template?
Why are members of a base class not available in a derived class if the base is templated in the derived? At compile time all of the types should be instantiated, so I don't see what or why it is different. I can see an argument for this being able to create unresolvable types; but, that feels like a compile time erro...
There is an ISOCPP FAQ for this question. https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members and read the next one too about how it can silently hurt you https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-silent-bug Basically the compiler will not look into templated base classes. The re...
70,149,716
70,149,818
How to directly use vector as parameter in a function?
I know how to initilize a new vector before using it, but how to convenitently use it as paramter in a function? For example, when I init v1, it can get result in the end, but when I use v2, it shows error :cannot use this type name. #include <iostream> #include <algorithm> #include <vector> using namespace std; class ...
The problem you are having has nothing to do with vector. Sol1.add(vector<int> v2{4,5,6}, 8); Here, it seems like you are trying to declare an object name v2 in the middle of this expression, which isn't something you can do in C++. However, you can create a unnamed temporary object in the middle of it like: Sol1.add(...
70,149,907
70,734,278
How to distinguish ADS (Alternate Data Stream) vs Main stream changes with ReadDirectoryChangesW
I'm developing file sync client for Windows. I use ReadDirectoryChangesW API for detecting file events (modifying, remove, create, etc.). But ReadDirectoryChangesW reports NTFS ADS changes same as file modifications. For example, when eml file is created, OS System add ADS on this file. (stream name is OECustomProperty...
There are a number of alternative APIs you might consider. In particular, there's the NTFS Journal, with which you can review and sync based on things that happened since the last time you visited. You'd have to keep the last-read journal identifier...the USN...so you'd know where to start your processing. It's kind of...
70,149,917
70,149,950
no match for 'operator<' (operand types are 'const Vehicle' and 'const Vehicle')
I have this class: class Vehicle { private: char dir_; public: char car_; // functions // // overloaded operators bool operator==(Vehicle&); bool operator<(const Vehicle& v); // // other functions }; which has this implementation: bo...
To make a function usable on a const object, you need to declare that function const: class Vehicle { ⋮ bool operator<(const Vehicle& v) const; ⋮ ^^^^^ ⋮ }; bool Vehicle::operator<(const Vehicle& v) const { ⋮ ^^^^^ }
70,149,947
70,156,298
Why are access specifiers treated differently when expanding template parameters?
Expanding on the question "Why is decltype'ing members of the parent class forbidden if it's a template?". Both Clang and GCC complain that B can't access A::member, because it is protected. But, B can access A::member if a particular instance of B is asked, it's only during the expansion of B<int>::type_name that the ...
They'er not. Use B<T>::member. The trouble comes from, in decltype(member) the compiler imminently notices that member isn't in scope; however, in decltype(A<T>::member) the compiler can't tell that the member is protected until template expansion. Leading to a (mostly) unrelated stack of template expansion informat...
70,150,720
70,158,525
Deduce field width from data type in std::format
I'm experimenting with the new C++ 2020 std::format function. I would like to represent the output with a width deduced from its type. Currently I have this line: std::wstring wstr = std::format( L"{0:#0{1}x}", ::GetLastError(), sizeof( ::GetLastError() ) * 2 ); This results in the value L"0x000002". Is # supposed to...
Is # supposed to count the 0x as part of the width? (If I remove it, I get 8 nibbles as expected) Yes. There is an example in [format.string.std]/13 which illustrates this. The whole string is 6 characters, including the 0x: string s2 = format("{:#06x}", 0xa); // value of s2 is "0x000a" This is similar to what...
70,151,000
70,151,415
Data type sizes in C++ and VB.NET
I am working on developing an application in VB.NET which uses a third party DLL for which the documentation is for C++. For the data type conversions, I was using two pages: https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/ ...
Check this: https://learn.microsoft.com/en-gb/cpp/cpp/data-type-ranges?view=msvc-170 Long is 4 bytes. The vb.net page is correct, the C++ one is not.
70,151,455
70,195,744
How to get more debug info for C++ std::ofstream writing to device?
Good day, I am trying to debug this C++ code which interacts with XDMA device: #include <fstream> #include <iostream> #include <unistd.h> int main() { std::ofstream output_; const char* output_name = "/dev/xdma/card0/h2c0"; output_.exceptions(std::ios::failbit | std::ios::badbit); output_.rdbuf()->pub...
Although I didn't succeed in getting more debug info, the solution was to downgrade the XDMA driver, which provides /dev/xdma/card0/h2c0 device, from v2017.1.47 to the older v2017.0.45 version (which needed a custom patch to work on new OS). Unfortunately these new drivers are really buggy...
70,151,546
70,169,736
exe file is not running in Release folder
My project IDE: Visual Studio 2019, Qt 5.15.0. I'm trying to launch the application by the project_name.exe file of the release build, but nothing happens. The project_name.exe file of Debug mode is running well. The project is running well also in IDE in both Debug and Release modes. I added Qt Bin directory to the PA...
The following steps finally solved my problem: Copy the qml folder from the project directory into Release folder (it has to be near the exe file). In Release folder launch Command prompt and write: windeployqt project_name.exe, this step must come after having qml files for getting the whole needed deployment files b...
70,151,957
70,152,012
What is the purpose of "int[]" here: "std::void_t<int[static_cast<Int>(-1) < static_cast<Int>(0)]>;"
This is from an example from a tutorial on std::enable_if. Here is more context: // handle signed types template<typename Int> auto incr1(Int& target, Int amount) -> std::void_t<int[static_cast<Int>(-1) < static_cast<Int>(0)]>; From Shouldn't std::void_t be accepting a type as template argument? What is the purpose o...
If static_cast<Int>(-1) < static_cast<Int>(0) yields true, int[static_cast<Int>(-1) < static_cast<Int>(0)] leads to int[1] (true could be converted to int (and then std::size_t) implicitly with value 1), which is an array type. If static_cast<Int>(-1) < static_cast<Int>(0) yields false, int[static_cast<Int>(-1) < stati...
70,151,963
70,152,209
The question is about printing digits of two digit number n, I'm encountering a runtime error
Given a two-digit number n, print both the digits of the number. Input Format: The first line indicating the number of test cases T. Next T lines will each contain a single number ni. Output Format: T lines each containing two digits of the number ni separated by space. Constraints 1 <= T <= 100000 10 <= ni <= 99 Error...
Fist, you declare t, but do not initialize it, so it is uninitialized. Trying to use the value leads to undefined behavior. Second, VLA is not valid C++, see here. You have to use std::vector instead. Third, you don't need to use an int. So, you should do: #include <iostream> #include <vector> #include <string> int mai...
70,152,329
70,153,113
Thread separated random int generation in C++
I need to genetate three .txt files filled with random int, calling the generate function in sepatared threads. The problem is that as a result I have the same values in every .txt files. A function that gererates and writes values: void generateMoves(int limit, std::string outputPath) { //open fstream...
As the comments state, all your generators have been created from the same default seed. It suffices to give each generator a different seed: std::random_device rd1; static thread_local std::mt19937 generator(rd1()); This uses the (very slow) std::random_device, but only to generate a unique seed for the mt generator....
70,152,360
70,152,792
Is there a fast way to get the index of bit which equal 1 in a binary value?
I want to get the index which equals to 1 in binary format, now I use codes like this: inline static uint8_t the_index(uint32_t val){ return uint8_t(log(val & ((~val) + 1))/log(2)); } I want to know if there are other ways to achieve the same target? Is there any possible to use bit operation to solve this problem?...
There is a standard function for this: auto cur_index = std::countr_zero(temp); On my system, this compiled down to: xor eax, eax tzcnt eax, edi Note that this function successfully counts the zero bits from right until first one bit whether the input has exactly one set bit or not.
70,152,364
70,152,403
Why do designated initializers zero-initialize the data members?
Below is from cppref of Designated initializers: struct A { int x; int y; int z; }; A b{.x = 1, .z = 2}; // ok, b.y initialized to 0 By default, all fundamental types are default-initialized rather than zero-initialized in C++. Why do designated initializers zero-initialize the data members?
b.y will be initialized from an empty initializer list, as the effect, zero-initialized to 0. For a non-union aggregate, elements for which a designated initializer is not provided are initialized the same as described above for when the number of initializer clauses is less than the number of members (default member ...
70,152,465
70,152,532
Unexpected behavior concatenating string
I am trying to concatenate two strings in C++11 and I am often getting an unexpected behavior. First, I have a function that converts any type to string : template <class T> static inline const char * toStr(T arg) { stringstream ss; ss << arg; return (ss.str()).c_str(); } Then, I use this function like thi...
Here return (ss.str()).c_str(); You are returning a pointer to the buffer of a temporary std::string (returned from str()). The pointer returned from the function is useless for the caller, because the std::string it points to is already gone. A pointer is just a pointer. If you want a string, return a std::string. If...
70,152,931
70,153,001
How to set a string to an optional string value?
Due to some constraint in the program(C++), I have a case where I am assigning an optional string to a string variable, which give the following error: error: no match for ‘operator=’ ... The piece of code is something like: void blah(std::experimental::optional<std::string> foo, // more parameters) { std::string b...
You have several ways: /*const*/std::string bar = foo.value_or("some default value"); std::string bar; if (foo) { bar = *foo; } std::string bar; if (foo) { bar = foo.value(); }
70,153,546
70,154,006
Variable not set inside __attribute__((constructor)) or global static variable reset after __attribute__((constructor)) invoked
I have a std::vector which need to filled with some random values when library is loaded. but I see it is been reset after library is loaded. Is it because of global and static Library code: static std::vector<uint8_t> g_randomNr{}; __attribute__((constructor)) void generateRandomNrAtStart(void) { static bool fir...
Another option is to control the order of the vector initialization and constructor call with priorities: __attribute__((init_priority(101))) static std::vector<uint8_t> g_randomNr{}; __attribute__((constructor(102))) void generateRandomNrAtStart() { ... } Live demo: https://godbolt.org/z/bh9zj9cE3 Possibly OT to the...
70,154,749
70,154,870
I can't access to the protected member of my base class
I am new at programming using c++ and having some troubles creating my constructors & objects. How can I access to my protected members like int p_iID in the Fahrzeug class? I have to access them for both of my objects seperately. I would be so happy if you could help me out with this. class Fahrzeug { private: pr...
void vAusgeben(PKW pkw1, PKW pkw2) { You probably don't want to pass your PKW objects by value (or expect object slicing). Pass const references instead: void vAusgeben(const PKW& pkw1, const PKW& pkw2) { Also, why are you shadowing your 2 parameters with these local variables? PKW pkw1; // ??? PKW pkw2; // ???
70,155,129
70,156,087
Vector of structs containing allocation pointers is failing to destruct
In my project I use a class for paged memory allocation. This class uses a struct to store all of its allocations: enum PageStatus : uint_fast8_t { //!< possible use stati of an allocated page PAGE_STATUS_INVALID = 0b00, PAGE_STATUS_FREE = 0b01, //!< the page is free PAGE_STATUS_USED = ...
std::shared_ptr<char[]> pData and its aliasing constructor (8) might help. (that might even allow to get rid of PageStatus). It would look something like: constexpr std::size_t page_size = 6; struct PhysicalPage { std::shared_ptr<char[]> pData; }; int main() { std::vector<PhysicalPage> pages; { st...
70,155,168
70,155,250
Why my code is giving Time Limit Exceeded?
Today while solving a question on leetcode, I applied dfs on a directed graph which runs on O(N) time, but my code is giving TLE, so after trying too many time I checked on comments and there was a accepted code which also runs on O(N). So now I am confused as why my code is not getting accepted and giving time limit e...
In your dfs() function, you pass inform by value, which means the compiler makes a copy of inform every time you call the function, not the inform itself. You should pass by reference instead. void dfs(int head, int time, vector<int> &inform)
70,155,255
70,155,661
Print method for variadic template pairs in C++
I want to achieve something like: export_vars("path/to/file.dat", {"variable_name", obj}, {"another_variable", 2}); where obj can be any type as long as it has an << overload - the idea is to write to an ofstream later on. I have tried (for an initializer_list of pairs): void export_vars(const std::string& path, std::...
{..} has no type, and so disallows most deduction. Several work arounds: Change call to use std::pair explicitly: template <typename ... Pairs> void export_vars(const std::string&, const Pairs&... args) { ((std::cout << args.first << ": " << args.second << std::endl), ...); } int main() { export_vars("...
70,155,379
70,155,448
Template argument deduction fails on C++14
I was trying to compile this code but it fails on C++14 while it works on C++17 #include <cstdio> #include <utility> template <typename F> struct S { explicit S(F&& fn): fn(std::move(fn)) {} F fn; ~S() { fn(); } }; int main(){ S obj([]() noexcept { std::printf("Foo\n"); }); ...
Class template argument deduction (CTAD) was only introduced in C++17 . You can deduce the argument with a function: template <typename F> S<F> make_S(F&& fn) { return S<F>{std::forward<F>(fn)}; } int main(){ auto obj = make_S([]() noexcept { std::printf("Foo\n"); }); }
70,155,743
70,158,391
How to use Vec2w in Opencv Python
I have this part of code working in C++ Mat mapFrame5(Size(321,262), CV_16UC2); for (int y = 0; y < mapFrame5.rows; y++) { for (int x = 0; x < mapFrame5.cols; x++) { mapFrame5.at<Vec2w>(y, x) = Vec2w(y, x); cout<<mapFrame5.at<Vec2w>(y,x); } } I have a hard time finding if there is equivalent of...
The naive approach would be to just transcribe the algorithm to Python: def gen_grid_1(rows, cols): result = np.zeros((rows, cols, 2), np.uint16) for r in range(rows): for c in range(cols): result[r,c,:] = [r, c] return result Example output for 3 rows and 5 columns: [[[0 0] [0 1] [...
70,156,026
70,156,680
C++ Template method return ref to private map value where value's type is parent of T
I have a problem blowing my mind actually, and a challenge for someone, could you help me with that ? : class UItemEntity : public UObject { GENERATE_BODY() public: template<typename T=FItemComponent> T& GetComponent() { auto Result = Components[TYPE_ID(T)]; T Comp = reinterpret_cast<T...
There may be some Unreal-specific shenanigans at play that I'm not aware of, but in general-purpose C++ code, it would look like this: class UItemEntity : public UObject { GENERATE_BODY() public: template<typename T> T& GetComponent() { static_assert(std::is_base_of_v<FItemComponent, T>); ...
70,156,721
70,156,767
Can C++ deduce argument type from default value?
I tried to write this function with a default template argument: template<typename A, typename B> void func(int i1, int i2, A a, B b = 123){ ... } In my mind I can call it like this: func(1, 2, 3) and compiler should deduce type B as int from default value, but I get no instance of overloaded function. Is it incor...
The type of a template parameter in a function can't be deduced from a default argument. As shown in the example on cppreference.com: Type template parameter cannot be deduced from the type of a function default argument: template<typename T> void f(T = 5, T = 7); void g() { f(1); // OK: calls f<int>(1, 7) ...
70,156,751
70,158,665
counting number of elements less than X in a BST
I had implemented a BST for a multiset using the C++ code below, whereas each node contains the number of occurrence num of each distinct number data, and I try to find the number of elements less than certain value x, using the order function below. It works, however, inefficient in terms of execution time. Is there a...
You can bring the algorithm down to O(logN) time by storing in each node the number of elements in the subtree of which it is the root. Then you'd only have to recurse on one of the two children of each node (go left if x < node->data, right if x > node->data), which if the tree is balanced only takes logarithmic time....
70,156,844
70,156,983
Cpp/ C++ unique Pointer on objects access functions of that class
How do I access functions via a unique pointer pointing on an object of that class struct foo { foo(int); void getY(); }; int main() { foo f1(1); f1.getY(); std::unique_ptr<foo> ptr1 = make_unique<foo>(2); *ptr1.getY(); // Error }; foo has a constructor with an int as argument,getY() just prin...
The problem is that due to operator precedence when you wrote *ptr1.getY();, it was equivalent to writing: *(ptr1.getY()); So this means you're trying to call a member function named getY on the smart pointer ptr1 but since ptr1 has no member function called getY you get the error. To solve this you should write: ( *...
70,156,906
70,157,082
Is there a way to get the index of an array struct in its function without parameters?
As the title says and without any additional parameters in Request() while keeping it clean. Below is an example: struct CPerson { void Request(); } void CPerson::Request() { // get index /* EXAMPLES serverinfo* info; server.GetInfo(&info, index); cout << info.username << "\n"; */ } ...
In this specific case, as long as you can guarantee that CPerson is only ever stored in this array, you can use std::distance() to get the index, since this happens to be a valid iterator into the array. It's effectively the same thing as just doing this - person, but standard library implementations can (and often do)...
70,157,208
70,157,232
Why PyCallable_Check() returns 0 on global class instances?
Rigth now I'm working on embedding python into a larger C++ application. Despite I'm not a python specialist, I understand that with the builtin PyCallable_Check() I can check if a python object is actually callable. From What is a "callable"? I found that it depends on an available __call__ method within classes or on...
That's not a callable. You may be misunderstanding what "callable" means. If globalObj were callable, you would be able to do globalObj(), perhaps with some appropriate arguments between the parentheses. You can't.
70,157,682
70,157,737
How to pass a C++ Template instance to a function?
How can I pass any object of an templated class to another function in C++11? In the snippet below passInObj does not compile because it complains about Printer&. I want to pass in any Printer it does not matter which template T I have used. How can I do this and why does the solution below not work? #include <iostream...
How can I do this You need to make it into a function template: template <class T> void passInObj(const Printer<T>& p) { p.print(); } Demo and why does the solution below not work? Because Printer is not a type, it's only a template. For passInObj to work with any Printer<T>, you need to make the function into...
70,157,934
70,158,133
Pass in unique pointer for inherited class to constructor with unique pointer for base class?
Is it possible to do the following: I have an inherited class B from base class A. I want to create a constructor for a method that takes in a unique pointer to class A but still accept unique pointers to class B, similar to pointer polymorphism. void Validate(unique_ptr<A> obj) {obj->execute();} ... unique_ptr<B> obj...
Your issue doesn't really have anything to do with polymorphism, but rather how unique_ptr<> works in general. void Validate(unique_ptr<A> obj) means that the function will take ownership of the passed object. So, assuming that this is what the function is meant to do, you need to handoff said ownership as you call it....
70,158,738
70,163,046
Creating a QListIterator over a temporary object?
Currently I'm doing some code reviews and stumbled on the following construct: QVariantMap argumentMap = QJsonDocument::fromJson(" ... JSON-String ... ", &error).toVariant().toMap(); ... QListIterator<QVariant> keyIterator( argumentMap["key"].toList() ); while ( keyIterator.hasNext() ) ... My first feeling was that ...
The QListIterator should be fine, since it takes a copy of the list. What you are referring to by the lifetime extension of temporaries is this: { auto const & myRef = foo.bar(); // returns by value so it returns a temporary // you would expect the temporary to be gone now // and myRef thus being a dangling reference,...
70,159,251
70,176,499
Jinja2cpp valueMap param multiple items 'no matching function for call' error
I have build jinja2cpp from code. compiled libraries and everything. int main() { string source = R"( My name is {{myName}} )"; jinja2::Template tpl; jinja2::ValuesMap params {{"myName", "Mehmet"}}; tpl.Load(source); string result = tpl.RenderAsString(params).value(); cout << result; ...
This works: jinja2::ValuesMap params {{"users", jinja2::ValuesList({"John", "Joe"})}};
70,159,423
70,159,654
forward with remove_reference in template function parameter type
This page states the following: Given that we have the following factory template function: template<typename T, typename Arg> shared_ptr<T> factory(Arg&& arg) { return shared_ptr<T>(new T(forward<Arg>(arg))); } One can choose among any of the two forward implementations: forward implementation using remove_refe...
Why does using remove_reference forces us to specify Arg as the template arg Because having a nested type remove_reference<S>::type as an argument makes a non-deducible context. This applies for any nested type. For example, if you have template< class T> struct Identity { using type = T; }; template< class T> v...
70,159,945
70,160,181
[C++][ QT ] is not meant to be copied. Pass it by move instead
I am a beginner in C++. And I don't understand this error. I just need you to explain me. I try to show a .sqlite database in a QTableview. The problem come from: model->setQuery(*qry); I want to use a function called setQuery but in first argument, I set an object with *QSqlQuery type. And this error show up. ERROR P...
They want you to move the object behind qry into the function. The shortest change would be to replace model->setQuery(*qry); with model->setQuery(std::move(*qry)); delete qry; You don't need to use new/delete in this case though. Just using automatic storage duration works: QSqlQuery qry(DB); qry.prepare("SE...
70,160,138
70,161,667
Unresolved External Symbol LNK2019 CMake
I have here a class called engine and im trying to use, but when i include it i get LNK2019 error. Im running Visual Studio 2019 x86_64 compiler. Any ideas what could be wrong? I have constructor and destructor defined in cpp file. #pragma once namespace NRD { const int SCREEN_WIDTH(1280); const int SCREEN_HE...
I'm kinda guessing since your question is kinda hard to answer since it could be a lot of things. But here is my inference. It's not recommended to glob your source files like you are doing here. file(GLOB_RECURSE SOURCE_FILES ${CMAKE_SOURCE_DIR}/src/*.c ${CMAKE_SOURCE_DIR}/src/*.cpp) NOTE: My suggestion req...
70,160,171
70,160,325
Read binary data from PLY file using Qt
Im trying to read data from this file: Which contains both ascii text and float numbers stored in binary. I'm trying to read it by doing the following: QTextStream in(file); QString line; line = in.readLine(); while (!line.startsWith(QString("element vertex"))) { line = in....
The default byte order for QDataStream is big endian; change it to little endian: stream->setByteOrder(QDataStream::LittleEndian)
70,161,258
70,161,302
Width and setfill('-') in cpp
I am new to C++ and am wondering if there is a more elegant way to print out the following: Celsius Kelvin Fahrenheit Reaumur ------------------------------------- I guess you could just do cout << "Celsius Kelvin Fahrenheit Reaumur" << endl << "-------------------------------------"; But it doesn't look good. ...
Here are two other ways to produce this line: std::cout << "-------------------------------------\n"; std::setfill + std::setw: #include <iomanip> std::cout << std::setfill('-') << std::setw(38) << '\n'; Using a std::string: #include <string> std::cout << std::string(37, '-') << '\n'; Demo
70,161,402
70,161,839
Multilingual C++ program
How can I add multilanguage support to a C++ program? I want to let the user to choose between 2 languages when opening the app. What's the simplest way without any external libraries?
Replying to my comment, "You could make a dictionary where it's key is an enum representing a word, then the values could be an array of structures containing the language and actual string in that language. Example: (pseudo code) dictionary: - WORD1_ENUM => structure[LANGUAGE1_ENUM, WORD_IN_LANGUAGE1], structure[LANGU...
70,161,555
70,161,666
How properly use SetMenuItemBitmaps to replace the default bitmap on a menu item?
I'm trying to change the default bitmap on a menu item. Unfortunately, I'm not getting it to work. The documentation of SetMenuItemBitmaps() states that I should use the GetSystemMetrics() function with the SM_CXMENUCHECK and SM_CYMENUCHECK values to retrieve the default bitmap dimensions. I adjusted the .bmp file to t...
You need the HMENU handle of the menu that the red item directly belongs to. You are using the top-level HMENU, but red is a child item of the sub-menu of the color item, which is a child item of the sub-menu of the Menu item, which is a child item of the top-level menu. Once you have the top-level HMENU, use GetSubMe...
70,161,557
70,162,881
Bubble sort in double linked list
void sortTrain(TrainCar* head, bool ascending) { TrainCar* current = head; int count = 1; int size = (getlength(head)); if (ascending == 1) { for(int i = 0; i < size-1; i++) { while(current->next) { if((current->load) > ((current->next)->load))...
The main error in the code you posted is that you are not resetting current and count after each iteration of the outer loop, i.e. try the following: // ... if (ascending == 1) { for (int i = 0; i < size-1; i++) { TrainCar* current = head; int count = 0; while (current->next) { ...
70,161,571
70,161,766
Calculating color histogram of framebuffer inside compute shader
As the title suggests, I am rendering a scene onto a framebuffer and I am trying to extract the color histogram from that framebuffer inside a compute shader. I am totally new to using compute shaders and the lack of tutorials/examples/keywords has overwhelmed me. In particular, I am struggling to properly set up the i...
As for your questions: can't apply layout(r16ui) to image type "image2D" r16ui can only be applied to unsigned image types, thus you should use uimage2D. unable to find compatible overloaded function ... The spec explicitly says that atomic operations can only by applied to 32-bit types (r32i, r32ui, or r32f). Thus...
70,161,858
70,161,920
string_view Vs const char* performance
Is a std::string_view parameter better than a const char* one in the code below? void func( const std::string_view str ) { std::istringstream iss( str.data( ) ); // str is passed to the ctor of istringstream std::size_t pos { }; int num { std::stoi( str.data( ), &pos, 10 ) }; // and here it's passed to st...
But I pass them a std::string_view object using its data() member function. Is this bad practice Yes, this is a bad practice. It's bad primarily because a string view doesn't necessarily point to a string that is null terminated. In case it doesn't, passing data() into a function that requires null termination will r...
70,162,888
70,162,958
unexpected behavior with template function overloading
So i have the following snippet which compiles correctly: template<typename _Tp, typename _Up = _Tp&&> _Up __declval(long); //template<typename _Tp> // _Tp // __declval(char); template<typename _Tp> auto declval() noexcept -> decltype(__declval<_Tp>(0)); int main() { declval<int>; return 0; } and i h...
You are running into effectively the same problem as the following, simpler and equally broken, program: void foo(long) {} void foo(char) {} int main() { foo(0); } The error is a lot clearer here though: :5:5: error: call to 'foo' is ambiguous The issue is that 0, being an int, is equally valid as a char as it ...
70,163,517
70,165,479
Integrating a 2D Array into a Calendar Printing Program
I've decided to start learning to code on my own from a C++ textbook and one of the challenges is to create a program that prints the calendar of a given year, in this style for each month: -------------January------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 ...
I declared a global variable int yearly[12][2]; snippet line 90: for (int i = 0; i < 12; i++) { days = numberOfDays(i, year); yearly[i][0] = i; //month yearly[i][1] = days;//days ... ... The for loop is executed 12 times, and each i corresponds to a month. Yearly [i][0] is the month...
70,163,538
70,164,024
Does accessing two different members of the same object need synchronization?
If we have an object with two data members A, and B; Do we need any form of synchronization while accessing the two members from two different threads running in parallel? How about if the object was a global variable, versus the object was a heap object, accessed with a pointer to its address? Edit: Each thread reads ...
The keywords you are looking for is memory model. Non-bitfield members are distinct memory locations; there is no race condition from reading/writing different members. A write in one thread and access in another of the same memory location is a potential conflict. Unless certain requirements are upheld (like happens ...
70,163,749
70,163,783
How to add a period at the end of the sequence in stead of a comma?
This is my code: #include <iostream> using namespace std; int main() { int fib[10]; fib[0] = 0; fib[1] = 1; for (int i = 2; i < 10; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } for (int i = 0; i < 10; i++) { cout << fib[i] << ", "; } return 0; } And this is the outp...
Change the print for loop to: for (int i = 0; i < 10; i++) { cout << fib[i] << (i < (10 - 1) ? ", " : "."); }
70,163,753
70,164,476
erase rows and colums of a 2D vector, when a condition is achieved in another single vector?
I have a matrix (vector of vector), in other words, 2D vector (6 X 6) elements <double>, and after I have a vector with 6 elements <int>. the vector with ints has only "0" and "1". Then, I am looking for a way to remove a row and column of the 2D vector when a "0" is found in the vector (1D) of ints. This time is only ...
You can create a new matrix after you've removed the rows. std::vector<std::vector<double>> removeColumns(const std::vector<int>& boundaryConditions, const std::vector<std::vector<double>>& matrix) { std::vector<std::vector<double>> returnValue(matrix.size()); siz...
70,163,859
70,164,010
Declaring an object as extern
I am trying to declare an object as extern because I want a thread to be able to access and update it from a different file. But I get the following error message when I try to compile my code: In file included from main.cpp:1: dialog.h:43:6: error: storage class specified for ‘temperatureValue’ 43 | extern QL...
extern a class member is not allowed, If we can do that, for instances of a class type, compiler don't know which address to resolve while linking. you can do like this: //A.h #ifndef _A_H_ #define _A_H_ struct A{ int value; }; extern A a; #endif //A.cpp #include "A.h" A a; //main.cpp #include <iostream> #i...
70,164,128
70,164,223
array + n shifting in c++ memory behavior
I am going through a cpp course and the instructor used the following notation to get a subarray of the current array void f(int arr[], int len) { if (len == 0) return; f(arr + 1, len - 1); // arr + 1 takes a subarray ... } I wanted to understand how the arr+1 notation works with regards to memory...
array is pass by pointer when you call in function see this
70,164,289
70,165,446
Is there a way to detect when a key is pressed only once? (not held down)
I have been looking for ways to detect when a key has been pressed but only once, but the only things I can find are GetAsyncKeyState and GetKeyState. I am making a rhythm game for fun and I use a while(true) statement to get everything done. Is there anyway to detect when a key is pressed once? (I'm also using GLFW if...
You could store the state of the previous key presses, if it was not pressed in the last frame and is now, that would mean that the key is held down. Here's an example with the LMB: bool previousMouseState = false; if (GetKeyState(VK_LBUTTON) < 0) { if (!prevMouseState) { previousMouseState = true; //Mouse cl...
70,164,618
70,170,879
C++ typed variables using struct
In C++ I want to create a typed variable that won't accidentally be used or converted to some other type. What I've come up with is: struct DId { uint32_t v; DId (uint32_t i = 0) { v = i; } }; struct TId { uint32_t v; TId (uint32_t i = 0) { ...
You may make the structure templated so that it can be used at multiple places and define a typecast operator. template<typename T> struct Id { T v; Id (T i = T{}) { v = i; }. // Ideally not required operator T () { return v; } // optional to allow conversion to T }; using DId = Id<uint32_t>; Your code as it ...
70,164,978
70,165,070
No naming conflict from two functions in global namespace (C++)?
I created two files, Linkage.cpp and External.cpp. Linkage.cpp: #include <iostream> void Log(int x = 5) { std::cout << x << "\n"; } int main() { Log(); return 0; } External.cpp: #include <iostream> void Log(const char* message) { std::cout << message << "\n"; } Why am I not getting a linker error? ...
Why am I not getting a linker error? When you wrote void Log(int x = 5)//this means that the function named Log can be called without passing //any argument because you have provided a default argument which will be //used in case you don't provide/pass any argument { //..other...
70,165,120
70,165,158
Does a mutex lock itself, or the memory positions in question?
Let's say we've got a global variable, and a global non-member function. int GlobalVariable = 0; void GlobalFunction(); and we have std::mutex MutexObject; then inside one of the threads, we have this block of code: { std::lock_guard<std::mutex> lock(MutexObject); GlobalVairable++; GlobalFunction() } now, inside ano...
It’s the former. There’s no relationship between the mutex and the objects you’re protecting with the mutex. (In general, it's not possible for the compiler to deduce exactly which objects a given block of code will modify.) The magic behind the mutex comes entirely from the temporal ordering guarantees it makes: that ...
70,165,418
70,174,424
Nested call of consteval functions with a reference argument
The following program template<class T> consteval auto foo(const T&) { return 0; } template<class T> consteval auto bar(const T& t) { auto n = foo(t); return n; } int main() { static_assert(foo("abc") == 0); static_assert(bar("abc") == 0); } is built fine in GCC, but Clang rejects it with the messages...
This is a clang bug. gcc and msvc are correct to accept it. There are two relevant rules in question: All immediate invocations must be constant expressions. This comes from [expr.const]/13: An expression or conversion is in an immediate function context if it is potentially evaluated and either: its innermost enclos...
70,165,937
70,174,335
How to get function return values into ROS topic msg to be published
I'm a beginner when it comes to working with ROS. Currently working in Melodic, outside of the catkin workspace. ie: not using catkin My goal is to create a topic that contains an x and y value, then to update those values from the return value of my path prediction function, which returns a std::vector<Eigen::Vector2f...
The best, and only, way to handle this conversion is to do it manually. A Point message has fields for (x,y,z) so you'll need to simply assign those values yourself. Another thing to note is that a Point msg doesn't have a .data field like std_msgs do. geometry_msgs::Point msg; std::vector<Eigen::Vector2f> tmp_vec = en...
70,166,420
70,166,590
Writing a video with H.264 in OpenCV with High profile from a high profile mp4 file
I have High profile mp4 video i am using opencv to overlay some text inside but output.mp4 is writing in simple profile format. is there a way to write it in high profile I am using opencv 3.4.16 latest Devlopment platform is: Windows C++ VS2019 VideoWriter videocc(destFile, VideoWriter::fourcc('M', 'P', '4', 'V'), fp...
You would need to pass parameters through OpenCV, to ffmpeg and libx264. As far as I can tell from official documentation, OpenCV doesn't support that. However, the source contains access to the environment variable OPENCV_FFMPEG_WRITER_OPTIONS You should be able to pass parameters like you would give them to ffmpeg, e...
70,166,715
70,166,958
Why casting of function pointers not working as it is for the primitive types?
int* b = new int(40); int c = *(int *)b; The above cast is working fine. But similar casting is not working for function pointers void abc(int a){ cout<<a<<endl; } std::function<void(int)> callback = *(std::function<void(int)>*)abc; // this cast is not working What is wrong in the above piece of code?
You cast b to the same type that it already has. This results in a static cast, which doesn't change the value. The type of b is int* and you cast to int*. You cast abc to an entirely different type. And since the target type is unrelated, this resulst in a reinterpret cast, and accessing the pointed object through the...
70,166,739
70,167,497
Confustion about Android NDK libc++ libc++_shared, libstdc++
I am getting very confused trying to build a simple C++ library using Android NDK 23 (23.1.7779620). I am using CMake and this is a very simple program: # CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(mf) add_library(mf lib.cpp) // lib.hpp #pragma once #include <string> std::string foo(std::string); //...
By passing -DANDROID_STL=c++_shared to the CMake invocation you explicitly asked for the shared runtime as opposed to the default runtime. As explained in the documentation, the rules are simple: if all your native code is in a single library, use the static libc++ (the default) such that unused code can be removed an...
70,167,025
70,167,171
Integer overflow and underflow in C++
Can anyone please explain why this happens ?? : int a = 2147483647; cout <<"Product = " << a * a << endl; // output = 1 (why?) int b = -2147483648; cout <<"Product = " << b * b << endl; // output = 0 (why?) Also when we write the similar for 'short' , the compiler takes the product as integer type despite the variable...
Part 1: Intuition, without consulting references Let's try to use some intuition, or reasonable assumptions, regarding why these results can make sense. Basically, this is about what physical integer variables can represent - which isn't the entire infinite set of all integers, but rather the range -2^31 ... 2^31 - 1 (...
70,167,284
70,178,175
boost::log with multi-process
I have asked a question about how to use boost::log in multi-process How to use Boost::log not to rewrite the log file? That answer can solve most part of the problem. But in some rare case, when one process is writing log and another process is starting to write log, 13548:Tue Nov 30 17:33:41 2021 12592:Tue Nov 30 17:...
Boost.Log does not synchronize multiple processes writing to the same file. You must have a single process that writes logs to the file, while other processes passing their log records to the writer. There are multiple ways to achieve this. For example, you can pass your logs to a syslog service or writing your own log...
70,167,531
70,176,161
I2C communication between RP2040 and adxl357 accelerometer ( C/C++ SDK )
I need to communicate via I2C to the adxl357 accelerometer and a few questions have arisen. Looking at the RP2040 sdk documentation I see that there is a special method to send data to a certain address, such as i2c_write_blocking(). Its arguments include a 7-bit address and the data to be sent. My question is, since t...
I2C addresses have 7 bits: these are sent in the high 7 bits of an 8-bit byte, and remaining bit (the least significant bit) is set to 1 for read, 0 for write. The reason the documentation says it wants a 7-bit address is because it is telling you that the write function will left-shift the address by one and add a 1, ...
70,168,411
70,168,500
Can I make use on templates when implementing different interfaces in the same way?
I have many interfaces for different listeners, the all look like this: class ListenerA { public: virtual void onEventA(const EventA&) = 0; }; class ListenerB { public: virtual void onEventB(const EventB&) = 0; }; When testing, I always end up just collecting those events in a std::vector for analyzi...
C++ does not have introspection, so you cannot find the virtual function in ListenerA. The other parts can go in a templated base class, but the override you'll need to define manually. Modern C++ would use a std::function<void(EventA)> instead of a named interface, but that won't help you as a user of that old interfa...
70,169,500
70,234,600
Automatically know if a GCC/Clang warning comes from Wall or Wextra?
I wonder if there's some clever, automatic way of knowing if a particular compiler warning (e.g. -Wunused-parameter) comes from the group -Wall, -Wextra, or another group, for both GCC and Clang. Use case: we want to enable: -Wall -Wextra -pedantic However, some of the pedantic warnings are unapplicable to us and we w...
There's no specific command to get a direct answer to the question "which warning group does a given warning come from?", but it's possible to infer this information automatically by querying the compiler which warnings are enabled and checking if the warning we are interested in is part of the list of enabled warnings...
70,169,887
70,169,973
Ending a while loop in command prompt
This is an excerpt from the Competitive Programmer's Handbook by Antti Laaksonen: If the amount of data is unknown, the following loop is useful: while (cin >> x) { // code } This loop reads elements from the input one after another, until there is no more data available in the input. My question is how do we end su...
In order for that loop to end, cin needs to enter a failed state. That will cause it to evaluate to false and stop the loop. You have a couple ways you can do that. First is to send bad input, which will cause cin to fail and end the loop. Since you are excepting integers, you could just input a letter and that wil...
70,170,160
70,170,420
template class derived from `const` specialized version
I've stumbled upon this code (simplified version here): template<typename T> class SmartPtr; template<typename T> struct SmartPtr<const T> { const T& operator*() const { return *_ptr; } const T* operator->() const { return _ptr; } const T* _ptr; // more member data a...
The general behaviour of SmartPtr<T> and SmartPtr<const T> is indeed identical and no specialization would have been needed simply to handle const and non-const versions of T. However, the answer to your question lies in that this construction allows for implicit conversion from SmartPtr<T> to SmartPtr<const T>. For in...