question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
74,367,090
74,368,006
Is there a fast way to 'move' all vector values by 1 position?
I want to implement an algorithm that basically moves every value(besides the last one) one place to the left, as in the first element becomes the second element, and so on. I have already implemented it like this: for(int i = 0; i < vct.size() - 1; i++){ vct[i] = vct[i + 1]; } which works, but I was just wonderin...
As a comment (or more than one?) has pointed out, the obvious choice here would be to just use a std::deque. Another possibility would be to use a circular buffer. In this case, you'll typically have an index (or pointer) to the first and last items in the collection. Removing an item from the beginning consists of inc...
74,367,298
74,369,151
how to compare (strcmp) 2 char with space?
#include <iostream> #include <cstring> #include <cctype> using namespace std; int main(){ char string1 [50] {}; char string2 [50] {}; cout << "enter the string 1: "; cin.get(string1,50); cout << "your string1: " << string1 << endl; cout << "enter the string 2: "; cin.ge...
Here's the issue: cin.get(string1,50); reads up to 49 characters or until it encounters a \n but it doesn't consume the \n. When cin.get(string2,50); is reached the \n from the first line is the first character in the input buffer so nothing is read. There's a few ways I can think of to fix this. Keep using cin.get an...
74,367,778
74,369,432
How to introduce a new buffer in Base class without wasting extra spaces?
Before======================== struct RedBook : Book {...} struct BlueBook : Book {...} struct YellowBook : Book {...} struct Book { virtual ~Book() = default; // ... static constexpr int COLOR_BOOK_SIZE = 100 char color_book_buffer[COLOR_BOOK_SIZE] = {0}; // used only by ColorBook(i.e. RedBook/BlueBook/Yell...
I believe something like this was mentioned in the comments but you could add another class to the hierarchy which just holds the buffer (std::array). The read, write and count functions are for illustration purposes only. struct book { virtual void read() const = 0; virtual void write(const std::string_view co...
74,368,912
74,369,336
C++: Call constructor of object inside of a vector
I can't seem to find an answer to my question. Everything I've read on the matter seems to not quite connect and I'm starting to think what I want is impossible. I'm working on a very very very light database management system, it's a college project and in my group I'm tasked with the main functions. Here's my problem...
I suppose the simplest approach is to just tell the compiler to construct your vector from a range. You could even use (almost) the same range you used to assign values to all_args. For example: #include <iostream> #include <string> #include <vector> class File { public: File(std::string name) { std::cou...
74,369,079
74,369,120
Powershell subexpression doesn't recognize "pkg-config --cflags --libs opencv4" command
I want to compile an OpenCV C/C++ (MSYS2) program on Windows using solely the CLI. The GNU Bash way to do this is (which runs fine on MSYS2 MINGW64 Shell): g++ main.cc -o main `pkg-config --cflags --libs opencv4` Bash perfectly recognizes the backticks as a subexpression, however PowerShell doesn't: > g++ main.cc -o m...
The equivalent of your bash command is: g++ main.cc -o main (-split (pkg-config --cflags --libs opencv4)) That is: (pkg-config --cflags --libs opencv4) executes your pkg-config call, and, by enclosing it in (...), the grouping operator, its output can participate in a larger expression. Using the unary form of -spli...
74,369,146
74,369,581
Boost Graph Library - Dijkstra's shortest path fails when the edge weights are large?
I have a question regarding the edge weights when using Dijkstra's algorithm in Boost. The problem I am facing is that when the edge weights are large, I do not get a solution from Dijkstra's algorithm. Let's say I have an adjacency list with bundled properties. My vertices are of type VertexType and edges are of type ...
You're passing pred as both the predecessor map and the distance map. One will overwrite the other at unspecified points during algorithm execution. The result is unspecified at best, undefined if you're lucky. Fixed that and simplified some of the code, now the result is the same for both weight inputs: Live On Coliru...
74,369,338
74,372,915
Find and print three-digit positive integers which the value of the first digit is the sum of 2nd and 3rd ones?
I've tried to separate the last digit and the second one and then add them up to compare with the first. How many loops should I use and how to apply? I've tried to separate the last digit and the second one and then add them up to compare with the first one.But I don't know how to. #include <iostream> using namespace ...
I can see some mistakes in the posted attempt. The variable s, which should represent the sum of the second and third digits, is declared and initialized outside the loop, but its value should be reset to 0 at the beginning of the loop, otherwise it accumulates the value of all those digits in all the three digits num...
74,369,360
74,369,496
Recursive Merge Sort, wrong data type for argument?
I feel like ive properly solved the problem, but the program my school is using wants me to add to existing code. The types conflict, and i get this error: main.cpp: In function ‘void mergeSort(std::vector<int>&, int, int)’: main.cpp:21:25: error: cannot convert ‘std::vector<int>’ to ‘int*’ for argument ‘1’ to ‘void me...
To get the underlying int* in array, use the .data() method: void mergeSort(vector<int>& array, int p, int r) { //stuff merge(array.data(), p, mid, r); }; The .data() method returns an int* representing the underlying buffer in which the elements of the vector are stored. This should remove the error.
74,369,679
74,370,484
Get the address of an intrinsic function-generated instruction
I have a function that uses the compiler intrinsic __movsq to copy some data from a global buffer into another global buffer upon every call of the function. I'm trying to nop out those instructions once a flag has been set globally and the same function is called again. Example code: // compiler: MSVC++ VS 2022 in C++...
It's not useful to have the address of a 0x90 NOP somewhere else, all you need is the address of machine code inside your function. Nothing you've written comes remotely close to helping you find that. As you say, &__nop doesn't lead to there being a NOP in your function's machine code which you could offset relative...
74,370,205
74,372,929
calculate sum and avg of the numbers in data file
created a data file to store integers and after the program reads the numbers from the data file, i want to calculate the sum total and average of the numbers and output the total and the average from the second code that reads the data file. what do i need to do to get to that to work? #include <iostream> #include <fs...
This is not that complicated. As per definition, the average can be calculated by divdiding the sum of the values by the count of the values. So, we need to add 2 variables counter --> To count the values in the file sum --> To sum up the values The variables will be defined and initialized to 0 before your read-loop...
74,370,747
74,370,814
Separating this code into a header and cpp file
I am new to modern c++, so I have difficulties to separate header and cpp file with below code (AES encryption and decryption). For example, how would I separate the code? https://gist.github.com/edwardstock/3c992fb71320391d3639696328a61115
Your API goes to the header file. That includes: Any classes your users might want to use Any function/variable declarations your user might want to use The implementation of this API goes to the CPP file: Most function definitions Most variable definitions Implementation details (classes, functions your user will n...
74,370,800
74,371,235
How to produce binned histogram from vector using std::map in C++?
I have a std::vector of float which contains 1300 data, i.e. {1.45890123, 1.47820920, 1.48326172, ...} I would like to build the histogram of the vector using std::map and then plot the histogram with OpenCV. This is how I use std::map to get the count of each data but I have no idea on how to do the binning? size_t fr...
If you want to use a std::map for binning data, you can simply choose the bin's starting value as the key. For that, divide by the bin size and then compute the floor. This will give you a whole number uniquely identifying the bin. float_t binsize = 1.0f; std::map<float_t, int> hgram; for (auto x : hdata) { ++hgram...
74,372,488
74,372,610
Weird behaviour in strptime and mktime, 01-01-1970 (d-m-Y) is unix timestamp 354907420?
I have some weird behaviour in strptime and mktime on MacOS. Perhaps I am doing something wrong but I am getting some weird output. This the code. int main(int argc, const char * argv[]) { const char* timestamp = "01-01-2022"; const char* format = "%d-%m-%Y"; struct tm tm; if (strptime(timestamp, format...
tm is uninitialized; you should initialize it before calling strptime(). This program works: #include <iostream> #include <ctime> int main(int argc, const char * argv[]) { const char* timestamp = "01-01-1970"; const char* format = "%d-%m-%Y"; struct tm tm = {}; if (strptime(timestamp, format, &tm) == N...
74,373,357
74,376,684
How does Windows terminates applications without a window or console on shutdown?
I am currently writing on an background application. It has no window or console running and is also no service. I am using the /SUBSYSTEM:WINDOWS inside my CMake. So I know there are the WM_CLOSE and the CTRL_CLOSE_EVENT and I could spawn an invisible window to wait for the WM_CLOSE. My question now is, what happens t...
On logoff / shutdown all processes associated with that session will be terminated. (equivalent to TerminateProcess(), i.e. the windows SIGKILL equivalent) This is described in Logging off / Shutting down on msdn. Notifications There are a few ways you can register a handler to get a notification before your process g...
74,373,411
74,373,630
Thread_local cost of unused variable
Variables declared thread_local are unique for each thread. But do they consume memory if the function is not called? Let's say I have a bunch of libraries that have thread_local variables in their functions. When I create a thread, are these variables going to be initialized even if I never call the functions that use...
They certainly consume memory. cppreference has this to say (emphasis mine): thread storage duration: The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. As ...
74,373,477
74,541,493
how to test public void function which calls void private function of the same class using google test
dummy code: void fun() { while (m->hasMessage()) { std::pair<std::string, Vector> msg_pair = m->getMessage(); auto topic = msg_pair.first; auto msg = msg_pair.second; for (auto const& x : msg) { auto const type = m->MessageType(x); if (type == "a...
The approach that I have followed to test public function which in turn calling private function is adding throw conditions(exceptions) in private functions and in test case using macro EXPECT_NOTHROW to test the public function : EXPECT_NOTHROW(obj.publicfunction);
74,373,807
74,373,999
Example on FFT from Numerical Recipes book results in runtime error
I am trying to implement the FFT algorithm on C. I wrote a code based on the function "four1" from the book "Numerical Recipes in C". I know that using external libraries such as FFTW would be more efficient, but I just wanted to try this as a first approach. But I am getting an error at runtime. After trying to debug ...
The first 2 editions of Numerical Recipes in C use the unusual (for C) convention that arrays are 1-based. (This was probably because the Fortran (1-based) version came first and the translation to C was done without regard to conventions.) You should read section 1.2 Some C Conventions for Scientific Computing, specif...
74,374,253
74,382,823
OpenACC: Why updating an array depends on the location of the update directive
I'm new to openacc. I'm trying to use it to accelerate a particle code. However, I don't understand why when updating an array (eta in the program below) on the host, it gives different results depending on the location of '!$acc update self'. Here is a code that re-produce this problem: program approximateFun use funs...
This one was perplexing till I determined that its a compiler error. I've filed a problem report, TPR #32673, and sent it to engineering for review. When setting the environment variable NV_ACC_NOTIFY=2, which shows the data movement, I see that the compiler is only copying 40 bytes, versus the correct 128. However, ...
74,374,597
74,374,645
Why is my do/while loop in c++ not allowing me to input 'amount' more than once?
I am attempting to develop a vending machine in C++ in which the user can insert as many 50 cent, 20 cent, and 10 cent coins as they would like to then move on to the 'purchase' of a product. So far, my primitive code runs smoothly; the issue I am currently facing is that I can only 'insert' coins into the vending mach...
You need to put the do { ... } while(...); around the entire block you'd like to repeat. Also, you need a separate variable for the sum. int amount, sum = 0; // ... cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n "; c...
74,375,099
74,376,062
When is `noexcept` required on move assignment?
I recently realized (pretty late in fact) that it's important to have move constructors marked as noexcept, so that std containers are allowed to avoid copying. What puzzles me is why if I do an erase() on a std::vector<> the implementations I've checked (MSVC and GCC) will happily move every element back of one positi...
Here I am only guessing at the rationale, but there is a reason for which push_back might benefit more from a noexcept guarantee than erase. A main issue here is that push_back can cause the underlying array to be resized. When that happens, data has to be moved (or copied) between the old and the new array. If we move...
74,375,574
74,409,240
Which Sentry SDK should I install for my application?
I currently have an iOS application written in C++/Qt and I want to integrate Sentry in my app. The problem is : I don't know which Sentry SDK I should use between sentry-cocoa and sentry-native. How should I chose the SDK for my application ? I tried installing sentry-native but I get this error : [sentry] DEBUG disca...
After some days experimenting, I came to the conclusion that I just needed to install the sentry-cocoa SDK for my application to be working !
74,375,683
74,375,719
what does this variable name do in the Do-While loop expression and what is the meaning of its existence in it?
im trying to learn how to reverse a number but came across a problem about this Do-While loop. Specifically while (n1). Usually i just see people put in a condition with about comparison. #include <iostream> #include <conio.h> using std::cout; using std::cin; using std::endl; int main() { long int n1, n2, Rinteger...
while(n1) without a comparison just means while (n1 != 0) (C treats zero/NULL values as false, all other values as true). So the loop body is always entered once (thanks to being a do/while, rather than a plain while), and continues as long as n1 is not reduced to zero.
74,375,751
74,375,849
Create const std::vector as the concatenation of two const std::vector
I would like to create a const std::vector to contain all the elements of two other const std::vector of the same type. Since the vector is const I can not concatenate it step by step with the two const std::vector using the method mentioned in Concatenating two std::vectors. #include <iostream> #include <vector> int ...
Make a function that takes the other two vectors, creates a third one, inserts values from the first two, returns the result by value. Then assign this to your const vector: const std::vector<int> int_a{0,1}; const std::vector<int> int_b{2,3}; const std::vector<int> all_ints = concat(int_a, int_b);
74,375,991
74,376,360
How to write contents into a file in multiple steps?
I have a basic question: I opened an old log file in the readonly mode and stored content in QTextStream, and closed it. It basically contains 7 lines of texts. I opened another file to write and tried to read line by line. I can read line by line and write entire content into the new file. But I'm trying to do the fo...
since it is 5 lines you could write a simple while loop (I am using the fstream library) void readFirstFiveLines() { std::ifstream file("file.txt"); std::ofstream file2("file2.txt"); std::string line; int i = 0; while (std::getline(file, line) && i < 5) { file2 << line << std::endl; ...
74,376,259
74,376,386
Array decay, passing and recieving pointers to arrays
Please help me understand what happens here: #include <iostream> void foo(int *ar) {std::cout << sizeof(arr) << '\n' << arr[3];} // exceeding array bounds on purpose int main() { int arr[2]{3, 5}; foo(arr); return 0; } Is this an example of array decay? And what exactly is *arr? Is it a pointer-to-int, o...
Yes, that is an example of an array decaying into a pointer. int* arr is a pointer to the first element of the array. The address is guaranteed to be the same as the address of the array, but the type is different. In foo(*arr), you are dereferencing a int[2][1], an array of 2 elements where each element is an array o...
74,376,463
74,380,616
convert python float to 32 bit object
I'm trying to use python to investigate the effect of C++ truncating doubles to floats. In C++ I have relativistic energies and momenta which are cast to floats, and I'm trying to work out whether at these energies saving them as doubles would actually result in any improved precision in the difference between energy a...
I'd suggest using Numpy as well. It exposes various data types including C style floats and doubles. Other useful tools are the C++17 style hex encoding and the decimal module for getting accurate decimal expansions. For example: import numpy as np from decimal import Decimal for ftype in (np.float32, np.float64): ...
74,376,668
74,376,761
How do i create a template function definition with a template class as input
Say I have the following classes: /* Frame.hpp */ template<class PayloadType> class Frame { int address; PayloadType payload; } /* RequestPacket.hpp */ template<class PayloadType> class RequestPacket { // Also a similar ResponsePacket exists Command command; // Command is an enum PayloadType payload; } ...
A specialization needs to match the primary declaration. In your primary declaration you have: template<class From, To> size_t Serializer::serializeTo(const From& input, To buffer); so your specialization needs to be in the form of template<> size_t Serializer::serializeTo(const concrete_from_type& input, concrete_to...
74,377,169
74,377,536
I can't add a new element to dynamic array
There is something wrong with the expand() method. #include <iostream> struct obj { int fInt; float fFloat; }; template <typename T> class dynamicArray { private: T* myArray; int elements; int size; public: dynamicArray(); void add(T dane); void expand(); void init(int el); ...
You got yourself confused, you have a pointer to an array of T, not a pointer to an array of T*, but some of your code is written as if you had the latter. This (in expand) for (int i = 0; i < this->elements; i++) { delete this->myArray[i]; } delete this->myArray; should simply be delete[] this->myArray; You can'...
74,377,297
74,377,928
How do I count the number of paths in this problem?
You are given an n×n grid where each square contains an integer between 1…n^2. A route in the grid starts from some square and moves always either vertically or horizontally into another square, which has a smaller number than the current square. The squares need not be adjacent, and a route can consist of only a singl...
This problem describes a directed graph: every square has a number of (directed) neighbours that are in a horizontal or vertical direction with a smaller number than the start square. The number asked for then devolves to finding all possible paths in this graph. A solution sketch: Create a vertex for every item in th...
74,378,225
74,379,873
std::memset with zero count and invalid pointer
Is it safe to call std::memset(pointer, ch, count) with invalid pointer (e.g., nullptr or junk) when count equals 0?
No, that causes undefined behavior. For example: void* p = get_address(); // may return null size_t sz = get_size(); // zero if previous returned null memset(p, 0, sz); // Compiler may assume that p is not null if (p) { // this null-check can be omitted since we "know" p is not null foo(p); } And indeed, if you l...
74,378,277
74,379,976
Is there a way to check a variable is already initialized in c++?
Let us say I'm initializing a vector vector<bool> V(n);. Is there a way I can know if V[n] is initialized or not? I need this for dynamic programming purposes. If the V[n] is initialized, I would utilize the value V[n] to obtain the result. If it's not initialized yet, I'd apply a function foo(.., n) or something to ob...
Just gathering all the comments into a readable answer. All the members of a vector that exist are intialised, so to solve the problem we really need to represent 3 states, Uninitialised, False, True, and create the entries as Uninitialised. We would want the vector to initially contain nodes in state Uninitialised. So...
74,378,408
74,378,650
How can I get the type of underlying data in a SFINAE template definition?
Say I have a library function int foo( const T& ) that can operate with some specific containers as argument: std::vector<A> c1; std::list<B>() c2; auto a1 = foo(c1); // ok auto a2 = foo(c2); // ok too std::map<int, float> c3; auto a3 = foo( c3 ); // this must fail First, I wrote a traits class defining the allowe...
There is a simple solution: define a trait IsA in exactly the same way you defined IsContainer: template<class> struct IsA : std::false_type {}; template<class T> struct IsA<A<T>> : std::true_type {}; and then write IsContainer<U>::value && IsA<typename U::value_type>::value Depending on your exact use case, you migh...
74,379,582
74,379,734
Texture drawn at wrong coordinates?
I tried drawing a '1' texture at mouse coordinates when I press the 1 key: switch (e.type) { case SDL_QUIT: { quit = true; break; } case SDL_KEYDOWN: { switch (e.key.keysym.sym) { case SDLK_1: { SDL_Rect rect = {e.motion.x - 8, ...
SDL_Event::motion is only valid when SDL_Event::type is SDL_MOUSEMOTION. Stop trying to use SDL_Event::motion when SDL_Event::type is SDL_KEYDOWN, perhaps by recording the X and Y coordinates of the most recent SDL_MOUSEMOTION event and using those instead.
74,380,505
74,380,569
C++ Inheritance and use of Const
I'm currently learning c++ and in inheritance. I have an issue concerning use of const. Here's the code : #include <iostream> using namespace std; class Base { public : virtual void pol() const { cout<< " Base "; } }; class Derived : virtual public Base { public: void pol(...
The problem is that in the derived class const-ness for method pol is missing and therefore is considered a different method, not an override. Add const there too and it will work as you expect
74,380,520
74,381,788
std::invoke_result<F, Args...> does not seem to give a const type
I'd like to start with a simplified example: const bool Foo() { return false; } bool Bar() { return false; } int main() { std::cout << std::is_same<const bool, std::invoke_result_t<decltype(Foo)>>::value << std::endl; std::cout << std::is_same<bool, std::invoke_result_t<decltype(Foo)>>::value << std::endl; std::...
std::invoke_result does not give you the declared return type of the function. It gives you the decltype that an INVOKE expression, i.e. a function call expression in this case, would have with the given argument types. That is specified essentially exactly like this (with a bit more technical wording) in the standard....
74,380,580
74,380,773
How to draw texture at mouse coords using keyboard
Its like the title suggests, i want to draw a "1" texture at mouse coords using a keyboard key press. I am using switch statements for input: switch (e.type) { case SDL_QUIT: { quit = true; break; } ...
e.motion only makes sense when e is a mouse event. Call SDL_GetMouseState to get the current mouse position.
74,380,618
74,380,781
Is there a way to display a vector IN ORDER using a reverse iterator? C++
I have this vector of names: vector <string> names; names.push_back("William"); names.push_back("Maria"); names.push_back("Petterson"); names.push_back("McCarthy"); names.push_back("Jose"); names.push_back("Pedro"); names.push_back("Hang"); I need to display this vector IN ORDER using a reverse iterator. This is my at...
If you go from the end of a range to the beginning, you should check the equality first and then decrement inside the loop body. Otherwise there either is no iteration for the last element or the iterator gets decremented past the end resulting in undefined behaviour. You could use the following loop: // print elements...
74,380,637
74,380,980
boost::adaptors::transformed fails with std::filesystem::directory_iterator
Why entry is empty inside boost::adaptors::transformed() ? I tried without filter, but it does not help. #include <boost/range/adaptors.hpp> #include <boost/static_string/static_string.hpp> #include <boost/utility/string_view.hpp> #include <filesystem> #include <iostream> const auto root = std::filesystem::path("."); ...
I have copied your image into a self-contained program an cannot see your issue: Live On Coliru #include <boost/range/adaptors.hpp> #include <boost/static_string/static_string.hpp> #include <boost/utility/string_view.hpp> #include <filesystem> #include <iostream> int main() { std::filesystem::path root = "."; ...
74,381,187
74,382,139
Find indexes of multiple minimum value in an array in c++
Please don't write that I should do my homework myself. I have tried but cannot find the answer. Input: arr[11]={1,2,3,4,1,5,6,7,8,1,9} Output: 0 4 9 Returned position numbers are to be inserted into another array, I mean: arr_min_index[HowManyMinValues]={0,4,9} I tried to end it in many different ways, but I failed...
Actually you are almost there, if you are new to c/c++, it is a good start. only two modification on you code could make it work: #include <iostream> // using namespace std; // is not a good practice int main() { int n; std::cout<<"How many elements should be in the array?"<<std::endl; std::cin >> n; in...
74,381,238
74,381,338
How to define default constructor and user-defined constructor in the same line?
In my university class we are messing around with inheritance, though my professor's code confused me and seemed to be a little off. class Circle { protected: double radius; public: Circle(double = 1.0); double calcval(); }; Circle::Circle(double r) { radius = r; } Here she is creating a default con...
Here she is creating a default constructor within the class then creating a separate user-defined constructor outside of the class. No, she is declaring the default constructor inside the class's declaration, and then defining the body of that constructor outside of the class declaration. This is perfectly legal and...
74,382,382
74,384,256
how do i compare types in c++?
i'm trying to divide two integers, and if the output is not an integer, it doesn't continue. for some reason this refuses to work no matter what i try. int numeratorOutput{}; int denominatorOutput{}; for (int i{ 2 }; i < 100; ++i) { auto test = numerator / i; auto test2 = denominator / ...
how do i compare types in c++? In your given example, you can use decltype along with std::is_same to check if test is the same as int and test2 is the same as int as shown below: #include <type_traits> static_assert(std::is_same_v<decltype(test), int>); static_assert(std::is_same_v<decltype(test2), int>);
74,382,530
74,382,545
How to use comparer function inside class with algorithm header?
This is what my compare function looks like: bool smallest_weight(const size_t& i, const size_t& j) { return this->abs_weight[i] < this->abs_weight[j]; } I use this function inside the constructor of the class to initialize some other arrays. This is the code that uses it: size_t best_node = *min_element( this...
Try this: size_t best_node = *min_element( this->pointer_list[i + 1].begin(), this->pointer_list[i + 1].end(), [&](const auto& i, const auto& j) noexcept { return this->smallest_weight(i, j); } );
74,382,886
74,383,373
Store character in 2d array and print
I am trying to make a program that plays battleship. I have a 2D array that is printed to the console with nested for loops to display a 10x10 grid of dots that represent the grid. I would like to be able to have the user input an x and y coord for the ship and have it displayed on the grid with a different character l...
You can make this a lot easier on yourself. For instance, initializing every value of playerBoard to '.' can be as simple as: std::fill_n((char*)playerBoard, rows * columns, '.'); You probably don't want to do that in the drawPlayerBoard function, because you'll erase your board whenever you want to display it. Make a...
74,383,298
74,383,542
Input information into a string array - overwriting other parts?
I have a string array that I would like to hold information input at runtime. I'm using an int var to control how many 'rows' there are in my array, but there will only ever be a set number of 'columns'. #include <iostream> using namespace std; int main() { int rows; cout << "How many rows? "; cin >> rows;...
Well, if I understood correctly that the task is to store strings with text in an array that imply the use of newline hyphenation, then here: #include <iostream> #include <vector> #include <string> using namespace std; int main() { int rows; cout << "How many rows? "; cin >> rows; vector <string> page...
74,383,367
74,383,393
How to designated initialize a C++ struct that has a construcotr?
I have a very large struct that has customized copying constructor, customized moving constructor, customized moving assignator, and customized copying assignator, but I also need to use Designated Initialization syntax somewhere to initialize it, because it is very large, while I just want to initialize only few field...
There isn't. Designated initializers work only for aggregates. Aggregates are types that satisfy a few conditions, notably: no user-declared or inherited constructors
74,383,685
74,383,710
C++ programming project header/implementation files
So i am practicing header files and implementation files for c++ and i cannot seem to display the letter grade for this program. Everything else is working as it should and displaying the correct data except for the letter grade. I have been trying to figure it out and i think it may be something so simple that i am mi...
You are never calling setGrade(). Maybe you should call it in the class's constructor?
74,383,819
74,383,887
program that reads an integer, and prints all the perfect numbers
int n; int sum; cout << "write a number"; cin >> n; for (int i = 1; i < n; i++) { sum = 0; for (int j = 1; j <= i; j++) { if (i % j == 0) sum = sum + j; } if (sum == i) cout << i<< endl; } Why do I always get 1 as a result? I couldn't understand the logic of it. Wh...
Remind about mathematics. Refer to wiki In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. So, in your code, you are making sum of ALL divisors of i include itself. That's why you only get result 1. You should change it simply. for ...
74,384,200
74,384,993
How to extract value from json array with QJsonDocument format
I'm getting a json format like this and I want to get the value of "Duration", "Id", "LoadCumulLimit" and "Notes". QJsonDocument({"d":{"results":[{"Duration":"420.000","Id":"123456789XYZ","LoadCumulLimit":"15.000","NavWpNioshToOpNoish":{"__deferred":{"uri":"http://xxx/WorkplaceNOISHDataSet('123456789XYZ')/NavWpNioshToO...
You could convert the QJsonDocument to a QVariant. Then you can use QVariantMap or QVariantList to walk the document and use the appropriate toString() or toDouble() to retrieve the values. The following is hard-coded to your JSON there are only minimal validation checks included. (i.e. it is a disclaimer that the code...
74,384,437
74,384,794
How to define a multiline wstring with content from another file
I would like to define the content of a file in a wstring, so I can print it with an ofstream later on. Example: // Working std::wstring file_content=L"€"; // Working file_content=L"€" L"€" L"€"; // NOT Working file_content=L"€" L"€"" L"€"; // Working file_content=LR"SOMETHING(multiline with no issues)SOMETHING"; F...
You need to escape double-quote characters inside of a string literal, eg: // Working file_content=L"€" L"€\"" // <-- L"€"; Alternatively, use a raw string literal instead, which does not require its characters to be escaped, eg: // Working file_content=L"€" LR"(€")" // <-- L"€";
74,384,496
74,384,544
Memory fault when print *pointer
Why do I have a memory fault in the below code? How do I fix it? I want to read the progress of the outside function. But I only get the output get_report_progress:100 #include <iostream> int* int_get_progress = 0; void get_progress(int* int_get_progress) { int n = 100; int *report_progress = &n; int_get_p...
Your global int_get_progress variable is a pointer that is initialized to null. You are passing it by value to the function, so a copy of it is made. As such, any new value the function assigns to that pointer is to the copy, not to the original. Thus, the global int_get_progress variable is left unchanged, and main() ...
74,385,153
74,386,828
How to optimize Fibonacci using memoization in C++?
I'm struggling with getting the correct implementation of finding the nth number in the Fibonacci sequence. More accurately, how to optimize it with DP. I was able to correctly write it in the bottom-up approach: int fib(int n) { int dp[n + 2]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) ...
You set up the memoization storage in fib, and then create the recursive part of your solution in the lambda recurse. That means that here: dp[n] = fib(n - 2) + fib(n - 1); you really should call recurse not fib. But in order to do that with a lambda, you need to give the lambda to the lambda so to speak. Example: #inc...
74,385,642
74,385,814
converting heap based vector to stack
I would like to convert it to vector of vectors but I'm confused about the code above it's better to store it on stack rather than heap, that's why I want to change it to vector of vector std::vector<DPoint*>* pixelSpacing; ///< vector of slice pixel spacings pixelSpacing = new std::vector<DPoint*>(volume.pixelSpaci...
Okay, as per the comment, I am making an answer. std::vector<DPoint> pixelSpacing(volume.pixelSpacing->size()); for (unsigned int i = 0; i < pixelSpacing.size(); i++) { pixelSpacing[i] = DPoint(/*DPoint constructor args*/); } Or alternatively: std::vector<DPoint> pixelSpacing; //Reserving size is optional. pixelSp...
74,386,082
74,386,303
C++ maps with variables
Is it possible to create a dynamically changing map? For example, i want to use it in the for loop, and use i as a variable in map value: uint8_t i{}; std::map<uint8_t, int16_t> substitutions{ {0, array[i][0]}, {1, array[i][1]}, {2, array[i][2]}, {3, array[i][0] * array[i][1]}, {4, array[i][0] * array[i][...
I'd probably solve your problem by not using a map at all. I'd use a switch statement instead (it should be slightly faster): for (uint8_t i = 0; i < 3; i++) { auto substitute = [i](uint8_t value) { switch (value) { case 0: return array[i][0]; case 1: return array[i][1]; case 2: return array[i][...
74,386,327
74,386,611
How to check whether a mutex lock have been destroyed or not?
I have a problem where my code tries to call pthread_mutex_destory() twice. I need to check whether the lock have been destroyed before or not. How can I do this? Will this work: void deinit() { if(1 == pthread_mutex_trylock(&this->m_lock)) { (void) pthread_mutex_destroy(&this->m_lock); } } Will tr...
Once you destroy a a c object, the data left behind is garbage. c++ doesn't let you do this. (It does but you have to explicitly ask for it.) But you are using a c library, so you have to do everything yourself. So you have a few options: use std::mutex which works nicely with c++. But as such, you mutex will have the...
74,386,612
74,403,322
How to expose native to managed - C++/CLI on x64 Platform
I have a static lib in my project and I want to use this in my .net project. I have taken this project as a starting point. Exposing native to managed - C++/CLI My use case is the Second Approach. So far everything works, but when I change the architecture from x86 to x64 I get a lot of linker errors: Currently I do n...
Do you change library when switching architecture? If not the linker would look for the wrong mangled
74,387,597
74,388,381
std::map::try_emplace return value results in a dangling pointer when retrieving a unique_ptr
I have a factory function that returns a non-owning pointer to the created object after it is inserted into a resource-owning map to be later stored as a non-owning pointer elsewhere; however, by using the return value of std::map::try_emplace which should be an iterator to what was/is inserted, this causes the interna...
The code can be as simple as Feature* Feature::CreateFeature(Map* map, const XMLElement& elem) { auto new_feature = std::make_unique<Feature>(map, elem); return s_registry.emplace(new_feature->name, std::move(new_feature)).first->second.get(); } If the new_feature was not inserted because the slot is already o...
74,387,787
74,388,539
C++ equivalent to std::all_of but working with a range loop?
I am trying to re-write a piece of code that currently looks like this: if (nchildren > 7 && parent->isChildValid(0) && parent->isChildValid(1) && parent->isChildValid(2) && parent->isChildValid(3) && ... parent->isChildValid(7) ) { } It tests the parent->isChildValid(i) 8 times where i, is an index...
In C++20, you can use views::iota and ranges::all_of to do this if (nchildren > 8 && std::ranges::all_of(std::views::iota(0, 8), [parent](auto i) { return parent->isChildValid(i); }) ) { }
74,387,901
74,387,948
Using .c_str' with pointers (and also pointers to pointers)
so, I encountered a little problem and I am kinda stuck. Basically I am trying to pass the value of a string** in C-type form to a char* string The code is as follows: static int BuildDBListSql( std::string **SqlBuf, const char* ColumnNames, const char* TableNames, ...
To fix the error you ask about, change char *SqlBufcopy = *SqlBuf.c_str(); to char *SqlBufcopy = (*SqlBuf)->c_str(); Reason: SqlBuf is pointer to pointer (which makes no sense at all), so to get to the actual object, you need to dereference it twice.
74,388,124
74,502,988
Can assignment operations which declared as default have reference qualifiers?
When declaring assignment operations as default, is there anything wrong to make them reference qualified to prevent assignment to temporaries? (Most often than not, it prevents stupid errors). Common resources, do not say anything about reference qualifiers for "default" operations, and almost every example I've seen ...
It is allowed to define a defaulted assignment operator with an additional ref-qualifier. See [dcl.fct.def.default]/2.1. Whether or not you should actually do it is an opinion-based question. I don't see anything obviously wrong with adding a &, but I suspect that you'll encounter resistance if you try to convince ever...
74,388,676
74,390,469
Is THRUST stable_sort_by_key O(n)?
Can I assume that Thrust stable_sort_by_key performed on unsigned int has complexity O(n)? If not what should I do to be sure that this complexity will be achieved? (Except of implementing radix sort on my own)
It depends a bit on your circumstances/view. Just from the docs/API there doesn't seem to be a guarantee for thrust::stable_sort_by_key on unsigned int keys using a radix sort. On the other hand the necessary algorithm cub::DeviceRadixSort::SortPairs is implemented in the CUB library which is used by Thrust in the back...
74,388,697
74,388,836
_mm256_load_ps segmentation fault
I'm developing a high throughput low latency real-time program that involves several matrix operations. I have decided to use AVX2 or AVX512 to boost the performance of system. This is my first first attempt to use AVX instruction set of SIMD in general. I'm using the AVX Intrinsics functions available in g++. The pr...
_mm256_load_ps requires aligned memory. _mm256_set_ps doesn't even require contiguous addresses. You want _mm256_loadu_ps - unaligned load, but still from a contiguous array.
74,389,216
74,389,396
How can I use the C++ regex library to find a match and *then* replace it?
I am writing what amounts to a tiny DSL in which each script is read from a single string, like this: "func1;func2;func1;4*func3;func1" I need to expand the loops, so that the expanded script is: "func1;func2;func1;func3;func3;func3;func3;func1" I have used the C++ standard regex library with the following regex to f...
You can also NOT use regex, the parsing isn't too difficult. So regex might be overkill. Demo here : https://onlinegdb.com/RXLqLtrUQ- (and yes my output gives an extra ; at the end) #include <string> #include <sstream> #include <iostream> int main() { std::istringstream is{ "func1;func2;func1;4*func3;func1" }; ...
74,389,226
74,403,906
Are resources global in scope in a C++ (VS) program and consequently where is the ideal place to load a list into a combo box?
I'm using a resource file for my dialog boxes, menus, etc. in a C++ program in Visual Studio. Just wondering if a resource file has a global scope? Also, as a consequence of this, where is the ideal place in the program to call GetDlgItem to get the handle of a combobox and to load its list (as well as other similar ...
The information given in the comments answered the question sufficiently. What initially prompted the question was my desire and attempts to put items in a combo box list. The code below successfully accomplished this. This is mostly a Visual C++ autogenerated message handling procedure for a drop down menu entry ca...
74,389,275
74,389,323
convert struct to uint8_t array in C++
I have a typedef struct with different data types in it. The number array has negative and non-negative values. How do I convert this struct in to a unint8t array in C++ on the Linux platform. Appreciate some help on this. Thank you. The reason I am trying to do the conversation is to send this uint8_t buffer as a para...
For a plain old data structure like the one you show this is trivial: You know the size of the structure in bytes (from the sizeof operator). That means you can create a vector of bytes of that size. Once you have that vector you can copy the bytes of the structure object into the vector. Now you have, essentially, an ...
74,389,562
74,389,701
wrong printed sorted array
I'm new to C++ and I've been doing bubbleSort, but when I want to show the numbers in the terminal, the leading number is a problem. Sorry for my bad english btw. where am i doing wrong? this is the code: #include <iostream> void printArray(int *myArr, int lenght) { for (int i = 0; i < lenght; ++i) { std::...
The problem is that you are confusing pointers with arrays with single integers. int bubbleSort(int *myArr, int lenght) { // ... not actually that important what happens here ... return *myArr; } Your bubbleSort gets a pointer to first element of an array passed, you do some sorting and eventually you return t...
74,389,801
74,389,917
Is there a way to make a struct take a variadic list of elements in a nested struct to be constexpr without initializing it in multiple parts?
Say I have this struct layout: #include <vector> struct A { char const* name; std::vector<char const*> list; }; struct B { char const* group_name; A an_A; int other_stuff; }; Which I initialize thusly: B b = { "My B", { "My A", {{ "My", "variable", "length", "list" }} }, 42 }; Is there...
The problem is that you've specified extra braces around { "My", "variable", "length", "list" } in your second example. Thus to solve this you need to remove those extra braces {} as shown below: B b = { "My B", { "My A", //-v--------------------------------------v---->removed extra braces from here { "My", "va...
74,389,905
74,390,040
Can a factory method return 0 in case of an error?
I am studying a bit of code, which contains a factory method, if I am remembering my object orientation correctly. The factory method and the related classes can be described by the following pseudo-C++. The class Actor is the base class for the various implementations of concrete actions or operations, which in turn a...
yes, you are overthinking this. It should really be return nullptr, but in this case return 0 is equivalent.
74,390,711
74,390,798
Why adding `explicit` to a defaulted copy constructor prevents returning an object?
Considering this MRE (the real case involves some class with some inheritance and some member variables) class A { public: A() = default; explicit A(const A&) = default; // explicit A(A&) = default; ///Adding this serves no purpose explicit A(A&&) = default; A& operator=(const A&) = default...
In your function dummy_a your return value requires implicit copy construction auto dummy_a() { A a; return a; // implicit 'A::A(A)' } If you indeed want your copy constructor to be explicit then this should be modified to auto dummy_a() { A a; return A{a}; // explicit 'A::A(A)' }
74,390,977
74,392,274
Boost Geometry compilation error in version 1.80.0 using custom point type
I'm using Boost 1.80.0. I would like to use boost geometries with a custom point type. To do that I register my custom point into boost::geometry. I am then lock when I want to use boost::geometry::within() function. I got a compilation error that I do not understand well. See some errors: boost/1.80/include/boost/geom...
So I dove into the code/message and noticed that inside the algorithm an equal_range call is used comparing between a helper geometry (built with helper_geometry<>) and yours. It ends up calling a comparator with incompatible point types: using mutable_point_type = bg::helper_geometry<MyPoint, double>::type; bg::less<m...
74,391,415
74,391,523
Change values of a matrix in C++
I need to get the upper triangle of a matrix by setting everything under the diagonal to 0. Here is the code I wrote: #include <iostream> #include <vector> using namespace std; vector<vector <int>> upper_triangle(vector<vector <int>> n) { int rij = n.size(); int kolom = n.size(); vector<vector<int>> result...
You simply have return result; in the wrong place. Like this vector<vector <int>> upper_triangle(vector<vector <int>> n) { int rij = n.size(); int kolom = n.size(); vector<vector<int>> result = n; for (int i = 0; i < rij; i++) { ... } return result; } not this vector<vector <int>> upper...
74,392,924
74,393,071
determining variadic template arguments are compile time
Let's assume i want to define a type that depends on some types: struct TimerPump{}; struct GuiPump{}; struct NetworkPump{}; template<class... Pumps> class DispatcherT{}; using Dispatcher = DispatcherT< TimerPump, GuiPump, NetworkPump >; I would like to make the gui and network pumps ...
Basically, you'd like optional list append. To do that, you first need list append: template<typename... Ts> struct list { template<typename T> using append = list<Ts..., T>; template<bool b, typename T> using appendIf = std::conditional_t<b, list<Ts..., T>, list<Ts...>>; template<template<class.....
74,394,749
74,394,791
why the result is different add thread by loop
I am the novice of multithreading, and I want to try to use the 2048*2048 height map texture to generate a set of vertices. void HeightMap::CalculateVertices(Vector3 vertex_scale, Vector2 texture_scale, int start, int end, GLubyte* data) { for (unsigned int z = start; z < end; ++z) { for (unsigned int x = 0...
The secret is your lazy auto-capture-by reference: std::thread([&]{ /*...*/ }) This is almost always a bad idea. In this case, you are capturing i by reference, which means when the thread invokes the lambda, i might not even exist and will certainly not have the correct value. At the very least, capture i by value. I...
74,394,819
74,396,261
How can an object access another objects data?
Yet another question about my project for my university! We are creating a cash register program which has an inventory, both held in their own respective header files with their own classes and objects. Here is our current iteration of our header files, thought it may be messy from debugging. Inventory.h: class inven...
If you want to access the data of inv from a cashRegister object; instead of passing the inv object as reference every time you use it's data, you may want to hold a pointer in cashRegister class. inventory class will have member functions for manupilating and accessing it's data. Therefore you will be able to access t...
74,394,852
74,394,872
Write a function that multiplies each element in the array "myArray" by the variable "multiplyMe". c++
I'm supposed to use a function to multiply all elements of an array by 5 and print the numbers after. I don't understand how to put the array in the function definition. What i tried: #include <iostream> using namespace std; // TODO - Write your function prototype here int MultiplyArray(int[], int); int main() { ...
You are very close. Simply remove the 10 from the [] in the function's parameter type, and use < instead of <= in your function's loop. Your loop is going out of bounds of the array (look at the loop in main(), it is using < correctly). int MultiplyArray(int myArray[], int m) { for (int i = 0; i < 10; ++i) { // <--...
74,394,991
74,395,593
What is the minimal way to write a free function to get the member of a class?
(This question popped to my mind after reading this one and its accepted answer.) Assume a class Foo that you cannot modify, that has a public member bar, but no getter for it. You might want to write a function to get that memeber when passed a Foo, so that you can use it in higher order functions, such as std::transf...
Well, for minimal work: const auto getBar = std::mem_fn(&Foo::bar); This particular use case appears to do what you want. In C++20, it was upgraded to be constexpr, but that might or might not be available. Unlike the other question, which has overloadable member functions, a member variable isn't ambiguous. So I w...
74,395,291
74,400,887
Sum up values in multidimensional array in c++ and store it in another multidimensional array
I try to sum up the values in an array, and would like to store it in another array. #include <cstdlib> #include <iostream> using namespace std; int main() { int rev[2][12] = {{10,20,30,40,50,60,70,80,90,100,110,120}, {100,200,300,400,500,600,700,800,900,1000,1100,1200}}; int tem...
The first two for loops give me the desired output Let's see why // This variable is declared and contextually assigned a meaningful value: zero. int temp = 0; for (int j = 0; j<2;j++){ for(int i = 0; i<12; i++){ // Here it's updated, we want it to hold the sum. temp += rev[j][i]; } // N...
74,395,393
74,424,628
Gtkmm add/Remove widget leaks Why?
When I add a widget to container, then I remove it. Widget is leaked, why ? I used a "MyWidget" to spy widget deletion but I get same result from a classic Gtk::Label. Code below have been tested on two distro. #include <iostream> // gtkmm30-3.24.5-1.el9.x86_64 // or gtkmm3 3.24.7-1 (arch) #include <gtkmm/main.h> #incl...
The incorrect assumption we made here is that Gtk::Window::remove() destroys the widget it removes, but in reality, it only removes its reference from the parent container. I instrumented your code with extra couts to see what was happening and when this line is executed: builder->get_widget_derived("widget", widget); ...
74,395,552
74,452,644
Prevent clang-tidy from running on generated files
We have a project that includes protobuf files that get pre-compiled into C++ files. Unfortunately, those files (like the other source files in the project) get checked by clang-tidy and generate a large number of warnings. The relevant top-level CMakeLists.txt statements are: # For all targets set(CMAKE_CXX_CLANG_TID...
Since the "grpc_services" target only contains generated files, you can just set the CXX_CLANG_TIDY target property on that target to be nothing.
74,395,595
74,398,359
CXX translate - const char * to rust equivalent
I am writing an integration of C++ and Rust via CXX https://cxx.rs/index.html The C++ function signature in myclient.h public: bool connect(const char * host, int port, int clientId = 0); What do I put in the main.rs in order to have it callable from rust? I've tried a lot of combos fn connect(hos...
char in rust is not what you want (in rust char is a unicode chacrter, while in C it is a single byte). What you want is libc::c_char. use libc::c_char; extern "C" fn connect(host: *const c_char , port: u64, clientId: u64 ) -> bool { true } However I'm not sure the bool as the return type will work reliably, I'd p...
74,395,672
74,395,892
Why do I need std::move twice in a row?
I'm fudging around with some code because I think I found a solution to another problem. I'm writing a little test program and I got it to work. But only if I use std::move() twice in a row. Here's the example code: using namespace std; class Serializable { public: virtual string serialize() = 0; }; class Packet:...
If you do: Frame("", packet) The compiler will try to copy the argument packet into the parameter packet. As you know, std::unique_ptr cannot be copied. Even if you are passing this into a parameter, since you cannot copy, you need to move the std::unique_ptr. And then, in the constructor: Frame(string head, unique_pt...
74,395,948
74,414,040
C++ lambda as parameter with variable arguments
I want to create an event system that uses lambda functions as its subscribers/listeners, and an event type to assign them to the specific event that they should subscribe to. The lambdas should have variable arguments, as different kinds of events use different kinds of arguments/provide the subscribers with different...
After the input from @joergbrech and @HolyBlackCat I made this enum class EventType { WindowClosed, WindowResized, WindowFocused, WindowLostFocus, WindowMoved, AppTick, AppUpdate, AppRender, KeyPressed, KeyRelease, MouseButtonPressed, MouseButtonRelease, MouseMoved, MouseScrolled, ControllerAxisChan...
74,396,388
74,396,797
C/C++ macro conflict from external libraries
I'm trying to combine boost/asio library with ncurses, but they have macro conflict. It gives this error message: [build] /usr/local/include/boost/asio/basic_socket_streambuf.hpp:640:39: error: expected expression [build] socket().native_handle(), timeout(), ec_) < 0) [build] ...
To prevent a macro conflict you need to redo a structure of your project that way, so no file include both ncurses.h and boost/asio.hpp headers simultaneously. To do this you need to wrap one library in .hpp+.cpp pair and also make sure that .hpp doesn't include the header of this library and only .cpp does. Then only ...
74,396,641
74,396,780
Is there a way to change the color of the text in a ChooseFont() dialog in the Win32 API?
I am developing a basic text editor program with the Win32 API's file editor example, using Dev-C++ from bloodshed.net. How can I change the text color when I select it on the ChooseFont() dialog? In that dialog, everything works except the color changing option. Below is my code. Choose font dialog, and in the switch ...
A font doesn't have a color. A device context has a color assigned which it uses when rendering text using a font. To set a text color for a standard EDIT control, have the parent window handle the WM_CTLCOLOREDIT and WM_CTLCOLORSTATIC window messages: An edit control that is not read-only or disabled sends the WM_CTL...
74,396,733
74,396,742
C++ - Why is a Static Library unusable without source files?
So from what I understand, a static compiled mylib.a file should just be usable as plug-and-play. But I can't use it without the source code, I'm trying to avoid that. I adapted this tutorial to compile using CMake with the following directory structure: / lib libmy_math.a main.cpp my_math.h my_math.c...
A static library does not contain each and every definition a header can contain - think of macros, etc. Thus you still need the header. However, you don't need the .cpp anymore to link the library.
74,396,872
74,397,379
Declare a template pointer without knowing the type
I have this code with a template function. The function can accept any object that is inherited from Object or with an operator providing a pointer to an Object instance. Inside the function I need to get the Object pointer, but it is a template type and I can't figure out the way how to specify the template type. here...
First off, either your Wrapper is wrong or your usage of it is wrong. You instantiate Wrapper<Object<int>> but in the class you have: Object<T> object; operator Object<T>*() which is instantiated as Object<Object<int>> object; operator Object<Object<int>>*() You should either instantiate Wrapper<int>, which would "wr...
74,397,068
74,397,305
pointer variable defined by typedef
I know that the code below works. int* pn; pn = new int; So I tried to apply it in same way, in my custom class. class Matrix { private: typedef struct ex_node* ex_pointer; typedef struct ex_node { int ex_data; ex_pointer next; }; public: void examplefunction() { ...
I like the question and Jason Liam already provided different ways to fix your code. But I'd like to answer your first questions, which are entirely valid: "The error says that I cannot assign "ex_node" type value to "ex_pointer"type entity. But ex_pointer is defined as ex_node*. Is ex_pointer different type from ex_no...
74,397,873
74,397,890
What is a Token in C++?
I am feeling really dumb right now but I am not understanding the concept of tokens. I am currently reading Dr. Stroustrup's textbook, Programming Principals and Practices, am and in Chapter 6 learning about tokens and writing programs in C++. I have gotten every concept in the book thus far, but this has really got me...
A token corresponds roughly to a word of source-code. For example, in a line of source code like this: int a = 10; The tokens would be "int", "a", "=", "10", and ";". In a compiler, it's the job of the tokenizer to interpret the source code files (which are really just plain-text files, i.e. a series of characters) i...
74,398,728
74,399,696
Completing a Birthday Problem using a 2-D String Array
I'm really new to C++ so I apologize in advance if my code is horrendous. I have a birthday problem in which I am required to create a program that asks for a total of 5 friends names and their corresponding birthdays and store those values in a 2-D array and then print them all at the end. I have no idea how to do tha...
To do this project, you can get help from the STL library, which makes the work easier. you could use std::vector or std::arrays , also instead of char array you can use std::string. but if you want to use C-style array than your array will look like this : std::string birthSimulator[5][2]; you create a array of 5 str...
74,398,966
74,399,073
How do I make the if statement return to the previous step?
so I want to return to 'Enter a new email address: " once the user enters an incorrect email address rather than it move on to the next step. cout<<"\n\t Enter a new email address: "; cin>>str; if(Email_check(str)) { cout<<""; //i dont k...
Whenever you want to do something repeatedly you need some kind of loop. Since you want to repeat until an email address is valid a do ... while loop seems appropriate. Here's one way to do it bool email_valid = false; // track whether email is valid do { cout << "\n\t Enter a new email address: "; cin >> str; ...
74,399,033
74,401,467
Cannot reboot system from C++
I've a C++ program running in a docker container. I want to reboot container via my program but I cannot. Dockerfile: FROM gcc WORKDIR /client COPY . . RUN apt-get update && apt-get install qt5-qmake qtbase5-dev libmosquitto-dev -y RUN qmake mainapp.pro && make RUN chmod +x docker-entrypoint.sh docker-entrypoint.sh...
Thanks for the answers. I added this to my docker compose yaml file: privileged: true restart: always After that, reboot(RB_AUTOBOOT); rebooted my container and started the app successfully.
74,399,683
74,399,770
Strcat not appending a character
char* oledScreen::getCurrentTime(){ char* hour = malloc(16); snprintf(hour, 16, "%d", getHour()); char* minute = malloc(16); snprintf(minute, 16, "%d", getMinute()); char* firstPart = strcat(getHour() < 10 ? strcat("0",hour) : hour, ":"); const char* secondPart = getMinute() < 10 ? strcat("0",minute...
To begin with, strcat("0",hour) will lead to undefined behavior as you attempt to modify the literal string "0" which isn't allowed. Instead of using multiple strcat calls, why not simply create a string large enough to fit the result, and use snprintf to put contents into the string? Using snprintf will also make it e...
74,399,833
74,423,951
What is the machinery behind stack unwinding?
I'm trying to understand the machinery behind stack unwinding in C++. In other words I'm interested in how this feature is implemented (and whether that is a part of the standard). So, the thread executes some code until an exception is thrown. When the exception is thrown, what are the threads/interrupt handlers used ...
The thread executes some code until the exception is thrown, and it continues to do so. Exception handling still is C++ code. The throw expression creates a C++ object, running in the context of the throwing function. While the constructor of the exception object is running, all objects in the scope of the throwing fun...
74,401,144
74,409,272
QListView with Two QTextEdit 's as Item
In Qt Widget Application (c++), a part of my *.ui file consists of a QListView with two QTextEdits as its items like the below figure. As you can see custom widget includes two QTextEdit that each one has its text and stylesheet. As I searched on the net, there are solutions like HtmlDelegate classes for rendering tex...
well first of all you should create your custom widget like this: Then you add it to your Model of QListView by using setIndexWidget function like this: QStandardItemModel *model = new QStandardItemModel(120, 1); ui->listView->setModel(model); for (int r = 0; r < 120; r++) { ui->listView->setI...
74,401,246
74,403,903
Can C++-modules be consumed by non-modularized code?
I have a rather large codebase, that I want to start porting to C++20-modules. The layout is (roughly) like this: SDK/System > Engine > Editor In the order of they reference each other (editor uses engine, etc...). My main interest would be, to first port SDK, and then Engine to modules. Editor is the least important i...
A file that is not a module unit can import module units just fine. You can even #include a header which has import directives in it (not that this is a good idea). And module units can #include headers just fine, so long as you do it in the global module fragment, before the main module declaration. What you can't do ...
74,401,373
74,402,621
Can this_thread::sleep() be interrupted on linux?
When using nanosleep, we need to check the return value to detect whether we have been interrupted by a signal: while ((nanosleep(&rqtp, &rmtp) == -1) && (errno == EINTR)) { if (rmtp.tv_nsec != 0 || rmtp.tv_sec != 0) { rqtp = rmtp; continue; /* Wait again when interrupted by a signal handler */ ...
If you use GCC's libstdc++, you can find the corresponding code here: while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR) { } with the timespec __ts prepared accordingly. So it basically does the same thing as your code loop and restarts the sleep after a signal interrupt. The C++ standard itself says: Th...
74,401,389
74,401,507
Push back string into vector<T>
I'm finally trying to learn templates and I created a template function that will return an std::vector with a generic type. When compiling I get an error: error: no matching function for call to ‘std::vector::push_back(std::string&)’ Is there a way to support std::string or a comparable type in the template vector i...
The code does not compile because you try to check the types at runtime. This is too late. Use std::is_same to make a compile time check. template<typename T> std::vector<T> getData() { std::vector<T> entries; int i_value; double d_value; std::string st_value; if constexpr(std::is_same_v<T, int>) ...
74,401,584
74,403,491
About the Windows BYTE and PBYTES data types
What is "BYTE" and "PBYTE" used for?.I couldn't find any information on the internet. #include <iostream> #include <Windows.h> using namespace std; BYTE by='a'; PBYTE pby= &by; int main(){ cout<<"by : "<<by<<endl; cout<<"&by : "<<&by<<endl; // Why doesn't it return the memory address? cout<<"pby : "<<pb...
BYTE,PBYTE is very old style in windows programming. If you want to allocate heap memory for your image loader for example, you can write unsigned char* img = new unsigned char[1024 * 1024]; load_image(img, ....); conv_image(img, ....); But your finger would be tired, so you can write PBYTE img = new B...
74,401,680
74,411,120
Calling managed function inside CommandBuffer hang domain reload
I'am trying to call managed function inside CommandBuffer via IssuePluginEventAndData. It accepts (void* function pointer, int eventId, void *data). Here's the function: [UnmanagedFunctionPointer(CallingConvention.StdCall)] public unsafe delegate void PluginDelegate(int eventId, void* data); [MonoPInvokeCallback(t...
Ok, I found the solution. The thing is that if function pointer obtained by GetFunctionPointerForDelegate is called from non-managed thread, you need to first initialize a thread with mono_attach_thread(domain). So before calling function by pointer, you need to somehow call mono_attach_thread before, as stated in Mono...
74,401,974
74,404,075
Fastest way to get Storage Buffer to host from compute shader in Vulkan
I have a large Storage Buffer of ~4.6MB I am sending via compute buffer and then retrieving at the host at the end of the render loop. I was hoping someone could provide guidance on a possible optimal way of going about this? The performance of the app without the host read is about 3000 FPS on my machine and 800 FPS w...
The performance of the app without the host read is about 3000 FPS on my machine and 800 FPS with it. This is a prime example of FPS being a misleading performance metric. Using raw time is better, as it makes it much more clear what the absolute time difference is. The compute-only process really takes 0.33ms, while...
74,402,203
74,402,295
incrementing unsigned char *image
void draw(unsigned char *image) { for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { if (someCondition) { int red = x * 256 / WIDTH; int green = 255; int blue = y * 2...
From the code it is evident that the pointer points to an element of an array of unsigned char: [ ][ ][ ][ ] ........... [ ] ^ | image Next consider that image[i] is equivalent (really equivalent, that is how it is defined) to *(image + i), ie it increments the pointer by i and dereferences it. You can write image...