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
62,829,508
62,829,630
How can I make pair using vector in c++?
I am having difficulty pushing two integers as a pair in vector. I'd like to know where it went wrong. Thank you! #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ vector <pair<int,int>> vec; int s,n; cin>>s>>n; for(int i=0;i<n;i++){ int in1,in2; cin>>in1>>...
Change: vec[i].push_back(make_pair(in1, in2)); to vec.push_back(make_pair(in1, in2)); Also, if you change the order of these two lines: vector <pair<int,int>> vec; int s,n; cin>>s>>n; and reserve size of the vector, you will not have to reallocate memory every time you do a push_back. This will make your pro...
62,830,569
62,849,160
Boolean stop signal between threads
What is the simplest way to signal a background thread to stop executing? I have used something like: volatile bool Global_Stop = false; void do_stuff() { while (!Global_Stop) { //... } } Is there anything wrong with this? I know for complex cases you might need "atomic" or mutexes, but for just bool...
Yes, this will most likely work, but only "by accident". As @idclev463035818 already wrote correctly: std::atomic is not for "complex cases". It is for when you need to access something from multiple threads. So in this case you should use atomic<bool> instead of volatile. The fact that volatile has been part of that...
62,831,290
62,831,449
Segmentation fault with g++ (when using to_string twice on NaN)
Lets assume we have the following setup: # CMakeLists.txt project(Scripts CXX) add_executable(${PROJECT_NAME} script.cpp) // script.cpp #include <limits> #include <string> void func() { const double x = std::numeric_limits<double>::quiet_NaN(); std::to_string(x); std::to_string(x); } int main() { fun...
is this a g++ bug? Yes, it's a bug in the 7.x versions: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86274 It was fixed in version 8 of gcc.
62,831,585
62,834,138
C++ templates to avoid long switches, while calling a function with different return types
I have many functions q1, q2, q3, etc., each with a different return type (int, int64_t, std::string, etc.). I also have a print_result function that prints out their results (and the time they take to run, but trimmed here for simplicity): template <typename T> void print_result(T (*func)()) { T res = func(); std:...
If you can use c++17, here's a "simplified" version of @Klaus's approach. Instead of using a had-made recursive structure, you could use a c++17 fold-expression: template<auto... Funcs, std::size_t... I> bool select_case(std::size_t i, std::integer_sequence<std::size_t, I...>) { return ([&]{ if(i == I) { print_resu...
62,831,743
62,832,282
List to form-encoded parameters in Casablanca
I am using cpprestsdk (casabalanca) to POST a request to a server and I have a list of parameters std::list<std::pair<string, string>> query; query.push_back(std::make_pair("val1", "one two")); query.push_back(std::make_pair("val2", "yo")); that needs to be encoded as form-encoded parameters. val1=one%20two&val2=yo Th...
Found the solution... web::http::http_request request; web::uri_builder parameter; parameter.append_query("val1", "one two", true); parameter.append_query("val2", "yo", true); request.set_body(parameter.query(), web::http::details::mime_types::application_x_www_form_urlencoded);
62,831,813
62,831,896
What does this line of code means in C++ class?
I stumbled upon this piece of code while I was reviewing a repo and couldn't find any reference on the internet. What exactly does it? I assume it specify the default constructor and destructor to be used. But why bother writing this if the default constructor and destructor are implicitely used if there is no custom o...
It simply tells the compiler to use its default generated variants of the constructor and destructor. Note that you don't need to put the constructors and destructors in the source file, you can have those "defaultings" in the header file as well: class foo { public: // Use compiler-generated default implementatio...
62,832,280
62,832,558
c++ 17 filesystem::recursive_directory_iterator() gives error no such directory on mac but works on windows
Configurations macOS: 10.15.5 xcode: 11.5 clang: 11.0.3 Project is set to c++17 I am new to macOS and trying to solve a simple problem.. #include <iostream> #include <filesystem> using namespace std; namespace fs = std::filesystem; int main(int argc, const char * argv[]) { for(const auto& p: fs::recursive_direc...
I see three options: In XCode, go to Product - Scheme - Edit Scheme, then choose the Run target in the left column, switch to Options and use the Working directory to point to the directory in which you want the target executable to be run. This is where your data directory must exist for the program to succeed. Figu...
62,832,371
62,833,536
Creating QScatterSerie with for loop
I need to create several QScatterSeries with for loopand I need to named them seperately. Here is the sample of my alghoritm : for(int serie_count=0;serie_count<50;serie_count++){ QString machine_name = QString::number(serie_count); QString serie= "serie"; QString serie_low = serie.append(machi...
Based on comments to the question, that it is desired to access a QScatterSeries object created in a loop, indexed by the loop number. Can't test the code at the moment QList<QScatterSeries> SSList; for(int serie_count=0;serie_count<50;serie_count++) { SSList.push_back(new QScatterSeries); QScatterSeries &curre...
62,833,167
62,834,701
C++: floor unix timestamp to UTC month
Assume I have a unix timetsamp int timestamp=1594386202; I want to write a function int floor_to_month_utc(int timestamp); that floors a timestamp it to the beginning of the the corresponding month (in UTC). In this example the function shall satisfy 1593561600 == floor_to_month_utc(1594386202) because 1594386202 cor...
As Alan Birtles points out in the comments, this can easily be accomplished in C++20: #include <chrono> int floor_to_month_utc(int timestamp) { using namespace std::chrono; sys_seconds tp{seconds{timestamp}}; year_month_day ymd = floor<days>(tp); sys_seconds result = sys_days{ymd.year()/ymd.month()/1}...
62,833,398
62,833,638
Tell c++ compiler that the argument is not aliased
One of the big differences between C/C++ and Fortran when it comes to speed is that the former languages use pointers which can be aliased and therefore a compiler needs to load in the data at each loop iteration while Fortran's allocatable does not have that problem. C offers the keyword restrict so you ensure the com...
[Is] there is a way to [promise] the [C++] compiler that a specific pointer argument is not being aliased [..] without having to go beyond the standard[?] No, there isn't. You can usually use the non-standard __restrict instead, which was introduced to major toolchains to plug exactly this gap. Portability isn't such...
62,833,801
62,834,296
C++ MFC Libraries in Travis CI
I want to compile a C++ Project with Travis-CI which uses MFC Libraries. Is there a way to do this? Here my .travis.yml os: windows language: cpp env: - MSBUILD_PATH="C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin" install: - choco install visualstudio2019buildtools --package-par...
I found the solution I need to add the correct package-parameters: os: windows language: cpp env: - MSBUILD_PATH="C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin" install: - choco install visualstudio2019buildtools --package-parameters "--add Microsoft.VisualStudio.Component.VC.To...
62,833,957
62,964,975
Visual Studio mkl_link_tool.exe linking error
I'm trying to compile a very simple C++ code in my newly installed Microsoft Visual Studio 2019 and Intel Parallel Studio XE (shipped with the MKL Library 2020). Basically the code creates a 3x3 sparse idendity matrix handle in the CSR format and then destroy the handle: #include "mkl.h" #include "mkl_spblas.h" int mai...
the same problem has been discussed at the mkl forum:https://community.intel.com/t5/Intel-oneAPI-Math-Kernel-Library/MKL-2020-1-VS2019-linking-bug/m-p/1153138
62,834,780
62,838,267
Construct Binary Tree from Parent Array test case failing
Link of the question-[Link][1] Basically we are given an array of integers and it's size. Question is to construct a binary tree from it. Each index corresponds to data stored in a node, and the value of that index is the data of the parent. Value of the root node index would always be -1 as there is no parent for root...
Not sure what you are doing with your getParent method. Also you are initiating a root node with value 0 and not doing anywith it in the loop and then finally you return the root. I suspect your root will always have a value 0. The solution is very simple actually. You initialize an array of nodes with each node's valu...
62,835,131
62,835,186
How to return an array of object C++
So, I'm having this problem. Basically I made a class that contains a string, then a function that makes an array of that class that holds the string and I want to return it to main() but just return wordBank[]; doesn't work. Can someone explain to me why my code doesn't work and what I need to do for it to work? Sorry...
wordBank is local to the readWordList() function. So the second that function ends, wordBank and all the memory it has no longer belong to you. In other words, you're invoking undefined behavior by trying to look at what was returned there. Instead, I'd advise that you simply use a vector: std::vector<wordList> readWor...
62,835,140
62,835,285
How to compare two char arrays in C++?
I would like to compare two values z1 (CRC built from last two concatenated of outWord[10] and outWord[11]), and z2 that is also CRC but calculated upon packet numbers. z1 is as it should be e568 and z2 too, but when I compare both values I got a difference. Can you tell me please where the problem is? #include "Arduin...
You can't compare the contents of two char* string by comparing their pointers, as in if (z1 == z2). This will (almost) always be false, as the strings are in two different memory locations, so their addresses will be different. You should use the strcmp() function, which returns zero if the strings are the same. So: ...
62,835,713
62,835,795
Constructing a vector<int> with 2 string literals
For the following program: #include <vector> #include <iostream> int main() { std::vector<int> v = {"a", "b"}; for(int i : v) std::cout << i << " "; } clang prints 97 0. The ascii value of 'a' is 97, but I don't fully understand the output. On the other hand, gcc throws an exception: terminate called af...
I assume it's using the 2 argument constructor that takes the size and default value No, it's using the constructor taking two input iterators. "a" and "b" could decay to pointer which is valid iterator. As the pointer (iterator) to const char, the dereferenced const char would be converted to int and added as the ve...
62,835,717
62,836,022
C++ setiosflags function manipulator - undetermined indentation
I am studying C++ and I am focusing on cout manipulator functions. By running the following code I get an indentation in the second line containing Gauthier. #include <iostream> #include <iomanip> int main() { std::cout << std::setw(10) << std::setiosflags(std::ios::left) << "Mathieu\n" << "Gauthie...
std::ios::left tells to add fill characters to the right, i.e. it adds few characters to first string, so "Mathieu\n" "becomes" "Mathieu\n ". There is new line character at the end ('\n'), so added spaces are moved to next line (Gauthier). So it's not indentation of second line, those are trailing characters from firs...
62,835,996
63,242,373
Transparent button WinAPI C++
I have a simple window, my main window contains WS_EX_LAYERED flag. I can change opacity of main window but when I try to change opacity of children window I'll get some problem. It's not visible. Maybe I should use another flag in CreateWindowEx(..) or use post-fix A or W? I just need visible main window with 100 perc...
First you need to add a manifest file in the application directory to specify Windows 8 compatibility. <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!--The ID below indicates app support for Window...
62,836,083
62,836,756
Can anyone explain why the outputs are different in C and Java?
{ public static void main(String[] args) { int a = 10; if (a == a--) System.out.println("first\t"); a=10; if(a==--a) System.out.println("second\t"); } } For the java program, output is "first", whereas for the C/C++ program its "second". The functionality of post/pre fix ope...
In java, you get the guarantee that you'll always observing this code printing First, and never Second. In C/C++, you get no such guarantees. Depending on compiler, architecture, OS, and phase of the moon, it will likely print either only First or Second but I'm pretty sure the C and C++ spec make it 'legal' for a comp...
62,836,098
62,840,015
DBus rejecting to send message to a custom service on the system bus
I'm writing a chatbot that (besides other features) allows the admin to send custom message to instant message apps via a DBus call. The chatbot creates a service org.cdpa.cdpachan on the system bus, exposes the interface org.cdpa.bot_send_message and the method send_message. I'm able to get any user to register the se...
<allow send_destination="org.cdpa.bot_send_message"/> this looks like your interface name. You probably want something like: <allow send_destination="org.cdpa.cdpachan" send_interface="org.cdpa.bot_send_message"/>
62,836,421
62,836,475
Thresholding a sensor value
Starting position:I have connected a distance Sensor to an Arduino and would like to get the most accurate values for my project. My idea: My first idea would be to ignore both the highest and lowest measurement and calculate a more or less representative average in order to work with these "corrected values". What I...
Traverse the list once keeping track of the index of the largest value and the smallest value you see. You can do this by first marking the first element (index 0) as both the smallest (min_index) and largest (max_index). Then compare the current with that one. If it's smaller, set the min_index to the current. If ...
62,836,507
62,836,555
How can I make a class method that takes a function as a parameter?
I want to create a method inside a class (but I think this is irrelevant) that sorts a vector according to the bool value returned by a particular function... I read that it is possible but I don't know how to do it... I would like to call the function and put (for example) >, or <, as a parameter, so that I don't have...
You can do this by passing in a function object: template <typename Op> void f(Op op) { // ... if (op(v[i], v[i+1])) // ... } and call it like this: f(std::less{}); // for < f(std::greater{}); // for > Of course, f here is just an example, but you just need to add a template parameter to your own function in t...
62,837,206
62,839,399
how to convert an ostringstream hex string character pairs to a single unit8_t equivalent binary value
I am trying to do the following: I have an assembled ostringstream object that contains a hex payload to be transmitted. Say, it might be 03125412349876543210af (this is representing the data using hex convention in my string) This string is representing 11 bytes, so for example the last byte to be transmitted is ...
In example 2 you are extracting a uint8_t, 8 bits, so one char from the string, the 5. In example 3 is the same, you extract the first char, so the w. For the last example, it prints a char (8 bits), 95 is the ASCII - character. If you want to show the number, cast the value to int. value4 = (uint8_t)value1; cout << (i...
62,838,175
62,838,213
Program exits before executing rest of the program
I am trying to create a students program but it stops after I put the 4th name, it doesn't allow me to put the grades neither shows the list at the end... #include<iostream> using namespace std; int main() { string name[4]; double g1[4],g2[4],avg[4]; int cont; for(cont=1;cont<=4;cont++) { ...
The two loops for(cont=1;cont<=4;cont++) is wrong because you can only use indice 0, 1, 2, 3 for 4-element arrays. You should use for(cont=0;cont<4;cont++) instead and change cout<<"STUDENT "<<cont<<"\n"; to cout<<"STUDENT "<<(cont+1)<<"\n";. Another option is to add one more elements to each arrays. First elements of ...
62,838,193
62,840,468
clang-tidy 10 is ignoring my NOLINT commands
clang-tidy v10.0.0 appears to ignore my NOLINT or NOLINTNEXTLINE instructions. Using this trivial compile_commands.json: [ { "directory": "/home/cmannett85/workspace/scratch/build", "command": "/usr/lib/ccache/g++-10 -g -Werror -Wall -Wextra -std=c++2a -o main.cpp.o -c /home/cmannett85/workspace/scratch/main.cpp",...
The clang-tidy program can sometimes turn up false positives, or otherwise identify areas problematic that maybe (given your platform) are known implementation defined behavior that may not necessarily be compliant with the standard. You can have clang-tidy ignore those sections by passing in a command-line define, suc...
62,838,880
62,844,670
Difficulty understanding someones source code to a solution of an IOI problem
Here is the link to the problem: https://ioi2019.az/source/Tasks/Day1/Shoes/NGA.pdf Here is a brief explanation about the problem statement: You are given an integer n in the range 1≤n≤1e5 which will be representing the amount of positive integers inside of the array, as-well as the amount of negative integers in an ar...
int r = ord[i][j + sz(ord[i])/2].second; We've sorted the tuples of one shoe size in a vector of <size, idx>, which means all the negatives of this size take up the first half of ord[i], and all the positives are in the second half. if (l > r){ swap(l, r); ret++; } After our sort on size, the indexes of each corr...
62,838,950
62,839,788
2D rotation of a quad
I am working on a basic simulation program using C++ and I have a renderer that uses OpenGL. I am rendering quads on the screen which have a dynamic location in the simulation. My goal is to change the orientation of the quad when it is moving in the simulation. For each quad, I have a variable (m_Rotation) which holds...
I believe the correct solution should be as follows: Let's call the two angles from and to. I assume both are in positive degrees as per your question. There are two cases: the absolute distance |to - from| is less than 180. This means there is less degrees to travel by to - from than in the other direction, and that ...
62,839,108
62,889,840
Internal vs External Mapping of IDs to file paths from function perspective
An sf::Sprite can share the same sf::Texture object with multiple sf::Sprite objects, so I want to design a Texture Manager to not the same texture multiple times. I'm using an identifier for referring to textures. A TextureID maps a texture to the file path corresponding to the file that contains the texture: std::fil...
I assume, in a broad aspect, you're looking for something like an Asset Manager to load your assets (be it textures, sounds or fonts) only once and use them everywhere. You can use something I used long ago. Make an Asset Manager class which will have your textures in a map. Something like this: class TexManager { publ...
62,839,776
62,839,934
Is it possible to replace an array by list of variables in C++?
I'm in a situation where I need to define a function "fun" in terms of variables s12 and s23. Then in main function, I need to replace these variables (s12 and s23) by array "arr[ ]" defined in function "mn1". Example is here, int fun(int s12, int s23) { ...
The scenario shown in your code is extremely simple, so you shouldn't overthink it. The function mn is modifying the elements of its ar parameter, which correspond to elements of the ar array in main. So, just pass the elements of ar into the call to fun: int Fun=fun(ar[0],ar[1]); You can even ignore the return value ...
62,839,883
62,841,357
Template ReadProcessMemory with dereferencing
So I have a template function using ReadProcessMemory to read my game from an external program for debugging. This is the function: template<typename T> T read(DWORD addy) { T buffer; ReadProcessMemory(targetProcess, (LPVOID)addy, &buffer, sizeof(T), NULL); assert(buffer != NULL); return buffer; } Now ...
DWORD addy should be DWORD_PTR addy, or even void* addy. And the assert() is useless. You need to check the return value of ReadProcessMemory() instead. In any case, you can't avoid reading multiple values. The game has multiple pointers, you need to read them individually and follow the addresses, just like the game ...
62,839,896
62,839,928
boost::python memory error with dynamic array and delete operator
I have this code that I'm using to test the speed of the C++ code vs. the original python code (I used a pointer array to make sure that the data is in a single continous block and because a vector has to make copies when it grows, which takes O(N) time): void MyClass::test_packet(){ time_t t1; time(&t1); P...
Some incorrect code here for(int i = 0; i < 336000; i++){ for(int j = 0; j < 18; j++){ int N = 18; // allocate memory for 18 objects in a continous block packets = new PacketInfo[N]; // create the packetInfo objects packets[i] = PacketInfo(i, i); If i is greater than 18 (whi...
62,840,020
62,840,088
Can not knowing whether something is elided introduce undefined behavior?
Say we have a struct that has a member pointer that conditionally points to either an internal array, or to somewhere on the heap, like this: struct Ex { char* p; char data[14]; bool is_heap; Ex() : p(&data[0]), data(), is_heap(false) {} //etc... }; Now consider this function Ex...
In all cases where copy-elision is not mandatory, you have undefined behavior when you do: auto ex = ... ex.data[0] = 'h'; std::cout << ex.p[0]; From c++17, this function: Ex f1() {return Ex();} is guaranteed to do copy-elision, so the above code is fine if ex is the result of f1(). In general, I recommend not rely...
62,840,135
62,840,487
C++ Error C2600: Cannot define a compiler-generated special member function (must be declared in the class first)
I'm receiving C2600 error (in title) when compiling a simple program making use of custom copy constructors. My .h file is #pragma once namespace uiuc { class Cube { public: Cube(); double getVolume(); double getSurfaceArea(); void setLength(double length); private: ...
You didn't declare the constructor in your .h file. It should look like this: #pragma once namespace uiuc { class Cube { public: Cube(); Cube(const Cube& obj); // This was missing. double getVolume(); double getSurfaceArea(); void setLength(double length); private: ...
62,841,191
62,841,386
An array of pairs instead of an STL map - possible? What are the pros and cons?
Why are c++ standard maps very famous for, whereas an array of pairs is also similar those? When would it be better to use c++ standard maps, and when to use an array of pairs? Or are the applications similar for both?
Why are c++ standard maps very famous for, whereas an array of pairs is also similar to those? The following table should give you a small idea, where to use c++ standard maps (only choose some) rather an array of pairs. When would it be better to use c++ standard maps, and when to use an array of pairs? You can ...
62,841,292
62,841,321
Why doesn't the exception quit the program?
This is my custom exception: class MyException { public: MyException() :message("..."){} const char *what() const {return message;} private: const char * message; }; This is the class: Class MyClass { void function() { // [...] if (condition) throw MyException(); // ...
You caught the exception that is why the program didn't crash. The point of exception handling is to catch exceptions and handle them gracefully.
62,841,404
62,946,883
Looks like is_nothrow_constructible_v() is broken in MSVC, am I wrong?
Edit: Here is better code to reproduce. All MSVC versions below 19.20 fail to compile the test. This problem is related to this SO post. I've noticed my app getting terminated when logic under inplacer throws an exception. Here is the code to reproduce: #include <optional> struct S{}; S foo() { throw "oh, noes..."; }...
It is a known bug. Fixed in msvc v19.16.
62,841,552
62,841,593
Why does including windows.h create syntax errors, preventing instantiation of a class? (C2146, C2065)
(Platform details: Windows 10, Visual Studio C++ (MSVC 14.26.28801)) Here's a basic repro. Consider the following program that works fine: struct Rectangle {}; int main() { Rectangle rect {}; } Compiles and runs as expected. But now if we introduce the import to windows.h like this: #include <Windows.h> struct R...
Derp okay, found the answer. I was using Rectangle as a "hello world" example. Turns out windows.h already includes a "Rectangle", meaning the symbols collide (https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-rectangle) The implicit "everything from windows.h is available in the global namespace now...
62,841,600
62,841,727
Using fold expression with std::apply on two tuples
I just started learning C++17 fold expressions. I understand that it is possible to apply a fold expression to a tuple, like in the following example (inspired by replies to this question): #include <iostream> #include <tuple> int main() { std::tuple in{1, 2, 3, 4}; std::cout << "in = "; std::apply([](auto...
You can apply twice: auto out = std::apply([&](auto&&... x){ return std::apply([&](auto&&... y){ return std::make_tuple(op(x, y)...); }, inY); }, inX); Or you can use an index sequence, easier in C++20 since we have more generalized lambda syntax, though still fairly dense: auto out = [&]<size_t... Is>...
62,841,661
62,841,922
How to set Socket File Descriptor with FD_SET Unix in C / C++
I’m currently working on a socket programming project. Let’s assume: fd_set fd_in; Now I would like to set the file Descriptor for the select function: FD_SET(socket_fd, &fd_in); Is that the right way ? Then I use the select function: int rc = select(socket_fd + 1, &fd_in, NULL, NULL, NULL); Having done some researc...
The appropriate manual pages are available on line, for example here. Nevertheless, it might not be clear to you that before adding any file descriptors to your fd_set, you should first clear it: FD_ZERO(&fd_in); Then, yes, you use FD_SET() just as you present in the question: FD_SET(socket_fd, &fd_in); That assume...
62,841,671
62,851,481
Getting consistent callgrind output over multiple runs
I've been using valgrind to do some profiling on a C++ codebase, and based on my understanding it's performing sampling of individual calls to build its profile data. As a result, I can profile the same application twice using something like this: valgrind --tool=callgrind myprogram.exe and get different results each ...
callgrind does not use sampling technique. Instead, it exactly "counts" the instructions that are executed. So, if a program is run twice under callgrind and does exactly the same, then it will give the same result. However, as soon as your program is doing non trivial things (e.g. uses a lot of libraries), such lib...
62,841,766
62,841,825
C++ nested if statments, basic currency exchange
I have a simple C++ issue with my if statements, the program runs the values as the initial if parameters rather than performing the else if. Also I tried to code so that if the result of the function equaled 1 it would type out a grammatically correct statement is there a better way of doing that other than using anot...
When you type if (currency == "yen" || "y"), you probably want it to mean "if currency is equal to "yen" or if it is equal to "y", do something". However, this is not what your if-statement actually does. The if-statement if (currency == "yen" || "y") first tests if the string currency is equal to "yen", and if not, it...
62,841,830
62,841,964
Handle exception in Visual Studio 2019
I am trying to handle an exception in Visual Studio Community 2019, note that I am not sure if I have an error with my settings or it is because of my code. The exception that I am trying to handle is out_of_range. In order to do it I put it within a try block and catch, but I am unable to handle. When the program runs...
Debug Assertion Failed! Expression vector subscript out of range isn't an exception. That's the debugger telling you your program went out of bounds and stopped you so you could inspect the program and learn how it happened in order to prevent the program going out of bounds. You can't catch this. You need to fix the...
62,841,951
62,842,011
How to use a string literal as a macro argument?
My question is the inverse of this question. I want to write a macro that will accept an integer and a string literal as it's arguments, like so: #define STRING_MAP_ENTRY(value, name) \ {value, std::to_string(val) + " - " + name} STRING_MAP_ENTRY(0, "ENTRY_1") The macro should turn the above call into {0, "0 - ENTR...
Something like this could work: #define STRING_MAP_ENTRY(value, name) \ {value, #value " - " #name} STRING_MAP_ENTRY(0, ENTRY_1) the # before a token will stringify it. As for combining them, adjacent string literals will be combined into a single string.
62,842,049
62,844,447
C++ creating lambda from other constexpr lambdas executed in order can't be constexpr
Let's say I want to create a lambda that executes some other lambdas in order like this: constexpr auto some_func{[]() { // do something }}; constexpr auto some_other_func{[]() { // do something else }}; constexpr auto funcs_tuple = std::tuple(some_func, some_other_func); constexpr auto combined_funcs = do_funcs(...
Make funcs_tuple static. Because it is constexpr, this shouldn't change really change anything about how your code functions, since all calls to whatever function this is should always arrive at the same value of funcs_tuple. (The differences would be if you were taking the address of it for some reason, I guess.) Howe...
62,842,491
62,843,003
Implementing a C++ range-for wrapper for lvalues and rvalues
I've implemented a little helper wrapper for range-for loops that allows iterating over both keys and values of the associative Qt containers like QMap and QHash, extracting each pair as a structured binding, e.g.: const QMap<int, QString> digitMap = { {1, "one"}, {2, "two"}, {3, "three"} }; for (auto [intKey, strVal] ...
Since make_keyval knows if the object passed in is lvalue or rvalue, you can pass that parameter on to your wrapper. #include <type_traits> template<typename C> struct key_value_range_iterator { key_value_range_iterator(const C container) : m_containerRef(container) {} using iterator = typename std::remove_re...
62,842,696
62,842,835
Why can't modify value in object? Also How can I Improve on this Linked List?
I'm fairly new to C++ as I come from java and python. Here is my attempt at linked list. I tried to initialise the Node with data but it didn't work rather in the append function I had to pass in the data for it to show up. How can I improve this, before making sure that the last node pointed to null I had a memory err...
Your program is ill-formed / has undefined behavior because you dereference head (e.g. with if (head->next == NULL)...), although the pointer head is never initialized. Your append should check if head is already set to a value before traversing through all the head->next elements. Adapt the show list accordingly, too....
62,843,438
65,194,261
Any good way to make system call proxy to allow for mocking in unit test?
I am trying to create a proxy class with virtual system call wrappers so that in the functional code, I can define these wrappers to make system calls, but in unit test, making them mock methods. This is my current idea but it feels clumsy. Is there any better way to achieve this? SysCallAgent.hpp #include <string> #in...
The idea is OK IMHO, and the code is fine too I guess with one caveat: you're injecting MockSysCallAgent as unique_ptr so you don't have an access to this object anymore. In GoogleMock, you have to set the expectations on the very same object that is used in the code under test, i.e. the expect calls are the internal s...
62,843,460
62,843,620
C++ dynamically splitting a routine for thread work
The C++ DoWork1 routine below calculates the total of every number between 0 and 1000. Is there any way we can dynamically create 4 versions of this with each version counting a different quarter range i.e. 0-(250-1), 250-(500-1), 500-(750-1) and 750-1000 ? void DoWork1() { int n1 = 0; int p1 = 0; for (int ...
Here's a simple solution based on std::thread. No doubt you can adapt this to your needs: #include <iostream> #include <thread> #include <functional> void sum (int from, int to, int &total_out) { int total = 0; for (int i = from; i < to; ++i) total += i; total_out = total; } int main() { int ...
62,843,849
62,844,082
How do I access the friend function objects with my derived classes in seperate files?
I have 3 separate header files. Class A, Class B is derived A and Class. class A { public: virtual void foo(C ...object...); }; class B : public A { public: void foo(C ...object...); }; class C { public: friend class A; friend class B; private: A *arr[num][num]; }; Arr is pointer of 2D array.The ...
A common way to split your code into separate files is following: A.h #pragma once class C; class A { public: virtual void foo(C c); }; Class A doesn't need any type information of C. The declaration of member function foo doesn't need complete type information but a declaration because the function expects a pa...
62,844,472
62,844,724
I use the function "FillConsoleOutputCharacter" but the application stoped working
I want to make a console application, so i searched for Windows API, and get this code, but it stoped working when i run it, what should i do? Source code: #include "windows.h" #include "stdio.h" #include <conio.h> //console i/o int main() { HANDLE hOut; // 获取标准输出设备句柄 hOut = GetStdHandle(STD_OUTPUT_HANDLE); // 窗...
You are passing NULL to the lpNumberOfCharsWritten parameter of FillConsoleOutputCharacter(), but the documentation says: lpNumberOfCharsWritten [out] A pointer to a variable that receives the number of characters actually written to the console screen buffer. It does not say that NULL is valid for that parameter. S...
62,844,722
62,845,152
Running c++ in Windows as .exe
I wrote a c++ program and converted it to a .exe file with the hopes to let it run on windows without needing to install a compiler. I ran well on my main computer (which has a compiler so it ran as expected) but did not run on another device. The error message shown was "libgcc_s_dw2-1.dll was not found" How can I run...
C++ programs require additional c++ standard and runtime libraries to run. Most linker links to these libraries dynamically. That is some dll are required for running the program. You can run the program from a portable flash drive by copying those dll to the same folder as the application. Alternatively, some linkers ...
62,844,775
62,845,105
Clang bug? Using pointer as template argument
I want to use a pointer as a template argument. Generally, this works fine. But further, I want those pointers to be declared via another template class. I have it working fine on GCC, but it is failing on Clang. Here is a small program to demonstrate (live link): template <size_t ID = 0> struct PointerHolderT { st...
I guess the issue is with thread_local. If I add thread_local to pData as well, it fails to compile.
62,844,843
62,844,960
Why can two objects of class Mat be added without overloading operator +?
From the link: https://docs.opencv.org/trunk/d3/d63/classcv_1_1Mat.html operator+ is not overloaded in the definition of Mat class. However, oprator+ can be used to add two objects of class Mat. It really confuses me.
By consulting the cv::Mat documentation, the functionality you are looking for is under operator=(const MatExpr& expr): https://docs.opencv.org/trunk/d3/d63/classcv_1_1Mat.html#a2a0798475170fb3a23b5bc63686de334 Specifically, this section of the documentation is useful (emphasis mine): This is an overloaded member func...
62,845,166
62,845,226
Convert Array in C++ to String
I know in Java, you can use Arrays.toString() to return a String representation of an Array. Is there a method that serves a similar function in C++?
C++ is not Java. I recommend reading a good C++ programming book and to look into some C++ reference website. Be aware of various dialects of C++ (e.g. C++11 is not the same as C++17). Remember that C++ arrays are homogeneous: all array components have the same type. In contrast to Java, C++ does not have a root type l...
62,845,185
62,846,307
Visual C++ GC Interface How to enable it and which library to include
I started learning GC interface in C++ and ran a few examples available on web in Visual 2019 C++ for below functions: std::declare_reachable std::undeclare_reachable std::declare_no_pointers std::undeclare_no_pointers Each reference above has an example code which got compiled in my VC++ 2019 and successfully execut...
Visual C++ does not implement garbage collection, so the questions of whether/how to enable it or which libraries it requires are moot. The presence of the listed functions does not mean that a GC exists. It only means that VC++ implements the interfaces mandated by C++11 that would allow a GC to work. But there is non...
62,845,247
62,845,361
Function that inserts a space for every Nth character in a string isn't working the way I think it should?
Just to be clear, I know there are solutions for the actual code that produce the result I am looking for, but that is not what my concern is. I am concerned as to why the code that I have already written is not producing the desired output. I wrote this function: string ToBinary(int val, int space) { string str = ...
You need to add num not substract. After that change you also need to protect against inserting spaces beyond the length of the string. This code seems to work for (int i = 1; i + num < str.size(); i++) { if (i % space == 0) { str.insert((i+num)," "); // num -starting at 0- is the number of spaces in th...
62,845,313
62,845,423
Pointer addresses are getting overwritten
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> using namespace std; int d; long long int *arr = (long long int*)malloc(d * sizeof(long long int)); int* func(){ int *p = (int*)malloc(sizeof(int)); *p =5; return p; } int main(){ int *p = NULL; p = func(); d =10; printf("add of...
You clearly think that you've allocated an array of size 10. However when this expression is executed long long int *arr = (long long int*)malloc(d * sizeof(long long int)); d has a value of zero. d is a global variable so by default is initialised to zero. Confusingly there is also another variable called d in main b...
62,845,421
62,860,819
Angelscript transfer array from C++
I need to transfer an array of tiles from C++ to Angelscript, I have tried adding a function that returns an std::vector but it returns this error Failed in call to function 'RegisterGlobalFunction' with 'array<DumbTile> GetTilesAt(int x, int y)' (Code: asINVALID_DECLARATION, -10) my code: std::vector<DumbTile> GetT...
Is DumbTile registered before GetTilesAt() registration? Is array<T> registered before GetTilesAt() registration? Both needs to be registered before you can register your function. Are you using stock array implementation (sdk/add_on/scriptarray/) or your own, std::vector<>-based implementation? When using stock addon,...
62,845,425
62,845,520
Calculate Tree Height at each Node, help me explain this code solution
Here's a code snippet of a solution that calculates height of each node in a binary tree and stores the height in each node. The code traverse the tree recursively, and below is the Node constructor. class Node { public: int height; // to be set by computeHeight() Node *left, *right; Node() { height = -1; left = ...
Imagine a leaf node (left and right are nullptr). Then n->left != nullptr and n->right != nullptr are false so the calculation effectively becomes int leftHeight = -1; int rightHeight = -1; n->height = std::max(leftHeight, rightHeight) + 1; which is effectively n->height = 0; Now because of the way the recursion is d...
62,845,508
62,845,614
Entity reparenting using pointers?
In the game engine that I'm working on, I have a system of parenting entities to other entities. The way it works: Each entity has a pointer to its parent, and a vector of pointers to its children. In my editor, I want to have a feature were you can drag entities around a tree to reparent them. I already have dragging ...
Start by writing an IsDescendantOf() method for your entity class, if you don't already have one: bool Entity :: IsDescendantOf(const Entity * possibleAncestor) const { const Entity * p = m_parent_ptr; while(p) { if (p == possibleAncestor) return true; p = p->m_parent_ptr; } return false; } ...
62,845,538
62,845,627
C++ Why Traits are not available on objects but rather are available as static member variables
My understanding about class Traits is that it is a class that encapsulates a set of types and functions necessary for template classes and template functions to manipulate objects of types for which they are instantiated. In below example why we cannot make use of 'gquiz::container_type' declaration else how would we ...
You can use decltype(gquiz)::container_type Indeed having x::y to be meant equivalent as decltype(x)::y when x is not a type would seem simpler and is something that I also (and I bet a lot others) thought about too. However it's not in the standard and the reason is that ... because it's not in the standard, so doesn...
62,845,605
62,845,618
Print integer from array A based on array B integer?
New to C++. I am looking for advise on the approach to this problem. Given the following array: Array A 1 21 43 54 99 Array B 1 4 5 What I want to achieve: Array B integer is use to find the position of the value in array A. The end result, using the above two array, will be End result 1 54 99 Where array B 1 will e...
So you can iterate over arrB and get the desired values by doing the following: #include <iostream> int main(){ int arrA[] = {1, 21, 43, 54, 99}; int arrB[] = {1, 4, 5}; // iterating over arrB for (int i = 0; i < 3; ++i) std::cout << arrA[arrB[i] - 1] << ' '; return 0; } Output : ...
62,845,666
62,885,445
Constraints and explicit template instantiation
The following code does not compile in all of gcc 10.1, msvc 19.24, and clang 10.0.0: template <int N> struct A { void g() requires (N == 3) {} void f() requires (N == 3) { g(); } }; template struct A<2>; The error is something like error C7500: 'g': no function satisfied its constraints I'm somewhat surpris...
This seems to be a bug in the compilers; I reported it for all three compilers. Visual Studio has fixed this very recently in 16.7 Preview 1. Gcc developers agreed that it is a bug. No word on Clang yet.
62,845,733
62,845,772
Arduino: Custom library produces strange behavior
I am fairly new to arduino as well as C++. I want to make a plant watering system. I have found this tutorial to measure soil moisture. It's in Czech, but you can find a piece of code to handle the moist sensor. This program runs without any problems. I have decidede to enclose this algorithm to a class so it's more re...
So the problem is here Serial.println("constructor ok: " + analogPin); (and all the other places that you have similar code). You obviously think that this is going to convert analogPin to a string and append it to "constructor ok: ". But that's not what happens. Instead what you are getting is pointer arithmetic. The...
62,845,779
62,845,925
push_back to list in loop
I have a problem with pushing elements to a QList when iterating over it. Let's see example code below: typedef struct { int a[2]; } myType; int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; QList<myType> list; // Create list for( int i = 0; i < 1000; i++) { ...
The reason for the segmentation fault is that altering the size of the container that you are looping over in a ranged-based for loop is undefined behavior. Thus the loop needs to be rewritten. Looking at your code, you could still use the ranged-based for, but not alter the list. The following code seems to be equiva...
62,845,797
62,849,128
Why is loading my SDF causing Mobilizer creating a closed loop error
I'm trying to load an SDF into drake but my program throws a std::runtime_error terminate called after throwing an instance of 'std::runtime_error' what(): This mobilizer is creating a closed loop since the outboard body already has an inboard mobilizer connected to it. If a physical loop is really needed, consider ...
This is because currently we only support models that have a strict tree structure. From an SDF file, this tree structure is inferred from the <parent> and <child> tags, which due to this restriction, Drake understands as inboard and outboard bodies in the tree structure (we'll eventually lift this restriction, but pro...
62,845,890
62,849,470
How to set up http header in boost-beast http request?
I am trying to send message with a header using boost http library. I searched for a way to send message with a header but I could not find. what I want to do is following auto const results = resolver.resolve(host, port); beast::get_lowest_layer(stream).connect(results); stream.handshake(ssl::stream_base::client); ht...
Just req.set("key", "I am a header"); It's pretty much the same as the other - standard HTTP - header, but using a custom name. See it Live On Coliru #include <boost/beast/http.hpp> #include <iostream> namespace http = boost::beast::http; int main() { auto verb = http::verb::get; std::string query = "/path"; ...
62,846,391
62,847,626
Algorithm problem: find all sequences popped from the stack
Assume a list of [1, 2, 3, 4] to push to the stack, the possible sequence of popping from the stack is: 1 2 3 4 1 2 4 3 1 3 2 4 ...
In your C++ version, inQueue is passed by copy in recursive calls. This is not the case in your python version where inQueue is to_push. Adding a copy of to_push before calling print_out_stack_seq seems to fix your issue. from typing import List import copy def print_out_stack_seq(to_push: List[int], n, ...
62,846,469
62,846,759
How to pass string to gets_s() in C++?
#include<iostream> using namespace std; int main() { string str; gets_s(str); cout << str << endl; return 0; } When I tried to run the above code it threw an error that no instance of gets_s() matched the argument list. How can I pass an std::string instead of a char[] to gets_s() function if is poss...
Well, there are a lot of answers about std::getline, but in case if you really need to use get_s, you may write such code: size_t length = 10; // Just for example std::string my_string(length, 0); get_s(&my_string[0], length); // C++14 and older get_s(my_string.data(), length); // C++17 and newer
62,846,592
62,846,632
Missing integer when printing out from array after certain length
I have the following code: #include <iostream> using namespace std; int main() { int length = 0; int arrA[length]; cout << "Enter the length : "; cin >> length; cout << "Enter " << length << " integers for array : "; for(int i = 0; i < length; i++) { cin >> arrA[i]; } c...
int length = 0; int arrA[length]; This creates an array of size zero cout << "Enter the length : "; cin >> length; This sets the length variable to a value entered by the user but doesn't change the size of arrA which has already been created. You obviously think that when the length variable changes that the array a...
62,846,689
62,846,750
multiple definition error using namespace
I have created header file abc.hpp which contains a namespace of multiple functions. When I use single source file which includes the header and call the function defined in namespace it works well, but when I call the same function in project where I have to include this header in multiple places, compilation gives me...
You can treat header files as if they are copy-pasted into your implementation files. So by putting function definitions into your headers, those definitions appear in multiple translation units (roughly, compiler .cpp files). This is not allowed - how is the compiler supposed to tell between them if they end up differ...
62,846,748
62,846,813
Why does my adapted Selection Sort algorithm not work in C++
I have code for selection sort which I wrote over a year ago in Python here, But when I tried to adapt it to C++ it just stopped working completely, and the algorithm, which is logically exactly the same, sorts the algorithm differently and prints out a mess. void SelectionAscending2(int array[], int numItems) { in...
Actually you have diverted a bit from the python code. In the python code you have set the length of array (numItems) to actual length - 1 but here you have put the length (numItems) same as the actual length. And also while printing you are printing from i = 1. So that's why your code is not working as expected. S...
62,846,810
62,847,212
Find uncommon elements using hashing
I think this is a fairly common question but I didn't find any answer for this using hashing in C++. I have two arrays, both of the same lengths, which contain some elements, for example: A={5,3,5,4,2} B={3,4,1,2,1} Here, the uncommon elements are: {5,5,1,1} I have tried this approach- iterating a while loop on both t...
First of all, std::set does not have anything to do with hashing. Sets and maps are ordered containers. Implementations may differ, but most likely it is a binary search tree. Whatever you do, you wont get faster that nlogn with them - the same complexity as sorting. If you're fine with nlogn and sorting, I'd strongly ...
62,846,935
62,847,109
How do i find the common node point of 2 single linked lists?
My approach to this question was to use a hashmap for storing the addresses of first linked list and traversing the second array and checking whether i found the address or not .If it is found i would return the node at that address. This would take O(m+n),where m and n are lengths of linked list but here we are using ...
That method is only valid when the input linked lists are the same from the intersection point like : 1 -> 2 -> 3 -> 4 -> 5 12 -> 11-> 10 -> 3 -> 4 -> 5 Here the two lists are the same from the intersection point 3. Only then that algorithm works. Note : This problem is basically given as to find the intersection poi...
62,847,030
62,847,064
Assigning std::vector to pointer inside a method
I want to create a method, which uses std::vectors to build up a collection of data, then do some operations on the data and finally, I want to pass the generated information through a pointer of a given argument as seen in this small example: struct MyStruct { int* list; int entry_count; }; static MyStruct...
You need to make the function local vectorList, static and use the std::vector::data for getting the underlying array via a pointer. void createList(int* list) { static std::vector<int> vectorList; // ... list = vectorList.data(); } However, that makes vectorList to be the only instance in all of your create...
62,847,200
62,847,537
Is it possible to make template specialization for zero template arguments?
Let's suppose I have a class like that: template <typename T> struct S { int n = 1; S(T t) : n(t) {}; S() = default; }; Is it possible to change something so that it would be possible to instantiate S with no template arguments in case if I want to use the default constructor like that S s {};? The best thing I ...
If T is used only for the constructor, you don't need to template the whole class: #include <iostream> struct S { int n = 1; template <typename T> S(T t) : n(t) {}; S() = default; }; int main() { S s1 {10}; std::cout << "Value:\n" << s1.n << std::endl; S s2 {}; std::cout << "Value:\n" << s2.n << std...
62,847,368
62,848,606
why I cannot change the value in loop of `set<set<int>>`
Here is the minimum function of my question: void solve(void) { set<set<int> > test; for(set<set<int> >::iterator it = test.begin(); it != test.end(); ++it) { // (*it)'s type is set<int> right? but why I cannot insert a int into this? it -> insert(1); } } The compiler tell me that no matchi...
Your it->insert(1) attempts to change a set<int> inside the outer set<set<int>>, and in so doing might change the position in which *it should be stored in the outer set, which would breach the class invariants by not keeping the elements sorted. To avoid that, the outer set only gives it const access to the set<int> e...
62,847,490
62,847,913
How can we distribute compiled source code if it is specific to the hardware it was compiled on?
Suppose we take a compiled language, for example, C++. Now let's take an example Framework, suppose Qt. Qt has it's source code publically available and has the options for users to download the binary files and let users use their API. My question is however, when they compiled their code, it was compiled to their spe...
Code gets compiled to a target base CPU (e.g. 32-bit x86, x86_64, or ARM), but not necessarily a specific processor like the Core i9-10900K. By default, the compiler typically generates the code to run on the widest range of processors. And Intel and AMD guarantee forward compatibility for running that code on newer ...
62,847,613
62,848,795
Generate random integers in changing intervals
We can use std::uniform_int_distribution to generate random numbers in a specific interval. However, for my simulation I need a uniformly distributed random integer at each iteration, and the interval is dependent on the outcome of the previous iteration. I'm already aware of some of the tricks (like these) that can be...
A uniform_int_distribution is supposed to be cheap to create but if you are concerned you can supply temporary distribution parameters when calling it using the overload: result_type operator()( Generator& g, const param_type& params );
62,848,098
62,848,489
Execute CMD Command with QProcess and Save it in QString
I wanted to execute the cmd command "wmic share get name" with QProcess and then save the result of the command in the QString variable. In further, I wanted to show it in QMessageBox or ... How can I do that?
You can use QProcess for this. Let's say I want to execute g++. Example: QProcess p; p.setProgram("g++"); p.setArguments({"-O3", "filename.cpp"}); p.start(); // wait for the process to finish executing // returns true on success if (!p.waitForFinished()) { qDebug() << "Failed to exec...
62,848,311
62,848,389
c++ read function getting extra letter
int main() { int len; cout<<"Enter the size of dynamic array you want: "; cin>>len; int file_len; int *new_num; ifstream in("test.txt"); in.seekg(0, ios::end); file_len = in.tellg(); in.close(); if(file_len>len) { int times= file_len/len; for(int i=0; i<times; i++) { ifst...
You are reading C strings. C strings are null terminated, that is they need a null character at the end to indicate how long the string is. Your code doesn't do that. Try this char *n_ch = new char[len + 1]; // one extra for the null terminator in.seekg(0, ios::cur); in.read(n_ch, len); ...
62,848,434
62,849,669
What is the difference between declaring a static variable in a class in the .h file and a "global" variable in the .cpp file
I don't know if my title is expressed with the right terminology, if it isn't, please correct me so I can update it. However this is my question expressed with code examples: What is the difference, when it comes to the keyStates variable, between example A and B? Example A (Where the "keyStates" variable is defined as...
Well, when you have a static member of a class (whether it's a field or a method), it is "global" for the whole class, so that: To access it from anywhere you need to use ClassName::method() or ClassName::field. You can share or restrict access to this member with access modifiers: private, public and ptorected. This ...
62,848,447
62,848,524
How to specify the DLL file that I want my LIB to be linked to? - Visual Studio 2019
I have different versions of the same DLL file and I want to make sure it's linked to the latest version. But inside the LIB file there's only specified the "FileName.dll" which I guess it's checked in various folders until it's found. How can I make sure it uses the one I want? The problem is that I want to use the Op...
LIBs only reference the DLL by name, not by version, path, or any other unique identifier. When your process starts, it resolves its dependency on "FileName.dll" from a specific path search algorithm. Almost always starting by looking for the DLL first in the same directory as the EXE itself before falling back to othe...
62,848,532
62,848,969
CImg library when compiling return undefined reference to `__imp_SetDIBitsToDevice'
I'm using VSCode on Windows 10 with MinGW compiler installed. I've tried using CImg library to edit images (http://cimg.eu/), and when I'm trying to compile code from tutorial (http://cimg.eu/reference/group__cimg__tutorial.html) I get this error: C:\Users\Martini\AppData\Local\Temp\ccBswQ5w.o:tutorial.cpp:(.text$_ZN12...
You need to link to GDI32 on Windows I think. Something like: g++ tutorial.cpp -lgdi32 -o tutorial.exe
62,848,684
62,848,793
Constructor cannot Initialize one parameter when it exits the function
I am against one problem with my C++ code. I am using the Assimp library, and I have one class that has one attribute of type const aiScene*. In the constructor of the class, I assign this value and all works fine, but when I exit the constructor code, the parameter const aiScene* does not have any data assigned I past...
The documentation says The returned data is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon destruction. [Assimp::Importer::ReadFile] When the constructor is left Assimp::Importer importer; and the object scene is pointing to are destroyed. You have to make a copy of...
62,848,821
62,850,384
Thread Join hangs while using `std::call_once`
I am trying to understand why std::call_once and std::once_flag My program #include<iostream> #include<thread> #include<mutex> #include<condition_variable> using namespace std; once_flag once; void test(int i){ if(i==1){ cout<<"will be called again"<<endl; throw exception(); } cout<<"wont...
It seems that this is a bug in gcc (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66146). You can reproduce the issue by inserting a short sleep after constructing t1 in your example, e.g. std::thread t1(caller,1); using namespace std::chrono_literals; std::this_thread::sleep_for(1ms);
62,849,159
62,849,645
Can I use class scope like a namespace instead of prefixing everything with the class name
So inside header files I can do namespace X { doThis(); } and in the implementation file I can do namespace X { doThis() { .... } } But if I have a class class X { public: doThis(); }; Is it possible for me to do something like this in the implementation file class X { doThis() { .... } } instead...
There's the "Java hack"¹, where you "inherit" from the class to get its members into your namespace: class MyUserType : /*protected|private*/ X { void foo() { doThis(); // works } } Of course this only works of the class doesn't define additional (non-static) features that interfere when inherited...
62,849,269
62,849,462
Makefile doesn't use implicit rule on file
I just wanted to write a quick Makefile for a small C++ project, but when I try to build, make says: No rule to make target "obj/main.o" even though my implicit rule should cover that file. I have seen others who had forgotten a slash or something, but I dont't see the problem with this Makefile: .PHONY: run, clean ...
because of $(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(SRCDIR)/%.hpp you can only compile file having both a cpp and a hpp, but your main does not have header (e.g. you have a src/main.cpp but no src/main.hpp) Example : pi@raspberrypi:/tmp/p $ find . . ./bin ./src ./src/main.cpp ./Makefile ./obj pi@raspberrypi:/tmp/p $ make ma...
62,849,484
62,849,591
Can't find the source of the error: 'Undefined symbols for architecture x86_64' Makefile
I am getting this error: g++ -c location.cpp g++ -c place.cpp g++ -c popularplace.cpp g++ -c person.cpp g++ -o main main.cpp *.o Undefined symbols for architecture x86_64: "sim::PopularPlace::arraycounter", referenced from: sim::PopularPlace::PopularPlace() in popularplace.o sim::PopularPlace::PopularPlac...
Static variables need a definition; they are declared in the header but they should also be defined in the cpp file. This is also where you'd initialize them. For example: int PopularPlace::arraycounter{0}; PopularPlace* PopularPlace::places[POPULAR_PLACES] = {}; However, you might consider using an std::vector<std:...
62,849,712
62,849,749
Is this geeksforgeeks trie implementation having a memory leak problem?
I am reading a geeksforgeeks_implementation_of_trie, and i find that the TrieNode objects that are created by new are undeleted, in the main function, there is an undeleted pointer root: struct TrieNode *root = getNode(); and in function getNode() there is also undeleted pointer pNode, is there any memory leak? Is th...
This function implies a contract where the caller of the function is responsible for deleting the allocated TrieNode. There's only a memory leak if the caller does not honor this contract. Since you said this TrieNode is not deleted anywhere in main, there is likely a leak. Unless you can find somewhere this struct is ...
62,849,945
62,850,242
how to set a range to extract the information I want to get?
I am trying to extract a ragne of information from the data. for example, [student1] id: 001 name:red surname:brown phone number:0123456 address: blabla from this data (it's text file), I want to extract all information of this student using regular expression, just by putting in student number 001. here is the code i...
You can read the file and use the following regular expression on the content. With regex_search you can search for the student and iterate over the groups. You can use this regex to find the student and extract its data: \[student\w+\]\nid: *001\nname: *(\w*)\nsurname: *(\w*)\nphone number: *(\w*)\naddress: *(\w*) E....
62,850,908
62,866,708
Getting an empty CSV when downloading from URL in Cpp
My goal is to get a CSV or XLS from a specific URL using Cpp. When opening the following link http://www.centrodeinformacao.ren.pt/userControls/GetExcel.aspx?T=CRG&P=01-01-2007&variation=PT , can see in Browser tools a 302 redirect and the file being actually downloaded from the following URL http://www.centrodeinfor...
Once going to that specific URL, a .xls file downloads. I don't mind getting a XLS instead of a CSV and so changing it to I was able to get the file as expected. downloadFile("http://www.centrodeinformacao.ren.pt/_layouts/CI.GetExcel/SafeGetExcel.aspx?T=CRG&P=01-01-2007&variation=PT", "C:\\Users\\molecoder\\Desktop\\te...
62,850,909
63,154,941
Why does MinGW GCC tolerate missing return types even with `-pedantic-errors`, unlike regular GCC?
Here's the code: main() {} On gcc.godbolt.org, both GCC 10.1 and Clang 10 (with -Wall -Wextra -pedantic-errors -std=c++20) refuse to compile this. GCC: error: ISO C++ forbids declaration of 'main' with no type [-Wpedantic] Clang: error: C++ requires a type specifier for all declarations But on my local machine, MinGW ...
As noted by @ssbssa, MinGW GCC enables -fms-extensions by default, and it's one of the effects of that flag. Compile with -fno-ms-extensions to fix that.
62,851,022
62,851,356
Checking for duplicates in an array using for loop
I am trying to check whether there is any duplicate integer in the user input array. The problem is that the validation of the duplicate does not work properly and I have no idea why it is not showing the desired output. Following is the code: #include <iostream> using namespace std; int main() { int length; ...
The issue in your code is that you are printing out each array element every time a particular element is not matching another element. It seems that you only want to print out whether any duplicate values are found. For this, you can use a bool flag to indicate whether any element is duplicated: bool found_dup = false...
62,851,227
62,851,286
Why accessing out of bounds not producing any error in my code?
This is my function, I have run with -std=c++17 -Wall -Wextra with clang and gcc on godbolt; both compilers did not produced any errors; function returns 0, when empty needle; returns -1 when needle not found and returns index of first occurrence when match. int strStr(string haystack, string needle) { if ( ne...
it should produce error, when I access out of bound No. The behaviour of accessing an array out of bounds is undefined. There is no guarantee that you would get an error. but I have tested same code leetcode platform, it produced runtime error There is also no guarantee that you would not get an error. There are no...
62,851,384
62,851,609
How to search for an exact word?
I'm curious as to if there is a way to find an exact word by itself even if the search is consisted within a word. As you can see below, the output is stating that the word 'day' is found twice, but that's only because 'day' is also used to spelt 'today'. I would like the search to specifically look for the word 'day' ...
Yes, this is possible. But it requires you to decide what are word boundaries. For example, is '-' a word boundary like a space? Or would you consider it as a letter? You may for example filter out non-words, by checking if the found string: starts as a new word (i.e. either we are at the beginning of the string, ...
62,851,441
62,851,561
compute ratio of scaling polygon to get given area of polygon
I have a set of points for a polygon. I can get the area of it. for examples I have polygon.Area() = 1500; now, I need to make that polygon that gives area 1350, how to scale ratio value of it. I try to get it scaling by bounding box ratio. but it does not work. I try this way. but answer is not correct. I Get a Boundi...
Scale_Ratio = Math.sqrt(newArea/oldArea) That's because the ratio will be applied to the area twice -- once when you multiply the width, and once when you multiply the height, so the ratio of scaled areas is the square of the ratio applied to each dimension.
62,851,447
62,851,600
Tracking down unnecessary copies with callgrind
I'm working on C++ project (a ray tracer) and I've been going through and attempting to optimize the codebase. I'm not a C++ expert, and I'm sure I've made lot's of beginner mistakes especially around accidental copies (see below). I've been trying to find hot areas of my code but I notice that the top couple of lines ...
valgrind provides several ways to track down the code that does a lot of allocation/deallocations. Among others, the valgrind memcheck and massif tools provide a way to record the complete set of calls to allocation and deallocation functions. The recorded data can then be visualized with tools such as kcachegrind. Fo...
62,851,470
63,021,088
Using Vulkan-hpp vk::enumerateInstanceVersion() causes segfault
I encountered a weird issue. I can use vkEnumerateInstanceVersion from vulkan.h, but using vk::enumerateInstanceVersion() from vulkan.hpp causes an memory access violation (segfault). I use this function to create the vk::Instance: static vk::Instance createInstance() { loadVulkanGlobalFunctions(); uint32_t ve...
It turned out that the vk::DynamicLoader object created in loadVulkanGlobalFunctions must have its lifetime extended, as it unloads the dynamic library in its destructor. As it is a local variable that happens when loadVulkanGlobalFunctions exits and the stack unwinds. I simply changed it to this: static vk::DynamicLoa...
62,852,144
62,852,379
unexpend for-loop result after change the third part of for-loop
When I use for-loop in my source file, I get a unexpend result. Here is the minimum source file (I hide the head of file and the function of print_set): // the main function int main(void) { set<int> test{3, 5}; print_set(test); for (auto it = test.begin(); it != test.end();) { auto node = test.ext...
From the std::set<T>::extract() documentation: Extracting a node invalidates the iterators to the extracted element. After the call to test.extract(it), the iterator it is no longer valid. Even incrementing it or comparing it to another iterator are not defined operations. The only safe things you can do to it afte...