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
68,142,676
68,142,738
Why does decltype(captured_var) not behave as expected?
#include <type_traits> int x = 0; void f(int const x) { static_assert(std::is_const_v<decltype(x)>); // ok } int main() { int n = 0; [n, m = n] { static_assert(std::is_const_v<decltype(m)>); // ok static_assert(std::is_const_v<decltype(n)>); // err }; } See online demo Why does d...
Note that in decltype(n), n refers to the local variable n defined in main(), but not to the member of the closure type (as you expected). [expr.prim.lambda.capture]/11 (emphasis mine) Every id-expression within the compound-statement of a lambda-expression that is an odr-use of an entity captured by copy is transform...
68,143,585
68,143,650
std::vector.erase() only erases half of what it should
I have a program where I have to delete some entries of a vector of structs. Im doing it like this for(int i=0; i<molec.size(); i++) { if(!molec[i].mine) molec.erase(molec.begin()+i); } molec.mine is a boolean defined in the struct. The problem is that when I do this, it erases exactly half of ...
You are probably looking for std::remove_if. As in molec.erase( std::remove_if( molec.begin(), molec.end(), [](const auto& elem) { return !elem.mine; }), molec.end());
68,143,609
68,143,640
C++ finding index of value in array
I have recently started working with the Arduino (which is C++). When I run the below function (along with other code): int index(int val,int list) { int i; for (i = 0; i < 8; i++) { if (val == list[i]) { return i; } return null; } } I get an error on the line if (val...
you should accept as an array instead of single-variable in function: int index(int val, int *list) { int i; for (i = 0; i < 8; i++) { if (val == list[i]) { return i; } } /* if no match found */ return -1; } Note: you need to return an integer value instead of null, since the return type...
68,143,634
68,143,731
Function for inserting a value in binary tree?
I have a function insert that is used to insert values into the Binary tree. But when I log out the value nothing is shown. I'm aware of the insertion using member function. The root node's value is not being updated? Could someone tell me where I'm going wrong? #include <iostream> using namespace std; class Node{ ...
you are inserting position on the right place but the problem is you are not creating the link of your newly inserted node to it's parent. you can check this as reference!
68,143,642
68,143,927
Why does GCC succeeds on a constraint with std::tuple_size::value, but fails on one with std::tuple_size_v?
In the following code why does the second and third concepts produce a compilation error? #include <tuple> template <class P> concept IsPair1 = std::tuple_size<P>::value == 2; template <class P> concept IsPair2 = std::tuple_size_v<P> == 2; template <class P> concept IsPair3 = requires { typename std::tuple_size<P>; ...
The initializer of a variable template is not in the immediate context, so any error there causes a hard error instead of a substitution failure. std::tuple_size<P>::value == 2 works because the attempt to name the member value of an incomplete type is in the immediate context. requires { typename std::tuple_size<P>; }...
68,143,660
68,149,995
How can I find the positions from characters in a string with string::find?
I need the positions of characters in a string. The String contains: "username":"secret", "password":"also secret", "id":"secret too", "token":"secret" and I need the positions of the quotation marks from the token that are bold: "token":"secret". I have experimented with the code from http://www.cplusplus.com/referen...
There are so many possible solutions. So, it is hard to answer. What basically needs to be done, is to iterate through the string, position by position, then check if the character is the searched one, and then do something with the result. A first simple implementation could be: #include <iostream> #include <string> ...
68,144,039
68,154,023
Can boost variants safely be used with pointers to forward declared classes?
Can boost variant safely accept pointers to classes that are forward declared without any unintended implications such as using them with visitors? class A; class B; typedef boost::variant<A*, B*> Variant; class A { public: A() {} }; class B { public: B() {} };
I'd suggest using the builtin recursive element support for this exact purpose. It makes the (de)allocation(s) automatic and exception safe. Here's a complete demo where B actually recursively contains a vector<Variant> (which is 90% of the use-cases for forward-declared element types): Live On Coliru #include <boost/v...
68,144,057
68,144,097
Why is const temporary bound to rvalue reference parameter?
I have the following functions: void func(void * const &ptr) { std::cerr << "const" << std::endl; } void func(void * &&ptr) { std::cerr << "mutable" << std::endl; } void* const func2() { return nullptr; } One overload takes const reference parameter and another takes mutable rvalue reference. And th...
Why is const temporary bound to rvalue reference parameter? Because it's not const by the time overload resolution happens. [expr.type] 2 If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis. A cl...
68,144,099
68,148,132
This is a program to search a number and also display its index position if found in an array
This is a C++ program to search a number and also display its index position if found in an array. Program works fine. I just wanted to ask why we used k=1 in if statement because if we don't use it, then program won't work. Please explain the significance of k=1 in 2nd for loop in if statement. #include<iostream> usin...
Looks like you are trying to do a linear search, there are some points I would like to clarify.. Never use int arr[n] using cin by user, it may work in yours, but not all compilers support it. Always allocate memory to the array statically like arr[10] or arr[20] You are changing k which is the number that is to be f...
68,144,762
68,144,790
Access violation reading location error in multithread function
Check this code for possible multithreading errors, please. Sometimes I got an error "Access violation reading location" at line cv.notify_all(); (marked in code). uint64_t GetFirstAdvertisingBLEAddr() { std::mutex m; std::condition_variable cv; BluetoothLEAdvertisementWatcher advWatcher; uint64_t addr...
The mutex and condition variable both go out of scope when the function GetFirstAdvertisingBLEAddr returns. The captured variables in your lambdas are then dangling and reading those variables makes your program have undefined behavior. One possible workaround is to make them static: static std::mutex m; static std::co...
68,144,821
68,152,101
Vcpkg isn't working on windows with mingw
i'm actually trying to make vcpkg with cmake and MinGW working on windows but it seems like he don't want to use MinGW Here is the error : -- Running vcpkg install - done -- The C compiler identification is GNU 8.1.0 -- The CXX compiler identification is GNU 8.1.0 -- Detecting C compiler ABI info -- Detecting C compile...
You’re using a mingw x86 toolchain, while the config file from the error message is for x64, so it was rejected.
68,145,118
68,145,290
Create array upto 10^12
I tried to create an array with size upto 10^12 elements in c++. But I can only make array upto 1000001 size. i.e long long int dp[1000001] But I want to store data upto 10^12 values in the array. Any Idea how can I implement this in C++ ?
First, you must realize that the size of that array is nearly 8 TB. Does your computer have that much memory? Probably not. In such case, you cannot store that much data in memory, and practically cannot have such a large array. Any Idea how can I implement this Instead of an array in memory, you could store the data...
68,145,211
68,145,328
C++ : Ambiguous Behavior of Ternary Operator
I tried and tested the following code to understand the behavior of ternary operator. But it is only making things complicated for me. The code: #include<iostream> using namespace std; void print(bool a, bool b, bool c) { int x, y, z, w; cout << (a ? (b ? x = 5 + b : y = 10 + b) : (c ? z = 15 + c : w = 20 + c)...
You have strange results because you arn't initializing the x, y, and z variables. The old value is being resused. Init them with 0 and you'll get different results
68,145,364
68,148,888
How to reliably end a thread blocked on an IO task
I have a class which executes a thread in order to constantly read lines from a given istream, which are then parsed internally. At some point I want it to end, but since the getline() call is blocking, it may wait forever on join(). #pragma once #include <thread> #include <iostream> class Parser { private: std::...
If std::getline encounters end-of-file, then it will immediately return and stop blocking. Therefore, if you could somehow arrange for this to happen when you want the thread to exit, then that would probably be the best solution. However, if that is not possible, then I'm afraid that ISO C++ itself does not offer any ...
68,145,601
68,145,801
What is the better form to write Loop functions end with pointers in c++?
I know two forms to write loop functions with pointers in c++: using size of array or using the end of array. Use the length: float summationArray(float* numbers, int length){ if(length == 1){ return *numbers; } return *numbers + summationArray(numbers + 1, length - 1); } Use the end float summationArray(fl...
Pre C++20, two iterators are better because they allow the function work on all types of iterators even those that don't know the size of the range. This is the convention most of the standard library follows. Post C++20, you would probably use a range. PS: Don't use recursion to calculate a sum. That's a bad idea. Use...
68,145,852
68,145,867
Can't create multiple objects in class
When I try to create more than one object, I get an error saying no matching function for call. I don't understand, usually I can create as many objects as I want without a hitch but the moment I add a parameterized constructor in the equation, suddenly I'm not allowed to create more than one object. Why is it so? Here...
You explicitly declared a constructor Point(int x1, int y1), so the compiler-generated default constructor is disabled. You can add one to the class declaration like this: Point() : x(0), y(0) {} Or, in C++11 or later, you can add a default constructor like this (be careful, the int members won't be initialized by thi...
68,146,113
68,146,483
Is there a more concise way to create a std::wstring from an API that returns a wchar_t**?
I would like to generate a std::wstring from the Win32 function GetThreadDescription() function. Currently, I am doing it like this: wchar_t thread_desc[MAX_PATH]; wchar_t* p = &thread_desc[0]; check_hr(GetThreadDescription(GetCurrentThread(), &p)); std::wstring wthread = std::wstring(p); However this seems really awk...
GetThreadDescription() takes a wchar_t** parameter because it outputs a new wchar_t*. IOW, it allocates its own buffer for the string data and assigns that buffer to the wchar_t* that you have to provide. As such, your thread_desc[] array is useless and will just waste memory, so get rid of it. GetThreadDescription() ...
68,146,355
68,146,507
Correct way to pass object arrays to functions?
So recently, I have been struggling with passing an array to the function (described below). My problem is that when I pass an array only the first element of the array works properly (shown with cout's). And also, object "Enemy" is a child of "Obj". Creating an array of enemies: const int eN = 2; Enemy enemyAr...
the problem is, that you pass an array of type Enemy to a function that expects an array of type Obj. That only works if you pass a single object and if Enemy inherits from Obj. this cannot work for arrays: sizeof(Obj) is some X. So accessing obj[1] would expect that the second object starts at address adressof(b)+X. B...
68,147,148
68,147,163
How to slowdown an output character by character? (Mac OS)
My goal is to output a string of characters one by one. But when I run it, it staggers and ends up just outputting the entire string with no delay in-between characters. I am currently running this code on a Mac operating system. #include <iostream> #include <thread> #include <chrono> /** Asks user to input name. ...
Output to std::cout is usually line-buffered - that is to say, it is only sent to the terminal when a newline is encountered (or the buffer fills up). You can modify this behaviour with std::flush: std::cout << usrName.at(i) << " " << std::flush; Any buffered output will then be written to the terminal immediately.
68,147,179
68,147,310
How to get the event window from an event in xlib
I'm trying to implement a feature that changes the color of a child window when the user hovers over it. To do this, I need to receive EnterNotify events for specific child windows. I'm getting the EnterNotify events with no problem, but I can't figure out how to distinguish between which child window the EnterNotify e...
It turns out that when you create a child window using XCreateSimpleWindow, the parent window's mask input is not carried over to the child window. All I had to do was update each child window to receive EnterWindowMask events.
68,147,621
68,147,937
How can I create an iterator of a range of indexes in C++11?
I'm working with an API that takes a start and end iterator, and runs async work on the objects in that range. However, in one case I want to iterate over indexes of objects, not objects (from 0 to myVector.size() - 1). I could create a simple vector of those indexes and use its .begin() and .end() iterators, but that ...
If you have access to C++20, then you can use std::views::iota/std::ranges::iota_view to get a sequence of integers: std::vector<SomeType> vec = ... auto index_sequence = std::views::iota(std::size_t{0}, vec.size()); some_function_needing_iterators(std::begin(index_sequence), std::end(index_sequence)); Live Demo Unde...
68,148,507
68,148,791
How to implement queue with a single stack in C++
In this C++ code I'm implementing Queue with a Single stack instance. I found this code in GeeksForGeeks. Url Here #include <bits/stdc++.h> using namespace std; class Queue { private: stack<int> s; public: void enque(int x) { s.push(x); } int deque() { if (s.empty()) { ...
The code isn't really using a single stack, its using the built-in stack as a second stack via the recursive call to deque. The code is equivalent to: #include <iostream> #include <stack> class Queue { private: std::stack<int> s; public: void enque(int x) { s.push(x); } int deque() { ...
68,148,825
68,153,097
Setting Various compilers in CMake for creating a shared library
I am looking to set various compilers for different folders in my project, which should compile to a shared library. The project structure is as follows - /Cuda a.cu b.cu c.cu header.cuh /SYCL a.cpp b.cpp c.cpp header.h main.cpp test.cpp All the files under the Cuda folder must be compi...
CMake allows one compiler per language, so simply writing this is enough: cmake_minimum_required(VERSION 3.20) project(example LANGUAGES CXX CUDA) add_subdirectory(Cuda) add_subdirectory(SYCL) You can separately set the C++ and CUDA compilers by setting CMAKE_CXX_COMPILER and CMAKE_CUDA_COMPILER at the configure comm...
68,148,878
68,149,263
How do you create a singly linked list with input in C++
We were tasked with creating a linked list with the following output: Enter number of nodes: 5 12 4 5 44 45 The linked list: 12 4 5 44 45 I am very confused with linked lists, with my code being the following #include <iostream> using namespace std; struct Node{ int data; int nodeNumber; Node *next; }*...
You do not have to pass the size variable to the addNode Function. Just take values as much you desire in main funtion and pass them to addNode funtion by looping till the size, then add Nodes to the list as usual. Your code will look something like this: #include <iostream> using namespace std; struct Node{ int d...
68,148,886
68,148,913
C++ - One-liner to iterate nested brace-enclosed lists?
In Python we can do for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]: ... Is there something similar in C++? In the non-nested case there is for (auto i : {0, 1}); but extending to nested lists for (auto [i, j] : {{0, 0}, {0, 1}, {1, 0}, {1, 1}}); doesn't compile.
This works: #include <initializer_list> #include <utility> void foo() { for (auto [i, j] : std::initializer_list<std::pair<int,int>> { {0, 0}, {0, 1}, {1, 0}, {1, 1}} ); } and note you have to include the two headers. You can also use this shorter version: #include <initializer_list> #include <...
68,149,468
68,149,943
Cuda move element in array to the end
Hello my issue is this any advice will be greatfully accepted: I have array of structs (representating Particles) but for simplify I have array containing only True values at start (Particle.exist = True). I am running my own CUDA kernel function on this array and in some cases the True value is changed to False. Afte...
Sorting on GPUs is rather inefficient, so it is better to select the values to keep and perform a partition based on them. To do that easily, you can use CUB which is quite efficient (as it often implement best state-of-the-art algorithm or close to). You can use DevicePartition or two DeviceSelect (the former will lik...
68,149,996
68,150,053
Variable don't update from sfml event loop
I am using sfml library for my graphics. During paused I want to avoid drawing on the screen. I want to intercept a spacebar press using sf::Event::MouseButtonPressed. In the debug mode, the event is successfully intercepted but failed in normal execution, why? The bool variable 'paused' don't seemed to update. while (...
Use the Event::KeyReleased instead of the Event::KeyPressed as the key press gets called every loop that a key is down leading to many enters while the Release event is only called once per click.
68,150,015
68,150,049
Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'sound_ctl')
I'm trying to write a << operator. My code: #include <iostream> #include <ostream> class sound_ctl { private: int _vol; bool _status; public: sound_ctl() : _vol(50), _status(false) {}; void operator++() { if (_vol <= 98) { _vol += 2; } } void operator--() { ...
You should not define an input/output operators as member functions. std::ostream &operator<<(std::ostream &os, const sound_ctl& sc) { os << sc._status << "Volume: " + sc._vol << std::endl; return os; } And then declare this function as a friend: class sound_ctl { friend std::ostream &operator<<(std::ostream &...
68,150,160
68,150,803
C++ string calculator
I have been doing exercises on some online judges, and I encounter this question with this default answer. Question description: Finally, Hansbug has finally reached the moment to do the last math problem, and there are a bunch of messy addition and subtraction equations in front of him. Obviously success is at hand. ...
All right, let's try it, let's put there some expression with addition and subtraction of ints only, after that press Return, then ctrl+D (end of input): $ ./a.out 111-222+1 -110$ The loop while (cin >> c) will parse integers including the sign one by one using iostream capabilities until an end of input (you also ha...
68,150,162
68,167,216
Cmake package configuration when looking for each other's packages
When i catkin_make when module_one find package module_two and module_two find package module_one, there is error like below -- +++ processing catkin package: 'module_one' -- ==> add_subdirectory(module_one) -- Could NOT find module_two (missing: module_two_DIR) -- Could not find the required component 'module_two'. Th...
I tried to imitate your setup: I made a new workspace, I make two new packages using catkin_create_pkg, and I got your error. This happens when some of the following setup issues aren't addressed: In CMakeLists.txt, you must find_package(catkin REQUIRED COMPONENTS ...) the neccessary packages (don't forget roscpp if y...
68,150,477
68,151,674
Templates and optimization of conditional branching
I'm a fairly new to C++ and the whole template programming, im sorry this question might be a bit dumb or does not make much sense, but I have the following code enum SomeEnum : int {FIRST, SECOND, THIRD, FOURTH}; template<SomeEnum Val> void Foo(){ ... some code ... int x = 0; if(Val == FIRST){ x = DoCalcu...
The C++ standard allows the C++ compiler to perform any optimization that has no observable effects. However the C++ compiler is not obligated to do so. In your specific case, there does not seem to be any observable effects of the described optimization, and it is a fairly simple optimization. Therefore it's likely th...
68,151,032
68,164,618
c++ SDL_mixer error, Mix_LoadWAV_RW with NULL src
For some reason not all sounds is working. The Mix_GetError() returns this error message Mix_LoadWAV_RW with NULL src I have 57 different sound files loaded and 8 of them is not working and they all give the same error. The 8 sounds that does not work is the 8 in the very bottom of the picture. It is weird that the 8 t...
You just forgot to add ".wav" file extension at the end.
68,151,500
68,160,162
How to delete item within an item in json and C++ nlohmann::json
I would like to know how I can delete an item within another item using nlohmann::json in C++. I have looked at the documentation for basic_json::erase but I can only see how to delete an item in the root of the json file, for example "Test" in my example json file. Here is my json file: { "TEST":{ "Age":10...
you can use a json_pointer: auto json = nlohmann::json{<your json>}; auto path = nlohmann::json_pointer<nlohmann::json>{"TEST"}; auto& someTest = json[path]; // Erase from the 'someTest' node by key name someTest.erase("Name");
68,151,857
68,161,674
Parameter list in Lambda
I went through few of the answer about lambdas in C++ like: what is a lamba expression expression in C++ 11 The answers were quite helpful, however I am having difficulty to understand following the code. I have a vector of ints std::vector <int> ivec{ 19,2,23,15 }; I want to sort it in descending order so sor...
Lambda creation I think I had the same confusion when I first saw lambdas. So let's see what this expression means: [](auto x, auto y) {return(y < x); } This just creates the lambda object. It does not call the labda. Think of it as a class definition + object creation. Your questions Let's consider the declaration of...
68,151,969
68,152,278
Pass member function as parameter to a parent class in a different header
Consider two classes. One being EventReceiver in a header file named events.h that defines a method Subscribe which takes in a name parameter and some callback function, and a class that derives EventReceiver in a header entities.h named Entity, that defines a method OnStart, which must be called on event named "start"...
If you were to go the std::function route, it'd probably look something like: // events.h: using callback_type = std::function<void()>; // entities.h (the constructor): Entity() { SubscribeEvent("start", [this](){ OnStart(); }); }
68,152,010
68,152,150
How to friend a function inside a namespace which is in a different file?
I'm having an issue with a friend function. Basically I have a class in a header (inside a namespace), which contains a friend function: namespace X { class Foo { // private members friend void SomeNamespace::someFunction(const Foo& foo); } And in a separate header, I have the function which I'm trying to make a fri...
To expand on my comments, lets say you have the following three files: Foo header file #include "SomeNamespace.h" namespace X { class Foo { friend void SomeNamespace::SomeFunction(const Foo&); }; } SomeNamespace header file namespace X { // Forward declaration class Foo; } namespace Som...
68,152,047
68,152,097
Is it considered the bug of both GCC and Clang for the sequence of copy-initialization of the result of a call?
Please see this example #include <iostream> struct A{ A(){ std::cout<<"A constructed\n"; } ~A(){ std::cout<<"A destroyed\n"; } }; struct B{ B(int){ std::cout<<"B constructed\n"; } ~B(){ std::cout<<"B destroyed\n"; } }; struct C{ C(){ std::cout<<...
The return value from the function in question is a bool. This is what gets returned. Your logged output shows no evidence of when the copy-initialization of the bool return value was sequenced, before or after anything else. It also happens to be true that once the bool value is returned, the caller uses it to constru...
68,152,200
68,154,287
How to fit second-order multivariate polynomial (3D surface) using Ceres Solver library
I would like to find the following transfer function using nonlinear least square: z = a + b*x + c*y + d*x*y + e*x^2*y + f*y^2*x + g*x^2*y^2 Where a, b, c, d, e, f, g are coefficients which we need to find. x, y, z are variable. In my experiment, x and y are the vertical and horizontal coordinates of pupil-glints vect...
There is a curve fitting example in the ceres tutorial, have a look at that.
68,152,229
68,152,389
Does c++ file ostream or file print function output '\0' to file when output a char array
I want to write some data to a binary file. I output a char array to a file like this std::ofstream os; os.open("myfile", std::ios::out | std::ios::binary); os<<"A"; os.close(); or char a[]="A"; File* file = fopen ("myfile","wb"); fprintf(file,"%s",a); And in the end, does the file includes the '\0'? In other words, ...
And in the end, does the file includes the '\0'? No. Strings are printed excluding terminating zero byte.
68,152,247
68,152,479
How to format this data to send to a serial port?
I am trying to send commands and receive data from a hardware device via a serial port in Windows. The documentation has the following information: There is also an example command given in the documentation, which looks like this: Client: $02 $30 $34 $30 $31 $30 $33 $32 $41 $03 which should result in the returned da...
This is a bug: char(0x02) + "0401032A" + char(0x03) It adds integral types (char, char const* and char). What you likely wanted is char(0x02) + std::string("0401032A") + char(0x03), 10) // or char(0x02) + "0401032A"s + char(0x03) // or indeed, much simpler: "\x02" "0401032A0\x03"s Keep in mind that if you w...
68,152,333
68,152,526
copy constructor and assignment operator in C++
class MyClass { private: int x; public: MyClass(int x) { this->x = x; } MyClass(const MyClass& other) { this->x = other.x; } }; int main() { MyClass first(1); MyClass second = first; //(1) first = second; // (2) MyClass third = MyClass(2...
Constructors, including copy constructors, are for initializing a class object. Assignment operators are for modifying an object which was already initialized. Line (1) calls a copy constructor because it is initializing the object second. The assignment operator has nothing to do with the fact that the = symbol is als...
68,152,658
68,152,674
Can anyone explain about how this recursive function works in c++?
I have been new to programming and solving C++ questions of Deitel book for a while now and I got confused when imagining this recursive function in which an array of 10 elements and the first element number(current = 0) is sent to the function. My question is after executing the someFunction function inside the if blo...
All function calls work the same way. After returning from the function call the execution resumes with the next statement after the function call. Recursive function calls are no different, in that respect. The only difference between a recursive and a non-recursive function call is which function gets called: the sam...
68,153,140
68,153,210
Strategy Pattern and Covariant Return Type in C++
class Context{ public: Strategy* strategy; void PickStrategy(Strategy *strategy){ delete this->strategy; this->strategy = strategy; } C* execute(string some_text) const{ return this->strategy->execute(std::move(some_text)); } }; class C{ }; class D: public C{ } class My...
This is a perennial problem. The core issue is, Context wants to have dynamic control of its strategy (including the dynamic type of its return value) but its users want static assurances on that return value. You can template Context on the strategy and/or on the return type, and potentially template Strategy on the r...
68,153,281
68,153,457
OpenGL use uniform buffer as an array
I found out that I can use uniform buffers to store multiple variables like this #version 330 core layout (location = 0) in vec3 aPos; layout (std140) uniform Matrices { mat4 projection; mat4 view; }; uniform mat4 model; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0); } and tr...
uniform float[] globalBuffer; is not a uniform buffer. It is just an array of uniforms. You must set the uniforms with glUniform1fv. A Uniform block would be: layout (std140) uniform Foo { float[] globalBuffer; } Unfortunately, in this case each array element would be aligned to the size of vec4. See OpenGL 4.6...
68,153,636
68,153,742
Why returning a pointer to a struct initialized without malloc doesn't fail in C++
I saw this code in C++ - it is used to add two linked lists. The addTwoNumbers function defines a head which is a struct pointer and its next member is a struct. Eventually the function returns the next member of head. Both were initialized on the stack (without using malloc) so how is it possible that the returned val...
int main(int argc, char **argv) { ListNode three(3); ListNode two(4, &three); ListNode one(2, &two); ListNode six(3); ListNode five(4, &six); ListNode four(2, &five); All of these nodes have automatic storage indeed. And when the function main returns, those nodes are destroyed. However, you aren't return...
68,154,162
68,154,214
Why is the map value not updating?
I have this free function in my code : void changeRanks(int n, map<int, double>& id_rank_map) { cout << "n : " << n << endl; for(auto itr : id_rank_map) { itr.second = double(1) / double(n); } } I've verified that 'n' is not 0, but still each value in 'id_rank_map' is 0.00 even after the execution of th...
When using a range based for loop, the variable left of the : is not an iterator, but the value itself: for(auto v : id_rank_map) spelling it out: for(std::pair<const int, double> v : id_rank_map) Written like this, now it is obvious, that in each iteration, a copy of the value is created, then modified, then thrown ...
68,154,488
68,154,511
Alternatives To Global Variables in C++
I need to set a variable in the main function and access it from a different function in the same file. I can not pass it to the function because it means changing the entire code structure, which is not an option. To avoid declaring a global variable I crated a namespace and I want to check if this is a good programmi...
Alternatives To Global Variables in C++ In the example, function argument is a good alternative to avoid a global variable: static void myFunc(int mylocalvar) { ..... some code operationX(mylocalvar); ..... some code } int main(int argc, char **argv) { ..... some code mylocalvar = atoi(argv[0]); ...
68,155,095
68,155,212
periodic timer intervals in C++
I'm converting a code from C# to C++. I want to call a function every at periodic time intervals. My original function in C# is: private void Init_timerGetData() { timerGetData = new Timer(); timerGetData.Interval = 5; timerGetData.Tick += new EventHandler(ReadData_Tick); } private void ReadData_Tick(objec...
You can roll your own with a class that launches a thread to do the calls. Here's a simple one I use that will call every period until the class's destructor runs. You can tweak the details of the implementation to achieve most anything you want: #include <atomic> #include <chrono> #include <functional> #include <thr...
68,155,096
68,157,203
How do I find out the type of this map in a range based for loop?
map <int, map <int, double> > adj_list_M; I want to run a range based for loop, iterating through this map. So I want to know the type I can use for getting the references of the elements. Also please verify whether this is correct for doing that : for( auto& ele : adj_list_M ) Thank you in advance!
The type is pair the [key, value]'s template is template<typename _T1, typename _T2> struct pair { typedef _T1 first_type; /// @c first_type is the first bound type typedef _T2 second_type; /// @c second_type is the second bound type _T1 first; /// @c first is a copy of ...
68,155,311
68,155,475
How do you deep copy a vector of derived class pointers via the copy constructor?
#include <iostream> #include <string> #include <vector> //#include "V2d.h" using namespace std; class item { public: int value; string description; item() {} virtual ~item() {} virtual void display() { cout << "Value: " << value << endl; } }; class Cat : public item { public: strin...
To do this correctly two more things need to be added to the base class: class item { public: virtual ~item() {} The base class must have a virtual destructor. virtual item *clone() const=0; And an abstract method that's traditionally called clone(). Every one of your subclasses must implement clone(), typic...
68,155,600
68,232,605
CMake is not using correct paths when looking for lib files
I recently installed vcpkg on my windows system and the cmake (and cmake tools) extension for vscode, because I wanted to use a json file for my c++ project. I had put vcpkg in a random location just to mess around with it and learn how it works. However, when I moved it to another location as its final spot, CMake got...
I had to take out the find package function. The find package function made cmake expect the source code to be in the buildtrees folder, which in this case isn't (I think it was at some point, but I don't know why it wont come back). Just by using target_link_libraries(${PROJECT_NAME} jsoncpp), as well as the include/l...
68,155,708
68,155,871
vector variable inside for loop
I have defined an empty vector variable inside the loop for the test case, after execution of each test case I expect the vector will go empty, but it is storing the previous result of the earlier test cases as well please help thanks a lot. My problem statement is this. which takes input as: The first line of the in...
Your vector (v) is being reset (to empty) on each run of the outer for loop but your map (m) isn't. That is keeping its content each time, and your new inputs are being appended to it. Thus, your for (auto x : m) { appends the data from each previous loop to your (initially empty) vector. Move the declaration of map<st...
68,155,887
68,157,191
Valgrind detected wrong allocation on heap?
I wrote a C++ program that ran correctly over valgrind but I have notices something really strange: ==23369== HEAP SUMMARY: ==23369== in use at exit: 0 bytes in 0 blocks ==23369== total heap usage: 1 allocs, 1 frees, 72,704 bytes allocated Where this allocation came from? I only called sbrk() and mmap() but neve...
You may try to debug your program(We need to install the debug symbol for libstdc++ at first, see this): start the program with gdb gdb $YOUR_PROGRAM Add debug breakpoint b malloc Run the program r Get the call trace after hitting breakpoint: bt On my PC with this nearly empty program: #include <iostream> i...
68,156,027
68,156,073
How does recursion work in this code and not terminate after the if condition is not satisfied?
Can someone please explain to me how this prints 10 9 8 7...1 and not just 10? cout<<b[x]<<endl; is inside if(x<y), so how come does it not terminate after x reaches 9, making it print 10 only? #include <iostream> using namespace std; void someFunction(int[], int, int); int main() { int a[]={1,2,3,4,5,6,7,8,9,10}...
Try thinking of this in terms of code substituation. At each point that someFunction() is called swap in the actual code of the function. include <iostream> using namespace std; void someFunction(int[], int, int); int main() { int a[]={1,2,3,4,5,6,7,8,9,10}; int value=10; someFunction(a,0,value); retu...
68,156,032
68,156,062
is the string type a header file or in the standard namespace?
I'm a newbie to C++, and programming for the most part, just started learning a few days ago, and I'm a bit confused about this. Is the string variable type in the standard namespace? I found I can use strings without using #include <string>. I can also use using namespace std;, to activate the use of strings, or std::...
std::string is a class defined in the standard library header <string>. Like all names of the standard library, it is declared in the namespace std. is #include <string> the same as saying using std::string; ? No. Those have two entirely different meanings. #include <string> means "include the content of the header <...
68,156,582
68,156,616
C++ How do I make my code stop after the user enters three wrong guesses
the point of my code is to make the user input their guess. if their guess is 4 the code breaks if is not then they have 2 more chances out of the three.
You can "merge" two while loops by using logical operators: #include <iostream> using namespace std; int main() { int number; int correct = 4; int guess = 0; do { cout << "Enter a number: "; cin >> number; guess = guess + 1; } while (guess < 3 && number != cor...
68,156,686
68,158,257
Why for_each requires an instance to be passed as an argument while the hash unary function for unordered map does not in C++?
To construct an unordered map with a customized hash function struct EnumClassHash { template <typename T> std::size_t operator()(T t) const { return static_cast<std::size_t>(t); } }; enum class MyEnum {}; std::unordered_map<MyEnum, int, EnumClassHash> myMap; To construct a for_each function stru...
When you write std::unordered_map<MyEnum, int, EnumClassHash> you are specifying a type. When you write for_each(arr, arr + 5, Class()); you are specifying an expression. These are two very different things.
68,156,716
68,157,124
CMake include_directories does not help to find header files
The directory structure of the project is: project | bar | | src | | | src.cpp (include "a.hpp") | | | CMakeLists.txt (3) | | third_party | | | a.hpp | | CMakeLists.txt (2) | main.cpp (include "bar/src/src.cpp") | CMakeLists.txt (1) CMakeLists1.txt: cmake_minimum_required(VERSION 3.15) set(TARGET Foo) project(${TARGET...
'include_directories' affects the include directories of targets in that CMakeLists.txt, and its descendants. I think the issue is that the executable is added (targeted) in CMakeLists.txt 1; src.cpp isn't actually in CMakeLists 2's target/build scope, so it isn't affected by 'include_directories' calls in CMakeLists ...
68,156,762
68,157,278
How to export template function?
From this post, I need to export function ci_find_substr, so in my header file, i declare function: template<typename Twst> __declspec(dllexport) int ci_find_substr (const Twst& str1,const Twst& str2 , const std::locale& loc = std::locale()); but when compile this code from another project: int k=ci_find_substr (w...
You can't export a template from a DLL, you can only export a specialisation of said template! #ifdef COMPILING_DLL // ensure you are declaring 'COMPILING_DLL' somewhen when building your DLL #define DLL_EXPORT __declspec(dllexport) #else // when using the function it must be DLL import! #define DLL_EXPORT __declspec(d...
68,156,864
68,185,804
C++ {fmt} library, user-defined types with nested replacement fields?
I am trying to add {fmt} into my project, and all is going well, except I hit a little snag when trying to add a user-defined type for my simple Vec2 class. struct Vec2 { float x; float y; }; What I would like is to be able to use the same format flags/arguments as the basic built-in float type, but have it duplicated...
You can reuse formatter<float> for this (https://godbolt.org/z/vb9c5ffd5): template<> struct fmt::formatter<Vec2> : formatter<float> { template <typename FormatContext> auto format(const Vec2& vec, FormatContext& ctx) { auto out = ctx.out(); *out = '('; ctx.advance_to(out); out = formatter<float>::f...
68,157,291
68,157,442
why, I'm getting some strange garbage values?
When I'm trying to store & print an integer array with write(), I'm getting garbage values...But everything turns fine when I go with character array (instead of integer array). *I'm new with File-Handling. #include <iostream> #include <fstream> int main() { int num[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; /* char num[20...
Files are in bytes. Integers are made of either 4 (32-bit) or 8 (64-bit) bytes. They can also be in little-endian (Intel) or big-endian (PowerPC) byte order. In memory and in the disk file you wrote, num[0] is char[4] {1, 0, 0, 0} What you did is perfectly fine if you wanted to write the binary representation of your i...
68,157,413
68,157,722
Creating a template with an operation and a data type c++
In my project, similar code is used in two places. I would like to create a template to avoid this repetition of code. Here's the first case: IAsyncOperation<GattCharacteristicsResult> charListResult = service.GetCharacteristicsAsync(); while (charListResult.Status() != AsyncStatus::Completed) { continue; } GattCha...
I guess you can also template the return type and then explicitly specify it in the call: template<class ResultType, class Operation> ResultType getNested1(Operation operation) { IAsyncOperation<ResultType> result = operation(); while (result.Status() != AsyncStatus::Completed) { continue; } ret...
68,157,470
68,157,565
How to use ring of for to put letters together to form a word?
As we can store and add numbers. How to get the letters of a color in this code grain by grain and then display it in full, using for For example: enter n:4 number1:b number2:l number3:u number4:e color: blue My problem is I don't know what to do to save all the letters, not just the last letter. int n; char a; char s...
How about using + operator int n; char a; string s=""; cout<<"enter n:"; cin>>n; for(int i=1;i<=n;i++) { cout<<"number"<<i<<":"; cin>>a; s += a; } cout<<"color: "<<s; If you need individual letter, use string.at(postion) function.
68,157,476
68,157,509
What is this construct in C++ called?
I programmed in C/C++ for years, but haven't in some time, and am unfamiliar with some of the C++ code in the snippet below. Specifically I am confused by the inner { }. What is going on here. It looks like a get method of bufferTransfer is being called, but instead of that being followed by a semi-colon, it is followe...
Here we call get() passing it a lambda, where [this] denotes that the lambda captures the pointer to object on which the get() method is invoked. All what's in the {...} are the contents of the body of the unnamed lambda function object. Lambda has the following form: [capture1, caputre2, ...] (param1, param2, ...) { /...
68,157,800
68,166,813
Is there a way to "listen" for a program's outbound system messages?
I'm trying to replicate the behaviour of an automation tool that sends a few system messages to a program with the specified window handle but I'm not sure which messages it's using. Is there a way to listen to a program's outbound system messages? This is for Windows. My replica is in C# but I'm familiar with C++ as w...
I'm trying to replicate the behaviour of an automation tool that sends a few system messages to a program with the specified window handle but I'm not sure which messages it's using. Is there a way to listen to a program's outbound system messages? If the automation tool is using window messages, you can use monitori...
68,157,945
68,157,995
Initialize array of objects in constructor
I wrote a class that holds an array of objects, which each expect a pointer to a c-struct in their constructor: Here's some code: class TheOtherClass { private: SomeCStruct* m_pCStruct; int m_ObjIdx; public: TheOtherClass::TheOtherClass(SomeCStruct* pCStruct, int ClassIdx) ...
Since MyClass(SomeCStruct* pCStruct) constructor doesn't (can't) initialize the TheOtherClass m_objects in the member initializer list, the m_objects will need to be default constructed at first, and then this member will be reassigned with new value in the body of the MyClass constructor. The TheOtherClass won't have ...
68,158,012
68,158,313
Problem in implementing a linkedlist in c++
I am learning C++ and trying to implement a singly linkedlist. Basically a linkedlist providing two simple methods, insert and display. Below is the code snippet -- class LinkedList { public: int data; LinkedList *next; LinkedList() { } LinkedList(int d) { data = d; } ...
You have to improve more than one thing to keep the code running. Initialize the value of next in constructor. Otherwise you cannot be sure that when LinkedList is created next is set to NULL LinkedList(int d) : data(d), next(NULL) {} Use LinkedList* instead of LinkedList as a temp type. Otherwise you won't be modif...
68,158,107
68,159,336
find and return the sum of all nodes present in a generic tree in c++
I want to find sum of all nodes in tree (not binary) recursively, I have tried it but i am not getting right answer. Generally i struggle understanding how recursion work in a question and i am not able to understand it's working in. Please help int sum(TreeNode<int>* root){ int s = 0; for(int i=0; i<root-...
For a generic tree with n children, you can think of the recurrence relation as: sum(tree) = value(root) + sum(child[0]) + sum(child[1]) + ... + sum(child[n-1]) Then, the recursive solution is simply: int sum(TreeNode<int>* root) { // value(root) int s = root->data; // no. children int n = root->child...
68,158,220
68,160,336
Constructor, destructor, overloaded =operator function, copy constructor do not get inherited. What this exactly means?
Code #include<iostream> struct A { ~A() { std::cout<<"dctorA\n"; } }; struct B: public A { ~B() { std::cout<<"dctorB\n"; } }; int main() { B b1; b1.~A(); } Output dctorA dctorB dctorA if destructor is not inheriting then how I am able to call it through object of B ? a...
What that statement is trying to say, is that class B does not automatically get a constructor B::B(int) when you add A::A(int). Similarly, B::operator=(int) is not automatically generated when you have A::operator=(int). The copy constructor B::B(B const&) can be automatically generated, in which case it expects A::A(...
68,159,746
68,160,045
How to use template in C++?
I have two very similar classes Their function name are exactly same In another method,I called them and their functions and I want my code more concise So I use template Like this: void method() { if(...) { classA *a = new classA; a.f1(); a.f2(); ... } else if(...) { clas...
You might transform void method() { if (...) { classA* a = new classA; a->f1(); a->f2(); // ... } else if (...) { classB* b = new classB; b->f1(); b->f2(); // ... } } into template <class T> void common(T* t) { t->f1(); t->f2(); // ... } void meth...
68,159,961
68,160,042
The result is not same as I expected
The answer that I want should be 88.5 but it turns out to be 3.60434e+006. I think there's no problem with my quotient formula. What should I do? #include <iostream> using namespace std; int main() { int Grade_one, Grade_two; int Average = Grade_one+Grade_two; double average = Average/2; cout<<"Pleas...
Grade_one and Grade_two undefined when you first use them. You also need to cast Average to double if you want the result to be double as well. #include <iostream> using namespace std; int main() { int Grade_one, Grade_two; cout<<"Please input your Grade No.1: "; cin>>Grade_one; cout<<"Please input ...
68,160,131
68,160,176
How do I get user input on a class object
I have this simple code for Class training. It mostly looked up from a book though. What I'm trying to do is take user input on gradebook1 and gradebook2 object. I don't know even if it's possible so I'm seeking your precious help. #include <iostream> #include <string> using namespace std; class GradeBook{ public: ...
Almost the same as your displayMessage(), only that is should not be a const member: std::istream& input(std::istream& is = std::cin) { // Default argument is >> courseName; return is; // It's good practice to return a reference to input stream } Considering this, you may want to change your displayMessage():...
68,160,303
68,188,958
UE4 setting sprite by using C++
I didn't figure out how can i set a sprite in actor class constructor by using its reference. Reference is "PaperSprite'/Game/cc/combat/units/archer_Sprite_0.archer_Sprite_0'" I want to make this sprite static. I think should use ConstructorHelpers::FObjectFinder . When i run the code below, i got this error: sprite = ...
I want to make this sprite static. ConstructorHelpers::FObjectFinder is for finding an asset. In case of movement would be: sprite->SetMobility(EComponentMobility::Type::Stationary); I tested the code below without any problem. Are you sure ConstructorHelpers::FObjectFinder... is causing the error? static Constructo...
68,160,803
68,164,679
Uninitialized member not caught by compiler. Is it a bug?
As a bad c++ programmer, I encountered this segfault today: an uninitialized shared_ptr gave a NULL, and my program crashed. With normal class members I get warnings or errors if the member is uninitialized. But not in this case. I've produced a repro below. In debug mode this segfaults. I get no compiler errors or war...
an uninitialized shared_ptr ... I think that the compiler should error out and say that you need to initialize the private wooo It's not uninitialized. It's just default-initialized. By its default constructor. To nullptr. A not-explicitly-initialized shared_ptr is equivalent to a raw pointer like Wooo *wooo = null...
68,161,303
68,166,308
Given an integer K and a matrix of size t x t. construct a string s consisting of first t lowercase english letters such that the total cost of s is K
I'm solving this problem and stuck halfway through, looking for help and a better method to tackle such a problem: problem: Given an integer K and a matrix of size t x t. we have to construct a string s consisting of the first t lowercase English letters such that the total cost of s is exactly K. it is guaranteed tha...
This is a backtracking problem. General approach is : a) Start with the "smallest" letter for e.g. 'a' and then recurse on all the available letters. If you find a string that sums to K then you have the answer because that will be the lexicographically smallest as we are finding it from smallest to largest letter. b) ...
68,161,440
68,161,509
Is there a way to declare a type alias based on whether i get a single or multiple template arguments? Preferably without specialization
So this code block obviously doesn't work(conditional out of statement scope:D); what i want is, if only a single template argument is passed, i set the type alias to that type, if multiple are passed i set it as a tuple of the passed in types: template <typename... Args> struct KeyPolicy { if constexpr (sizeof...
Yes, you can use std::conditional from <type_traits> for this. #include <type_traits> #include <tuple> template <typename... Args> struct KeyPolicy { using KeyType = std::conditional_t< sizeof...(Args) == 1, // condition std::tuple_element_t<0, std::tuple<Args...>>, // if true std::tuple<Ar...
68,161,565
68,302,719
how to make our own Point Type with PCL 1.9
I was following this tutorial to make it. But I think it is deprecated since you have to #include <pcl/memory.h> Which has been remove since PCL 1.8. I didn't find other tutorial to bypass this problem. I need to make a new Point Type which can contain 15 other scalars as parameter in addition to its XYZ coordinates, ...
After struggling a bit here's how I solved it : You DO NOT #include <memory.h> It seems to be deprecated for the reason I've mentionned. I suggest you to follow this tutorial Therefore if you create your own point type your code will look like this : struct MyPointType { PCL_ADD_POINT4D; // prefer...
68,161,814
68,161,842
String vs Char array; Why I'm getting diffrent results?
I have saved 2 inputs in my file, 1st: Hello 05 and 2nd: Ciao 07. When I'm using std::string for assigning my string(in class), then code outputs correctly for first string and first integer value but for second string it gives some garbage value or some blank spaces, and when I used char array instead of std::string b...
sizeof(*this) is not related to the number of characters in the std::string but would be related to the number of elements in char text[20];. The number of characters you need to copy for the std::string case is text.size() + 1, the extra one is for the NUL terminator. (You need to to take care to make sure your stream...
68,161,948
68,161,995
Replace for-loop with alrorithm (c++)
i'm new to c++ and i'm facing the following problem: I have the following for-loop within a function: bool PlayerSea::allShipsDestroyed() const { bool destroyed = true; for (auto const & ship : ships) { if (!ship.isDestroyed()) { destroyed = false; } } return destroyed; } Th...
It looks like you want to check if all ships are destroyed, so you should use std::all_of. bool destroyed = std::all_of(ships.begin(), ships.end(), [](const Ship& ship){ return ship.isDestroyed(); });
68,162,827
68,163,014
Manually link and compile C++ program with SFML (macOS)
I am trying to create small C++ program with SFML and I don't want to use the Xcode template. I am using VSCode. I downloaded SFML for Mac, and copied the headers and dylibs to my project directory like so: include/ <- copied contents from the include directory (SFML dir with all headers) lib/ <- copied contents from...
I needed to tell the linker where to look for the dynamic libraries at runtime by adding these linker options: -Wl,-rpath ./lib More information here: https://gcc.gnu.org/legacy-ml/gcc-help/2005-12/msg00017.html So the full command to compile for example the hello SFML code is: g++ main.cpp -o main -I include -L lib -l...
68,162,937
68,163,011
C++ segmentation fault when creating aligned struct data twice
I am trying to write some c++ code which is crucial for performance. Therefor I am using AVX intrinsics and need to align my data to 32 byte. I am using a struct which look similar to this: (I commented out parts of it to track down the issue) struct Summation { alignas(ALIGNMENT) float summation[HIDDEN_SIZE] {}; ...
I have found the issue already. It turns out its not the alignment but the allocation on the stack. Since the 2d-array is very large compared to the other data contained, it allocates too much memory on the stack and causes a stackoverflow.
68,163,678
68,163,721
assigned twice on const char*
const char* str ="Hello World!" str = "HELLO!" In this code, will the string "Hello World!" be erased from memory or will it be left alone?
This is not specified by the C++ standard. Your compiler can do whatever it wishes here, including not even storing the original string in the first place, and effectively compiling the following code only: const char* str = "HELLO!" Your compiler can prove that performing this optimization has no observable effects, ...
68,163,835
68,163,871
Is it possible to change this recursion to a iteration without stack?
The following code uses depth-first search algorithm to generate permutations recursively, I want to know how to change to iteration equivalent without a stack(Pointers can be used). Note that this is very similar to traversing a tree, I try to use the method mentioned in this link, but it is always unsuccessful. #incl...
You can use std::next_permutation to generate permutations. #include <stdio.h> #include <algorithm> #define N 3 int A[N]; void perm() { for (int i = 0; i < N; i++) { A[i] = i + 1; } do { for (int j = 0; j < N; ++j) { printf("%d ", A[j]); } puts(""); } while ...
68,164,099
68,164,439
QProcess doesn't emit finish signal
QProcess* p = new QProcess; p->setProgram("ping"); p->setArguments(QStringList()<<"127.0.0.1"); connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [=](int exitCode, QProcess::ExitStatus exitStatus){ qDebug()<<"finished"; }); connect(p, &QProcess::stateChanged, [=](QProcess::ProcessSta...
https://doc.qt.io/qt-5/qprocess.html QString hostName = "127.0.0.1"; proc = new QProcess(); connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [=](int exitCode, QProcess::ExitStatus exitStatus){ qDebug()<<"finished"; }); connect(p, &QProcess::stateChanged, [=](QProcess::ProcessState ...
68,164,156
68,166,103
Passing opencv read image to dll c++ function
I am having problems of reading pixel info from c++ function, I can read all other argument so I am sure that my connection are working. My python code are as follows real_img = cv2.imread("215107.jpg", 0) n=real_image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) hllDll=WinDLL(name) hllDll.transform(n,ctypes.c_int(my...
You are passing an array of type np.uint8, the equivalent C pointer is unsigned char*. Replace int** a with unsigned char* a. For testing, you may fill the 4 first elements of real_image: real_image[0, 0] = 1 real_image[0, 1] = 2 real_image[0, 2] = 3 real_image[0, 3] = 4 hllDll.transform(n,ctypes.c_int(real_image.sha...
68,164,206
68,164,233
Why does `catch` catch the throw here?
I'm not really sure what's happening here. Its obvious why the inner catch catches throw 2, but why does the outher catch(int x) catch throw? I thought catch(int x) is supposed to catch integer values only. Is it possible that the second throw throws what was first cought (which is 2)? try { try { throw...
You cannot throw nothing. throw; alone can be used in a catch-block to rethrow the currently handeled exception. From cppreference: Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause afte...
68,164,489
68,164,851
What is explanation of vars' addresses
Here is the code: #include <iostream> using namespace std; struct S {}; int main() { S s1, s2; char c1, c2; cout << (uintptr_t)&s1 << '\n' << (uintptr_t)&s2 << '\n' << (uintptr_t)&c1 << '\n' << (uintptr_t)&c2 << '\n'; } Example of output: 19920899 19920887 19920875 19920863 I ...
It is up to your compiler/implementation to decide padding, to decide what direction your stack grows, to decide whether debugging data should be embedded with your variables. C++ makes no such demands regarding what this program would output. "why 12 bytes" would depend on the compiler you have chosen, the target arch...
68,164,731
68,164,759
C++ - problems with vector pointers
Imagine I want to manipulate a single vector with the content of two current vectors, such as: vector<double> b(5),c(5); vector<double*> point; for (int i; i<5; i++) point.push_back(new double(b[i])); for (int i; i<5; i++) point.push_back(new double(c[i])); That's nice until here. How would one manipulate such vect...
Since this is a vector of pointers, the subscript operator returns a pointer: *point[0] = 33.12; // Assigns new value to the pointer // Equivalent: *(point[0]), fetch a pointer and dereference it For example: vector<double*> point; double d = 3.14; point.push_back(&d); *point[0] = 1.61; std::cout << *point[0] << std:...
68,164,825
68,164,906
Define class where variadic template size is 1
I have the following superclass in typedarray.h template<typename... Args> class TypedArray {}; PrimitiveArray, a subclass of TypedArray, will always be constructed with a variadic template of size 1. I'm looking for a way to define PrimitiveArray such that this first and only template argument has a class-scope typen...
What you are doing is not a specialization. If you know that PrimitiveArray will always have only one type template arguments I think you should write the code to reflect this. Something like this should work: template<typename... Args> class TypedArray {}; template<typename T> class PrimitiveArray : public TypedArra...
68,165,156
68,165,222
Overloading >> and << in a class template - linkediting errors and I can't understand why
Here's a test class for demonstrating what I mean. #include <iostream> template <typename T> class Test { public: int s; friend std::istream& operator>>(std::istream& input, Test<T>& test1); friend std::ostream& operator<<(std::ostream& output, const Test<T>& test1); }; template <typename T> std::istream&...
friend std::istream& operator>>(std::istream&, Test<T>&); and template <typename T> std::istream& operator>>(std::istream&, Test<T>&) are unrelated functions (the former is non-template contrary to the later). Simplest fix would be inline definition: template <typename T> class Test { public: int s; friend std:...
68,165,267
68,165,298
why minimum number in an array in an output shows error with loops
I just started learning to code, so its very basic question. Below code gives some random number in minimum in output but gets right answer in maximum. int array[6]={1,2,3,4,5,6}; int maximum=INT_MIN; int minimum=INT_MAX; for(int i=0;i<6;i++){ if(array[i]>maximum){ maximum=array[i]; } els...
You used else if to update minimum, so minimum is not initialized when maximum is updated. You should remove the else. for(int i=0;i<6;i++){ if(array[i]>maximum){ maximum=array[i]; } if(array[i]<minimum){ // remove "else" minimum=array[i]; } }
68,165,315
68,165,448
Why are my if statements not working correctly?
When answered with the first question, if you put in 1962, for example, it comes up with "Close but its 1969" instead of "Wrong, it 1969". In fact, putting anything, including the 1969, which is the right answer, still outputs "Close but its 1969". #include <iostream> #include <vector> #include <cmath> #include <ctime>...
'1969' is a multiple-character character constant and its value is implementation-defined. You should write like 1969 withput '' to express numbers. You cannot use or like that. You should write comparision one-by-one or use std::set for defining sets to find from. Your second else if looks redundant because it seems ...
68,165,819
68,165,852
Main loop doesn't exit SDL2, C++
I'm trying to do a very basic main loop with SDL2 but the window opens and I can't close it. I've written this code: bool open = true; while (open = true) { SDL_Event event; while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_QUIT) { open = false...
You are doing assignment here, making the condition always true: while (open = true) You can use == operator to do comparision, but actually you won't need comparision and you should write simply: while (open)
68,166,139
68,166,635
Best way to store an initializer list in a polymorphic vector
Given the following scenario template <typename T> struct Parent {}; template <typename T> struct Child : Parent<T> {}; struct Bar { vector<???> stuff; Bar(initializer_list<Parent<T>> things) { // store things as stuff } }; I want to be able to write Parent<int> parent; Child<int> child; Bar bar{parent, c...
The first thing to note is that std::initializer_list<Parent<T>> will result in object slicing if some elements are initialized with Child<T> because the underlying array would hold Parent<T> objects. There could be different solutions. For example, you could use a variadic template for the constructor to avoid slicing...
68,166,506
69,227,866
QTextEdit: Tab key changes bullet list indentation
I am using C++ and Qt6. I have a QTextEdit that accepts rich text. When I press the tab key, formatting changes to this: The result I want is the 3rd bullet, but what I am getting is the second bullet. Any ideas? I already implemented a slot that gets called when my "Increase Indentation" button gets called and its th...
bool SummaryWindow::eventFilter(QObject *obj, QEvent *event) { if (obj == ui->textEditor && event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Tab) { this->changeListIndentation(1); return tru...
68,166,896
68,173,177
How do I make mousedrag inside Panel move form window c++/CLR?
I have this System::Windows::Forms::Panel that I want to enable so that if the user click and drags the mouse drags the window around to. Can I do this? Do i have to implement multiple events?
I suggest you should try to call Control.MouseDown Event and Control.MouseMove Event Here is my code, I suggest you could refer to : Point pt; private: System::Void panel1_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { Point mouseDownLocation = Point(e->X, e->Y...
68,167,661
68,167,718
C++ implicit constructor with member's argument list?
Apologies if I am not using C++ nomenclature correctly. I also tried searching StackOverflow and Cppreference but couldn't find information about this case. Let's take the following piece of code. struct Foo{ vector<int> vec; Foo(vector<int> inp) : vec(inp){}; }; struct Bar { Foo foo; Bar(Foo inp) : ...
Foo has a converting constructor taking a vector. In Bar bar2(vec);, vec is implicitly converted to a temporary Foo via the converting constructor, then the temporary Foo is passed to the constructor of Bar as an argument. You can mark the Foo constructor as explicit to prohibit the implicit conversion: struct Foo{ ...
68,167,789
68,167,800
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); Gives me an error
Code: #include <iostream> using namespace std; int main() { int num; while (true) { cin >> num; if (cin.fail()) { cout << "Enter an integer: "; cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); continue; } ...
You have to add #include <limits> to use std::numeric_limits, so add that to the top of your code.
68,167,790
68,169,381
stdout: invalid version 5 (max 0) when attempting to target link a c shared library into a c++ program
I have a C library with a makefile that builds a shared library. Within my own CMAKE c++11 project, I target_link_libraries that shared library and include the header files. When building, during the linking process, I get the following error: stdout: invalid version 5 (max 0) error adding symbols: bad value Based on...
The issue has been solved. While the file resulting from running make appeared to be a shared library and had a shared library extension, it was not in fact being built as a shared library. Added the -shared to the CFLAGS. Error was on my part for not ensuring the file type was actually correct.
68,167,926
68,168,099
How to include System in C++/WinRT console application
Using Visual Studio 2019 16.10.2 how do you include .NET components in a C++ / WinRT Console programme? The indexOf method of IVector requires a UInt32 struct from System. How is the System utilised in this context? Trying to use the namespace results in a "System' : a namespace with this name does not exist" This ha...
When you select the appropriate language from the documentation's language dropdown list in the top right corner (C++/WinRT) you'll see the C++/WinRT-specific signature: bool IndexOf(T const& value, uint32_t & index); You'll need to replace UInt32 bar; with uint32_t bar{};