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
69,686,125
69,686,261
Merge Sort: segmentation fault c++
For some odd reason, I am getting a segmentation fault when I call the merge function. I am using g++ to compile and have tried passing in different data for the parameters, but I still get this issue. #include <iostream> using namespace std; // Merges two sorted subarrays of A[]. // First sorted subarray is A[l..m]....
Try using the below code :- #include<iostream> using namespace std; void merge(int arr[],int l,int m,int h) { int n1=m-l+1; int n2=h-m; int L[n1],M[n2]; for(int i=0;i<n1;i++) L[i]=arr[l+i]; for(int i=0;i<n2;i++) M[i]=arr[m+1+i]; int i=0,j=0,k=l; while(i<n1&&j<n2) { ...
69,686,145
69,689,019
Selection sort in single linked list without using swap
I have been trying to solve the selection sort in single linked list without using swap nodes. Using a temp list to store nodes and assign the current list with a new one //my addlastnode function void AddLastNODE(LIST &mylist, NODE *p) { //Check the list is empty or not if(isEmpty(mylist)) mylist.pHead = m...
Your code does not reduce the list you are selecting nodes from: the selected node should be removed from it. To make that happen, you need a reference to the node before the selected node, so that you can rewire the list to exclude that selected node. There is also a small issue in your AddLastNODE function: it does n...
69,686,201
69,686,325
returning string_view from function
I am writing a lot of parser code where string_view excels, and have gotten fond of the type. I recently read ArthurO'Dwyer's article std::string_view is a borrow type, where he concludes that string_view (and other 'borrow types') are fine to use as long as they "... appear only as function parameters and for-loop con...
is returning the string_view this way unsafe (or UB) in any way, or can I keep on doing this with good conscience? Yes. The way you use it is perfectly ok. The string_view returned by your toString function forms a view on data that will remain intact until the program terminates. Alternatively, is there a better (f...
69,686,829
69,687,040
Why do we need std::boolean and what is the use of it?
Since we already have true and false as the type bool in C++, why do we need the class std::boolean and what's the use of it? Useful links also appreciated.
std::boolean used to be a part of the C++20 draft standard (e.g. it can be found in N4835), but in the actual C++20 standard it is replaced by an exposition-only concept boolean-testable. The change happened around February 2020 as a result of adoption of P1964R2 . In either incarnation it is a concept, not a type. Tha...
69,686,934
69,687,663
Concept checking on struct members
What is the simple, idiomatic way, to check that a specific struct member validates a given concept ? I tried the following and it does not work because { T::f } yields type float&: #include <concepts> struct foo { float f; }; // ok static_assert(std::floating_point<decltype(foo::f)>); template<typename T> conce...
You might want to use macro: #include <concepts> #include <type_traits> template <class T> std::decay_t<T> decay_copy(T&&); #define CHECK_MEMBER(name, type) \ { decay_copy(t.name) } -> type template<typename T> concept has_member_variables = requires (T t) { CHECK_MEMBER(f, std::floating_point); CHECK_MEMBER(i, ...
69,687,078
69,687,159
Operator Overloaded for Array but not working in Main
I wrote a program to add, subtract and multiply two matrices together. I overloaded the operators +, -, and * for this purpose, but when I use them in the main, I get an error which says: no operator "+" matches these operands I can't figure out the problem. Maybe I used incorrect logic to overload the operators for cl...
You've defined the operator + between a MATRIX and a MATRIX[] (i.e., an array of MATRIXs). You should amend the definition to operate on a MATRIX and another MATRIX: MATRIX operator+(MATRIX x); and of course, amend the implementation accordingly. EDIT: As Fabien mentioned in the comments, using a const reference will ...
69,687,260
69,688,508
Undefined symbol in C++ when function which is declared in header is custom defined
I'm building a library for android. eglGetNativeClientBufferANDROID function is available for android .so above 26 but I want the library to support all the versions from API 23. So I'm linking my file with libEGL.so version 23 and dynamically loading the .so at runtime and getting the function from the .so file (this ...
Why eglGetNativeClientBufferANDROID is not being picked up from B.obj? Because the exported method in B does not match the declaration in A. What _DYNAMIC means in libEGL.so and why are the method symbols just the names and no other type info are present? (I think it is because egl only loads the functions to fps dy...
69,687,687
69,688,385
How to print out elements of 2d vector vertically in c++?
I have a simple vector of vectors of integers. The output of the below code will be 1 2 3 4 5 6 7 8 9 10 11 I am trying to figure out how to get 1 6 9 2 7 10 3 8 11 4 5 int main() { using namespace std; vector<vector<int>> a { {1,2,3,4,5}, {6,7,8}, {9,10,11} }; for (int i = 0; i < a.size(); i++) { ...
In this line: cout << a[i][j] << " " ;, you just need to swap i and j. #include <iostream> #include <vector> #include <cstddef> // for std::size_t #include <algorithm> // using namespace std; is bad, so don't use it. int main() { std::vector<std::vector<int>> a {{1,2,3,4,5}, {6,7,8}, {9,10,11}}; std::size_t b...
69,688,016
69,691,118
Why is this program crashing and returning large values?
I'm trying to make a decimal to binary converter but its crashing the program. Could anyone please help #include <iostream> #include <cmath> #include <cstring> using namespace std; char *decToBin(unsigned long,int i=0); int main() { unsigned long n; cout<<"Enter number: "; cin>>n; cout<<decToBin(n)<<e...
Below solution works up to 64 bit: #include <iostream> #include <bitset> int main() { unsigned long n; std::cout << "Enter n:"; std::cin >> n; if(0 == n) { std::cout << n << std::endl; } else { std::string binary = std::bitset<64>(n).to_string(); std::cout<< binary.erase(0...
69,688,096
69,688,850
How do I use SIFT in OpenCV 4.2.0 with C++?
I am using visual studio 2017. Opencv and opencv verison of 4.2.0 is installed and files are generated using cmake. xfeatured2d420.lib is linked with compiler. And also #include "opencv2/xfeatures2d.hpp" #include "opencv2/xfeatures2d/nonfree.hpp" included. Extracting features using xfeatures2d::Sift giving me memory er...
Mat img_1 = imread("C:/Users/Dan/Desktop/0.jpg", 1); Mat img_2 = imread("C:/Users/Dan/Desktop/0.jpg", 1); cv::Ptr<Feature2D> f2d = xfeatures2d::SIFT::create(); std::vector<KeyPoint> keypoints_1, keypoints_2; f2d->detect(img_1, keypoints_1); f2d->detect(img_2, keypoints_2); Mat descriptors_1, descriptors_2; f2d-...
69,688,255
69,688,313
c++: how can I get access to private private attributes in base class from the subclass
I want to create a base class named Form and a subclass named ShrubberyCreationForm the problem is I have to set values to the base class using a subclass. I found a solution to solve it in the constructor but I can't find a way for it for the copy constructor and assignment operator. base class: class Form { priva...
The usual way to do this in C++ is to define a copy constructor in your superclass, that's responsible for copying/assigning to itself. Then, your subclass's copy constructor and assignment operator invoke it to handle the superclass. So, for example, the copy constructor would look like: ShrubberyCreationForm::Shrubbe...
69,688,471
69,688,666
Foreach loop uses more stack memory than traditional for loop?
In one of my programs I was using a for each loop that looked similar to this for(auto component : components) { doSomethingWithComponent(component); } and visual studio complained that this would cause the function to use more stack memory than the maximum, so I changed the loop to: for(int i = 0;i<components.siz...
for(auto component : components) { This is equivalent to having auto component=components[i]; being performed on each iteration of the loop. A (mostly useless) copy is made of each value in the container, on each iteration of the loop. Hence the stack usage. This is avoided simply by using a reference: for(auto &comp...
69,688,581
69,688,655
Accessing captured variables through explicit this parameter in lambda
From declarations / functions / 9.3.4.6 / 6.2 (i apologize on how to cite the specific sentence from standard): An explicit-object-parameter-declaration is a parameter-declaration with a this specifier. An explicit-object-parameter-declaration shall appear only as the first parameter-declaration of a parameter-declara...
The standard doesn't allow it: For each entity captured by copy, an unnamed non-static data member is declared in the closure type. If it's "unnamed", then you can't name it. There's specific language that causes the name of a captured entity to be transformed into a this-based expression, but that's it. So you can t...
69,688,667
69,689,235
OpenFOAM how to remove some elements from a List?
In OpenFOAM, I can access the list of times of my simulation, as follows: const auto& tlist = mesh.time().times(); //or runTime.times(); Just think of this in the context of a custom function object, where you want to access the list of times. When I print that list: Foam::Info << tlist << Foam::endl; and then run th...
Disclaimer, I never used OpenFOAM. Looks like List has iterators. https://cpp.openfoam.org/v9/classFoam_1_1UList.html. So you could try something like this (assuming iterators work like I'm used to from other libraries): const auto& tlist = mesh.time().times(); //or runTime.times(); // assuming operator+ availabl...
69,689,519
69,689,564
Copying Byte Pattern For Floats Does Not Work
I am currently teaching myself c++ and learning all I can about memory. I found out that you can use a char pointer to copy the bit pattern of an int for example and store it in memory with casting: #include <iostream> using namespace std; int main() { int x = 20; char* cp = new char[sizeof(int)]; cp[0] = *((char*...
(int)*cp; first dereferences the pointer, returning a char value, that is now static-casted to integers. This will only work for the range char can store - 0 255 or -128 127 and requires a little-endian system. It may seem that the way how to fix it would be *reinterpret_cast<float*>(cp); or *((float*)cp). Both are wro...
69,689,600
69,706,641
The same assembly code with and without (__restrict) in Visual Studio C++
I would like to compare the effect of producing assembly code in C++ by Visual Studio with and without __restrict keyword. So, I used the standard C++ example on the Microsoft website as below "https://learn.microsoft.com/nl-nl/cpp/cpp/extension-restrict?view=msvc-160" The main.cpp file contains: //In main.cpp file #in...
The answer is that I should use the /O2 flag when compiling the code. This flag will optimize the code and apply the effect of the __restrict keyword.
69,689,603
69,690,447
Why does gcc can't find opencv.hpp file?
I'm quite new to CMake, but I want to build a test .cpp file that includes OpenCV and shows me an image. I have built OpenCV in the path /usr/local and I have here folder with opencv.hpp file - /usr/local/include/opencv4/opencv2/opencv.hpp. Here is my CMakeLists.txt file: cmake_minimum_required(VERSION 3.0) project(cp...
In order to use a library you must specify the include directory as well as the libs. With find_package (in module mode), in your case it should populate the variables OpenCV_INCLUDE_DIRS and OpenCV_LIBS for you to use. So I recommend to add / alter your code to add the include directory & link the library (such as bel...
69,689,938
69,690,521
QueueUserAPC function not working, reporting error 31 randomly
The following code uses the QueueUserAPC function to add commands to a dispatcher thread in order to synchronize console output. #include <Windows.h> #include <iostream> constexpr auto fenceName = L"GlobalFence"; constexpr auto dispatchCloser = L"GlobalDispatchStop"; constexpr int threadCount = 5; DWORD WINAPI pure(L...
As soon as the loop in pure() receives its 1st APC notification, the loop breaks and pure() exits, terminating the thread. Error 31 is ERROR_GEN_FAILURE, and per the QueueUserAPC() documentation: When the thread is in the process of being terminated, calling QueueUserAPC to add to the thread's APC queue will fail wit...
69,690,358
69,690,765
Problem with throw exceptions when stack are empty ..... Queue / stack implementation
I need to throw an exception when both stacks are empty but i dont know how I should write it. I have to implement a queue with 2 stacks! this is main #include "QueueFromStacks.h" int main() { /* THIS IS JUST TO SHOW YOU HOW #include <stack> WORKS stack<int> st1; stack<int> st2; cout << "Size before push:...
You need to change this: void QueueFromStacks<E>::enqueue (const E& e) { st2.push(e); numElements++; } to this: void QueueFromStacks<E>::enqueue (const E& e) { st1.push(e); numElements++; }
69,690,872
69,690,899
Visual C++ - folder structure
I have started to learn C++ and i stuck in front of MSVC. Have you any idea about why MSVC have this folder structure? What is the purpose 'x64' folder inside 'Hostx86'? enter image description here
Hostx86/x64 means the toolset (compiler, linker, etc) that is running on x86 32-bit host (that is 32-bit x86 applications), but produces x64 binaries.
69,690,969
69,701,037
C++ Exception Thrown while trying to debug
I am trying to learn C++ with a given tutorial. I've tried to write some code. Visual studio says, there's no error, but when I'm trying to start debugging, it does not work. Can someone help me. I am getting the following Exception thrown. Here's the error message: https://prnt.sc/1x6qqgc #include <iostream> #include...
It's solved, thank you for your helps. #include <iostream> #include <string> using namespace std; class Question { private: string text; string choices[3]; string answer; public: Question(string textt, string choices[] , string answerr) { text = textt; for (int i = 0; i < 3 ; i++) {...
69,691,035
69,691,265
Problems with template argument deduction when extending std::span
I am trying to extend std::span to have a bounds checked operator[] (I am aware gsl::span provides this) I have declared my container as follows: #include <span> #include <string> #include <utility> #include <stdexcept> template <typename ... TopArgs> class BoundsSpan : private std::span<TopArgs...> { public: type...
The std::span template parameter list is not compatible with your variadic parameter list. It takes: template <typename T, std::size_t N> class span {...}; However, your class is working in terms of a variadic type list. There is no way for you to propagate the template parameters "up" to the span base when it wants...
69,691,682
69,734,674
Alternate scenes in a QGraphicsView
I have multiple QGraphicsScene objects that should be drawn into a single QGraphicsView at different times. Once I've assigned a scene to a view via setScene member function it's possible to change the viewed scene with another? Is it safe to assign nullptr via setScene if I don't want to show any scene or I have to pa...
It's possible to change the viewed scene with another? You can change the scene whenever you want, the documentation does not indicate a prohibition so you can do it. Is it safe to assign nullptr via setScene if I don't want to show any scene or I have to pass a valid pointer each time? Qt checks if the pointer is vali...
69,691,722
69,691,736
How do we know if a pointer was allocated with new or new[]?
I'm trying to implement a unique_ptr class in C++, but how to know if the pointer we passed to it was allocated with new or new[] without using default_delete (my school standard doesn't allow c++11). I mean when you pass your pointer to the constructor like this for example: unique_ptr<int> ptr(new int[10]); how do y...
You can't tell. And neither can std::unique_ptr. Think about it. If it could be determined automatically, you wouldn't need two kinds of delete. std::unique_ptr<int> ptr(new int[10]); is wrong, since it will call delete, rather than delete[]. Use std::unique_ptr<int[]> ptr(new int[10]); instead, which will call delete[...
69,691,956
69,692,025
Decrementing inside of an if statement C++
I am confused as to how to have equivalent logic without having the the decrement inside of the if statement. if(A && !B && !(C--)) { } I thought that this is equivalent to: if(A && !B && !(C)) { C--; }
In the first example, C is decremented if the first two conditions are true. In the second example, C is decremented if all three conditions are true. The difference is that if !C is not true (the third condition is false), the first example will decrement C while the second will not.
69,691,960
69,785,978
C++ jsoncons : cbor to json
I would like to convert cbor into json using the C++ jsoncons library (https://github.com/danielaparker/jsoncons/blob/master/doc/ref/cbor/cbor.md). But when I print the result to console some entries are weird. My Code: const std::vector<uint8_t> data1 = { 0xa4, 0x01, 0x58 , 0x65 , 0x83 , 0x43 , 0xa1 , 0x01 ...
The values in your output are base64-encoded, but you expect them in hex. See Base64 decode snippet in C++ for help with decoding in C++. Or see this example from the jsoncons documentation.
69,692,056
69,692,090
Prevent heap allocations in a function?
In C++, is there any way to ensure that a function does no heap allocations? I am imagining something like this would be very useful in a non-release build. int doSomething() { enable_no_heap_allowed(); // Do lots of complex work. // Program would crash/assert here if heap is allocated to. disable_no_heap_a...
You could have enable_no_heap_allowed() increment a thread-local int, and decrement_no_heap_allowed() decrement it. Then write a global-new operator that checks the thread-local variable and throws an exception/assert if it’s non-zero, or allocates the requested memory otherwise. Note that this approach isn't a full s...
69,692,150
69,692,178
Mathematical constant cannot be accessed
#include<numbers> int main(){ double x = pi; } on C++ 20 throws the error: error: 'pi' was not declared in this scope I'm fairly new to C++, what could be wrong? What was wrong? The compiler wasn't ready for this. I updated it and added -std=c++20 at compile time.
The constant pi: Requires C++20 And is defined in the std::numbers namespace. You must verify that your compiler implements at least this part of C++20, and provide any required compilation flags for C++20 support, as well as either replace the reference to fully-qualified std::numbers::pi, or add using namespace s...
69,692,722
69,692,954
How can I have a function pointer template as a template parameter?
I am trying to create a class template that expects a type and a function pointer as template parameters. The function pointer is expected to be a member function of the type passed in. I want the user of the class template to be able to pass in a void member function of the type passed in. That member function will th...
C++ doesn't allow non-type template template parameters. That means you can't have a parameter-pack for your member-function pointer parameter. Assuming you're using C++17 or newer, you can use an auto template parameter instead: template<typename T, auto func> public: template<typename... Args> void update(Ar...
69,692,790
69,692,917
Is something::something something() also a way to use scope resolution operator?
I was trying to understand a C++ program which used point cloud library and in that code I came across a strange syntax - pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); I read about scope resolution operator but I am still confused whether or not this ''cloud_normals'' is a function...
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); Here cloud_normals is a shared pointer to a PointCloud which contains pcl::Normal types. Check here. This line is creating an object of type PointCloud<pcl::Normal> and assigning it to the share pointer cloud_normals.
69,692,853
69,693,205
Is C++11's std::thread compatible with POSIX semaphores?
I want to use threads in my C++ application by using the standard C++ std::thread library, however y wanted to use semaphores and using the C++20's semaphores wasn't possible, I wanted to know if POSIX semaphores <semaphore.h> is compatible with C++ STD's Threads or I have to change my code in order to use POSIX thread...
The C++ standard library will implement std::thread as a wrapper over pthreads on POSIX systems, so using <semaphore.h> would be fine. Semaphores are usually implemented regardless of the specific threading interface, though the C standard library may do some book-keeping at the same time using pthreads. For this reaso...
69,693,109
69,701,790
Read Access violation when running gui.get<typename>("") with sfml backend in TGUI
I'm currently trying to use TGUI with SFML as the backend, everything works fine when I had this code #include <iostream> #include <TGUI/TGUI.hpp> int main() { sf::RenderWindow window{ {800, 600}, "TGUI window with SFML" }; tgui::GuiSFML gui{ window }; gui.loadWidgetsFromFile("menus/startMenu.txt"); whi...
Ok so I just had to restart Visual studio, and it now works perfectly
69,693,750
69,693,751
How to disable specific compilation warnings from CPP compiler in VSCode? (preferably using build options)
I am using VSCode and ESP-IDF to program Arduino. Some of the Arduino library files are generating warnings such as below. 988/1135] Building CXX object esp-idf/arduino/CMakeFiles/__idf_arduino.dir/libraries/WiFi/src/WiFiScan.cpp.obj /Users/sr/projects/gcp-iot/components/arduino/libraries/WiFi/src/WiFiScan.cpp:45:21: w...
Navigate to your ESP-IDF directory and look for build.cmake file under esp-idf/tools/cmake directory. In the build.cmake file - look for the section called function(__build_set_default_build_specifications) - this contains all the default compiler options that are executed at build time. Include -Wno-unused-function he...
69,693,808
69,694,108
Access vector of vector pointers
I wanted to create a matrix with vectors. In the below code, I created a vector with each entry containing a pointer to another vector(myvector) that acts as columns. I push random values to the myvector (i.e. columns). But when I try to access the values of arrays, it pops an compile error saying "error: no match for ...
This example shows both the syntax you where looking for, and also an example of how you should use std::vector without new/delete. #include <iostream> #include <vector> #include <memory> // using namespace std; <== teach yourself NOT to do this. // https://stackoverflow.com/questions/1452721/why-is-using-namespace-st...
69,693,897
69,694,086
Using std::apply on class method
I'm trying to get the following to compile (g++-11.2, C++20), but I get: error: no matching function for call to '__invoke(std::_Mem_fn<void (Foo::*)(int, double)>, std::__tuple_element_t<0, std::tuple<int, double> >, std::__tuple_element_t<1, std::tuple<int, double> >)' 1843 | return std::__invoke(std::forward<...
I recommend using C++20 bind_front, which is more lightweight and intuitive. Just like its name, member functions require a specific class object to invoke, so you need to bind this pointer to Foo::bar. void bar_apply() { std::apply(std::bind_front(&Foo::bar, this), std::tuple<int, double>(1, 5.0)); } Demo.
69,694,109
69,694,187
Why g++/clang++ throw error "does not give a valid preprocessing token"
Below is minimal code to reproduce problem. #include <chrono> #include <functional> #include <iostream> using namespace std; class Test { public: Test() {} void test1() { cout << __func__ << endl; } void test2() { cout << __func__ << endl; } void testPrepare() { cout << __func__ << endl; } private: }; #defin...
According to the C spec: each instance of a ## preprocessing token in the replacement list is deleted and the preceding preprocessing token is concatenated with the following preprocessing token. ... If the result is not a valid preprocessing token, the behavior is undefined. So using ## in such a way as to not creat...
69,694,151
69,694,220
How to find the power set of a given set without using left shift bit?
I'm trying to figure out how to implement an algorithm to find a power set given a set, but I'm having some trouble. The sets are actually vectors so for example I am given Set<char> set1{ 'a','b','c' }; I would do PowerSet(set1); and I would get all the sets but if I do Set<char> set2{ 'a','b','c', 'd' }; I would do P...
Your if test is nonsense -- it should be something like if ((i / static_cast<int>(pow(2,j))) % 2) you also need to move the insertion of temp into result after the inner loop (just before the temp.clear()). With those changes, this should work as long as pow(2, card) does not overflow an int -- that is up to about car...
69,694,519
69,699,993
How to sort map using comparator with reflection in original map?
How to sort the multimap using comparator. It should be reflected in the multimap container #include <bits/stdc++.h> using namespace std; // Comparator function to sort pairs // according to second value bool cmp(pair<string, int>& a, pair<string, int>& b) { return a.second < b.second; } // Function to s...
Basically the answer has been given in the comments already. I will summarize again and show an alternative. The background is that we often want to use the properties of an associative container, but later sort it by its value and not by the key. The unsorted associative containers, like std::unsorted_set, std::unorde...
69,694,630
69,694,775
Why do I get the error "use of deleted function 'class : : class()"
#include <iostream> using namespace std; class student { protected: string name; int roll; int age; public: student(string n, int r, int a) { name = n; roll = r; age = a; } }; class test : public student { protected: int sub[5]; public: void marks() { ...
student and sports have user-defined constructors, so the compiler does not generate default constructors for them. test and result have no user-defined constructors, so the compiler will generate default constructors for them. However, since student and sports have no default constructors, the generated default constr...
69,694,776
69,694,973
What does this strange number mean in the output? Is this some memory Location?
The node Class is as follow: class node { public: int data; //the datum node *next; //a pointer pointing to node data type }; The PrintList Function is as follow: void PrintList(node *n) { while (n != NULL) { cout << n->data << endl; n = n->next; } } If I try running it I get al...
As described in the comment by prapin, third.next is not initialized. C++ has a zero-overhead rule. Automatically initializing a variable would violate this rule as the value might be initialized (a second time) later on or never even be used. The value of third.next is just the data that happened to live in the same m...
69,694,932
69,694,968
Does not flushing a buffer lead to files having incorrect output
In the code below, if I don't flush the buffer using fflush(STDOUT), could it be that FILE2 ends up getting both "Hello world 1" and "Hello world 2" since the buffer might be flushed at the end of the program and it might be holding both those statements by the end? #include <stdio.h> #include <unistd.h> #include <sys/...
The problem is that you work on different levels here. The stdio-system and stdout will have its own buffer which will not be closed or flushed when you do the second dup2 call. The contents of the stdout buffer will still remain and be written when stdout is closed at process termination. So the fflush call is needed ...
69,694,978
69,695,096
String Rev function, strange behavior for out of bounds exception (c++)
I played with the string function,i wrote the following one, obviously I set the first character in the ret string to be written in a place that is out of bounds, but instead of an exception, I get a string that has one extra place . std::string StringManipulations::rev(std::string s) { std::string ret(s.size...
C++ has a zero-overhead rule. This means that no overhead, (like checking if an index is in-bounds) should be done unintentionally. You don't get an exception because c++ simply doesn't verify if the index is valid. For the extra character, this might have something to do with (regular) c strings. In c, strings are arr...
69,695,565
69,707,892
Is there a way to map a 2D array's x and y to a screen's resolution?
I have this SDL & C++ code to render the 24 x 24 array to the screen. int main(int argc, char *argv[]) { // Init SDL_Window *mainwindow = SDL_CreateWindow("window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_W, SCREEN_H, SDL_WINDOW_SHOWN); SDL_Renderer *mainrenderer = SDL_CreateRenderer(ma...
This seems to be a recent open issue. https://github.com/libsdl-org/SDL/issues/4001 In your case the issue is apparently with the top side, instead of the bottom one, but it's the same issue overall. Try leaving out SDL_RenderDrawRect and use just SDL_RenderFillRect.
69,695,664
69,708,742
Strange behavior of CUDA kernel
I am trying to make a simple Cuda application that creates integral image of given matrix. One of the steps I need to do, is to create integral image of every row. In order to do this, I want to assign 1 thread to each row. Function that is supposed to do this: __global__ void IntegrateRows(const uchar* img, uchar* res...
tl;dr: Make your output matrix have larger elements If you integrate/prefix-sum the sequence 1, 1, 1, 1, ... You get: 0, 1, 2, 3, ... and this sequence will wrap around to 0 when you reach the maximum value of your element type. In your case, it's a uchar, i.e. unsigned char. And its maximum value is 255. Add another 1...
69,695,743
69,696,012
How to add 0x padding to a uintptr_t in a variable?
So I'm trying to figure out how can I add 0x padding to a uintptr_t. The current value of it is: 400000. However I would like it to be 0x400000. So currently to achieve this I am adding the 0x padding when I'm printing this out. However how would I go about this so I can store the padded value of uintprt_t? uintptr_t m...
The type of the expression printed in both cases is uintptr_t, so in both cases output stream behaves the same way, i.e. not add the prefix. As an alternative to @RetiredNinja's suggestion in the comments (use std::showbase), you could create a wrapper type with a custom operator<< which would allow you to implement th...
69,695,842
69,696,002
how to add ZERO on beginning of binary number
void to_binary(int x) { while (x) { a4 = x % 2; x /= 2; new_b += a4 * pow(10, g);//g=0 g++; } } I wrote the function of converting a number to a binary number system, but there is one but if the number has leading zero, for example, 0011, then I see only 11 in the console. ...
You did not elaborate what was wrong with std::bitset. For me it seem to do what you want: #include <iostream> #include <bitset> int main() { unsigned long long x = 3; // 8 digits std::cout << "x = " << std::bitset<8>(x) << std::endl; // 4 digits std::cout << "x = " << std::bitset<4>(x) << std::en...
69,696,170
69,837,310
std::variant with const arguments in C++
There is a nice unanswered question about having union with const members: Can you write a copy constructor for a union with const members? One of suggestions there is to use std::variant instead. Indeed, const types must be supported P0086 - Variant design review. The relevant paragraph says: variant<int, const int> ...
As noted in the comment above, the code only started to be rejected by GCC trunk very recently (and is accepted by all released versions of GCC), after I implemented P2231R1. As I said in the bug report, before P2231R1 the libstdc++ std::variant was playing a bit fast and loose with constructing the active member of th...
69,696,245
69,696,378
Why does std::apply fail with function template, but not with a lambda expression with explicit template parameter list?
In looking at std::apply references from cpprefrence we can see that function templates cannot be passed as callable object of std::apply. Let's consider the following function template: template<typename T> T add_generic(T first, T second) { return first + second; } So as the function template can't be deduced in std...
A function template is not a function, just like a cookie cutter is not a cookie. C++ templates create new functions for every set of template arguments. And this is precisely why add_generic is not a viable argument. It's not a function, it cannot be passed around as a value. To obtain the function, the compiler needs...
69,696,368
69,697,073
How to solve a while loop that suddenly terminates itself?
I have code to look for permutations which takes input from the user until the user is satisfied with the amount of input added. However, when receiving more than 4x input, the code suddenly stuck/terminated itself. I've tried changing the array type to dynamic memory, but the result continues to be the same. Strangely...
This line int *Angka = new int(x); creates an integer on the heap with a value held by x which here it is 0. You are accessing memory which you should not, and as mentioned by @fredrik it may cause a buffer overflow. If you want to create an array on the heap you should do int *Angka = new int[x]; This creates an arr...
69,696,504
69,790,679
What's actually happens when we try to extract line in file after which `eof` character is present with istream::getline() and std::getline()
roha.txt I really love to spend time with you. Let's go for coffee someday. Enjoy whole day and cherish the memories. Code-1 #include <iostream> #include <fstream> int main() { char str[100]; std::ifstream fin; fin.open("roha.txt", std::ios::in); for(int i=0; i<=3; i++) { std::cout<<bool(...
To quote the standard, section 21.3.3.4 inserters and extractors [string.io]: Clause 6: […] After constructing a sentry object, if the sentry converts to true, calls str.erase() and then extracts characters from is and appends them to str […] until any of the following occurs: end-of-file occurs on the input sequence...
69,696,793
69,696,840
C++ no instance of constructor matches the argument list e0289
So the code should work, but it is not. How can I fix it? enter image description here #include <iostream> class Button{ private: unsigned width; unsigned height; public: Button(): width(0), height(0){}; Button(unsigned _width, unsigned _height): width(_width), height(_height){}; ...
At least declare the data member title like const char *title; and the constructor like Menu( const char* _title, int _x, int _y, Button _button): Window(_x, _y, _button), title(_title) { std::cout << "Menu has been created." << std::endl; }; Because string literals in C++ (opposite to C) have types o...
69,696,908
69,697,109
How to push strings (char by char) into a vector of strings
This code is just a prototype, how I'm expecting my output.. My program should be able to insert char by char to particular index of vector; This program works fine for vector<vector<int>> #include<bits/stdc++.h> using namespace std; int main() { vector<vector<string>>v; for(auto i=0;i<5;i++) v.emplace_back...
It seems you need something like the following #include <iostream> #include <string> #include <vector> int main() { std::vector<std::vector<std::string>> v( 2 ); v[0].emplace_back( 1, 'z' ); v[1].emplace_back( 1, 'r' ); v[0][0].append( 1, ' ' ); v[1][0].append( 1, ' ' ); v[0][0].append( 1...
69,697,011
69,699,335
Constexpr Sorted Unique Container Set as Array wrapper
I want to create a constexpr container like std::array that is also sorted and all elements are unique. What I want to achieve is to check at compile time if the given data in the constructor are sorted and unique. I believe an std::set interface is more close to what I want to achieve but it is not constexpr (yet?). I...
struct ConstexprSet { std::array<DataType, Size> mData; You can't do that - at the class level, DataType and Size aren't even declared identifiers. Let's declare them (T for DataType, n for Size): template<typename T, auto n> class Set { std::array<T, n> mData; // TODO What I want to achieve is to check at...
69,697,289
69,697,434
Why don't people check if containers allocation failed?
When we declare a std::vector, or std::string, ..., like that for example std::string hello("Hello"); isn't it wrong? shouldn't we do std::string hello; try { hello = "Hello"; } catch (std::exception &e) { std::cout << e.what() << std::endl; return (-1); } Because if I understood how it works, when an al...
Most people know how memory-intensive their app is, but what are you going to do if you can't allocate a string? You probably also at that point can't do much of anything, and you're going to have to exit. When you have actual recovery you can do, people will probably catch all exceptions at a higher level -- several m...
69,697,403
69,697,593
Access violation when the object goes out of scope in switch case
Ok, then. I started learning C++, and my task is to create a process manager with the Win32 API. It is going to look like this: I have a TBuffer class: (Buffer will keep information about the processes) #pragma once #include <wtypes.h> #define BUFFER_SIZE 10 #define WM_UPDATELIST WM_USER enum TProcessState { psEmp...
You're correct in your understanding, case WM_INITDIALOG: { TBuffer Buf(hWnd); Buffer = &Buf; ... return TRUE; // <-- Buf is destructed here, Buffer is now a dangling pointer } To allocate something that lives longer than its enclosing scope, allocate it on the heap using new: case WM_INITDIALOG: { ...
69,697,450
69,698,045
Alternative to Pimpl
I am required to provide a solution to the following problem: A class is published as a library and made available to the world. It is designed in a way which does not use the pimpl approach. Two new data members need to be defined in this class. How can these additional data members be added to the class without break...
My guess would be as follows. Suppose your class contains a pointer data member, say char* x (the type is not important) that is used for thing unrelated to your planned expansion. Your professor wants you to interpret x as a pointer to another thing: struct expansion { char* newX; int newDataMember1; doubl...
69,697,490
69,698,703
Boost datetime posix_time time_input_facet fails to parse single digit day
When using time_input_facet boost datetime posix_time fails to parse single digit day of month. Unbeknownst to me at the time of initial posting, https://github.com/boostorg/date_time/issues/106 describes this issue, as pointed out in the accepted answer. #include <boost/date_time/posix_time/posix_time.hpp> #include <v...
Your program has UB. delete facet; leads to double-free. Further more, you're only using a time input facet. I wondered whether the date input facet would be required in addition. So I extended the example to rule out some of these concerns: Live On Compiler Explorer #include <boost/date_time/local_time/local_time_io.h...
69,697,629
69,697,811
How do I prevent decimals from rounding off when printed in C++?
I'm doing my ICT homework and I ran into this problem: the decimals keep on getting rounded off when I print them. I've already included the <iomanip> header and used the fixed and setprecision manipulators, but it still keeps getting rounded off. Here's my code: #include <iostream> #include <iomanip> using namespace ...
Expanding answer of @eerorika. You can use std::fesetround() to set rounding strategy, as in code below. It outputs 3.1234 as you wished. Possible values for this function's argument are FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD. Try it online! #include <iostream> #include <iomanip> #include <cfenv> int main...
69,697,745
69,697,776
Erasing object from vector causes double free
When i use vector of class B, which contains allocated memory, double free error occurs. class B { public: std::string a; std::string b; int *hehe; B() { a = "Hello"; b = ", World!"; hehe = new int[7]; for (int i = 0; i < 7; ++i) { hehe[i] = i; }...
You did not define the copy constructor or move constructor. So the same value of the pointer hehe is copied from one object to another object and the destructor frees the memory pointed to by the pointer hehe more than one time due to storing the same value of hehe in more than one object. For example the copy constru...
69,698,066
69,698,116
When do we use arrays over vectors in C++ and vice versa?
I saw the following from this link: Vectors are part of STL. Vectors in C++ are sequence containers representing arrays that can change their size during runtime . They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offse...
If vectors can do so much, under what circumstances do we still prefer arrays? A good design is not when there is nothing left to add, rather when there is nothing left to remove. Or introducing extra complexity only when it is needed.
69,698,143
69,746,334
How to fix lock order inversion?
I'm using RAII style locks such as shared_lock and lock_guard but I see that I'm hitting deadlocks. I want to know why deadlocks happen in this case so I used tsan and tsan found that there is a lock order inversion. It outputted a stack-trace and it went over my head. I can't seem find what exactly causing the lock or...
Thanks to Nate Eldredge, I was eventually able to track down the second mystery mutex using GDB backtrace. I was running several lambda callbacks inside the LongRoutine but in same time re-assigning the Lambda callbacks again to the same Library Instance. According to the author of the library I'm using requires the ca...
69,698,294
69,698,936
Should classes manage dynamic memory on their own?
If a class needs to allocate memory dynamically (e.g. std::vector), is it acceptable for the class to simply allocate and deallocate the memory internally, using operator new or malloc? The answer isn't entirely obvious to me. The lack of a system managing the memory allocation like in garbage collected languages is ob...
If a class needs to allocate memory dynamically (e.g. std::vector), is it acceptable for the class to simply allocate and deallocate the memory internally, using operator new or malloc? Usually, we have two kinds of classes: managers of resources (including dynamic memory); "business logic" classes. Most of the tim...
69,698,323
69,698,471
How do I fix this warning - "control reaches end of non-void function [-Wreturn-type]"
During compiling, it shows this warning - control reaches end of non-void function [-Wreturn-type]. I googled and found that this warning shows when you don't return anything in the function. But I couldn't figure out where's the error in my code. Here's my code: #include <iostream> #include <algorithm> using namespace...
You have to know why this warning is shown to understand what to do about it, this warning is shown when your function has a return type but you haven't returned value from one or more exit points of a function. Now see in your function, you return a[i] but consider a situation where your code doesn't go in the else bl...
69,698,769
69,698,898
Why this code is NOT causing redefinition error?
#include <initializer_list> struct Foo { template <typename T> Foo(std::initializer_list<T>) {} template <typename T> Foo(std::initializer_list<typename T::BarAlias>) {} }; struct Bar { using BarAlias = Bar; }; int main() { Foo foo{ Bar{} }; } I believe that a compiler should produce two e...
You have two templates with unrelated template arguments Ts. For the second constructor to be a candidate, T should be deducible, at least. However, in template <typename T> Foo(std::initializer_list<typename T::BarAlias>) {} T is in a non-deduced context. As a result, this constructor will always be rejected thanks t...
69,699,324
69,699,368
Program that finds the number you are thinking doesn't work properly, what is wrong?
Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input ...
You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so: unsigned int search(unsigned int boundInf, unsigned int boundSup) { string magnitude; int b; b = (boundSup + boundInf) / 2; cout << "Is your number <, > or...
69,699,327
69,707,439
V8 c++ - Failed to deserialize the V8 snapshot blob
I'm trying to use V8 library compiled via vcpkg install v8 but receiving the following error: Failed to deserialize the V8 snapshot blob. This can mean that the snapshot blob file is corrupted or missing. I'm testing it on shipped hello-world.cc example: v8::V8::InitializeICUDefaultLocation(argv[0]); v8::V8::Initialize...
For v8::V8::InitializeExternalStartupData(argv[0]); to work, make sure you have the file snapshot_blob.bin in the same directory as the executable you've compiled. Alternatively, make sure you're passing the correct path instead of argv[0]. I don't know anything about vcpkg install v8; it could be that the library you ...
69,699,392
69,699,465
Multithreaded idiomatic find first of substrings in a string using modern C++
It is easy to find a string in a set of strings using set::find or first of a set of strings in a set of strings using std::find_first_of. But I think that STL doesn't handle this case of find_first_of set of strings (substrings) in a string. For low latency reasons I use parallel execution, would you please let me kno...
I think the idiomatic way of doing it would be to use std::find_if. Then you don't need the atomic<bool> either. // return iterator to found element or end() auto find(const std::string & sentence) { return std::find_if( std::execution::par , std::begin(m_Context) , std::end(m_Context) ...
69,699,441
69,699,477
Store struct with deleted copy and move constructor in container
I have a struct with deleted copy and move constructors and operators, but I want to add this struct to a container. How can I solve this problem? class NonCopyable { public: NonCopyable() = default; NonCopyable(NonCopyable &&) = default; NonCopyable(const NonCopyable&) = delete; NonCopyable& operator=(...
table.emplace("test", Data{"data",10}) will still call the move constructor of Data, you need to use std::piecewise_construct to construct the pair: std::unordered_map<std::string, Data> table; table.emplace(std::piecewise_construct, std::make_tuple("test"), std::make_tuple("data",10)); D...
69,699,589
69,701,123
freshly built Ubuntu executable fails with "Invalid argument" (exit code 126)
I've compiled and built a C++ program (that uses SDL2, in case that matters) on Ubuntu 20.0.4, but when I try to run it, it just prints "Invalid argument". If I try to run it via gdb, it also prints "Invalid argument" and then "During startup program exited with code 126." (This before it hits a breakpoint set at mai...
I finally stumbled upon the answer. I was working in a Parallels shared folder, i.e. a folder from the host OS (macOS, in this case) which has been mounted as a drive in the Linux file system (of the Parallels virtual machine). Apparently, running any executable from such a shared folder simply does not work. Copying...
69,699,756
69,700,745
Parse command line arguments string into array for posix_spawn/execve
Given single string cmd representing program command line arguments, how to get array of strings argv, that can be passed to posix_spawn or execve. Various forms of quoting (and escaping quotes) should be processed appropriately (resulting invocation should be same as in POSIX-compatible shell). Support for other escap...
As Shawn commented, in Linux and other POSIXy systems, you can use wordexp(), which is provided as part of the standard C library on such systems. For example, run.h: #ifdef __cplusplus extern "C" { #endif /* Execute binary 'bin' with arguments from string 'args'; 'args' must not be NULL or empty. Command subst...
69,699,854
69,699,907
Switch & Mapping issues - Called object type is not a function or function pointer
I am having issues with my switch function that made use of mapping to call functions from a class that I have created, and a switch function to pick them. void MerkelMain::processUserOption() { std::map<int, void(MerkelMain::*)()> menu; menu[1] = &MerkelMain::printHelp; menu[2] = &MerkelMain::printMarketSt...
All those map's values are member function pointers and needs special syntax to call. For instance for your first map entry you need (this->*menu[1])(); ^^^^^^^^^^^^^^^^ Or use more generic function std::invoke (require C++17 or later) #include <functional> // std::invoke std::invoke(menu[1], this);
69,700,068
69,700,126
When to not use lambdas over normal functions?
I am aware how a lambda works, I use lambdas pretty much everywhere in my code, is there any scenario where I should prefer using normal functions instead of lambdas
When not to use lambdas: When the function is declared in a header and implemented in a .cpp files. Can't do this with lambda. When the function is a template, and you want to be able to manually specify template arguments. Doing this with lambas requires an ugly syntax: foo.operator()<...>(...). When to use lambda...
69,700,210
69,700,396
How to display output in rows of five numbers?
I'm new to programming and I have to display all the prime numbers that are the product of this code in rows of five. After too many hours of trying to find something online, this is what I came up with. This way, not even the prime numbers are being displayed in the end; only 1s all the way. I'd be happy to know what ...
You are seriously over-complicating your output logic. Just have a counter variable declared (and initialized to zero) outside the for loop that does the output and then, every time you print a number, increment it. When that reaches the value of 5, print a newline and reset it to zero. A couple of other points: The S...
69,700,258
69,700,378
While loop with two conditions joined by an AND operator in HLA. Converting C++ to HLA
I want to translate (or manually compile) my program from c++ into HLA. The program reads an inputted number. Then subtracting off three and tens or only tens, determine if that value ends in a zero or a three. Three such numbers in a row win the game! One value that does not end in those numbers lose the game. I don...
Use logical transformations. For example, the statement: if ( <c1> && <c2> ) { <do-this-when-both-true> } can be translated to: if ( <c1> ) { if ( <c2> ) { <do-this-when-both-true> } } These two constructs are equivalent, but the latter does not use the conjunction. A while loop can be taken to if-go...
69,700,465
69,700,594
How to print page by page with cout in C++?
Imagine I have this code: for (int i=0; i<1000; i++) { cout << i << endl; } So in the console, we see the result is printed once until 999. We can not see the first numbers anymore (let say from 0 to 10 or 20), even we scroll up. How can I print output page by page? I mean, for example if there are 40 lines per p...
You could use the % (remainder) operator: for (int i=0; i<1000; i++) { std::cout << i << '\n'; if(i % 40 == 39) { std::cout << "Press return>"; std::getchar(); } } This will print lines 0-39, then 40-79 etc. If you need something that figures out how many lines the terminal has and adapts t...
69,700,503
69,700,832
myProgrammingLab Palindrome Challenge Using Recursion
I'm taking an Intro to Programming class and a good chunk of the material is drilled into our heads through myProgrammingLab. I'm having a little trouble with the concept of Recursion... It's sort of been hit or miss for me. This particular problem has me stumped. When I submit my code, it offers me CTest1.cpp: In func...
Recursion mostly has three main components: a stopping condition (when you reach an array size small enough to be a guaranteed palindrome (0 or 1)), a computation step (e.g. to compare the first and last item of the array and determine whether it makes sense to continue) and a data subset selection for the nested recu...
69,700,628
69,722,545
Simulating a kCGEventOtherMouseDown only works for right-clicking
The following code for right-clicking works: auto event = CGEventCreateMouseEvent(nullptr, kCGEventOtherMouseDown, {x, y}, kCGMouseButtonRight); CGEventSetIntegerValueField(event, kCGMouseEventClickState, 1); CGEventPost(kCGHIDEventTap, event); CFRelease(event); however, the exact ...
I was able to solve this by using kCGEventLeftMouseDown instead of kCGEventOtherMouseDown. This goes in hand with the Apple documentation of kCGEventOtherMouseDown: Specifies a mouse down event with one of buttons 2-31. (left = 0, right = 1, center = 2, extra buttons = 3-31) This also explains why the website register...
69,700,770
69,700,786
Class constructor defining inherited classes constructor syntax error in header file
I have the below code giving me a syntax error on the BindingSocket definition, my understanding was if I wanted to define an inherited classes constructor I continue the BindingSocket definition with BindingSocket(...):Socket(...);, however this gives me a standard syntax error output. #ifndef NETWORKING_BINDINGSOCKET...
The inheritance is given by class BindingSocket: public Socket. The : Socket(...) after the constructor calls the parent constructor and belongs to the definition and not to the declaration. So it has to be: namespace HDE { class BindingSocket: public Socket { public: BindingSocket(...); ...
69,700,806
69,700,949
Handling variadic function arguments of type 'std::size_t'
I am trying to get the hang of variadic function/template parameters. However, in the two functions below, I am very confused as to why SumIndices does not compile (I get the compiler error "expansion pattern ‘std::size_t’ {aka ‘long unsigned int’} contains no parameter packs") while SumValues does. template <typename ...
In first case you have parameter pack. In second case, you have variadic function from C. Variadic templates allow you to type-safely pass different types into your function. Example of print with this: // Create this function to terminate argument depended lookup void PrintValues(std::ostream&){} template<typename TFi...
69,700,985
69,701,133
Why does the loop in openmp run sequentially?
I try run example for scheduling in openmp, but its work sequentially. omp_set_num_threads(4); #pragma omp parallel for schedule(static, 3) for (int i = 0; i < 20; i++) { printf("Thread %d is running number %d\n", omp_get_thread_num(), i); } Result: Thread 0 is running number 0 Thread 0 is running ...
In Microsoft Visual Studio, OpenMP support is disabled by default. You can enable it with the /openmp compiler option. This option can be enabled in the project properties, under C/C++->Language->Open MP Support.
69,701,240
69,701,305
Are the sources added to a library via the add_library command PUBLIC or PRIVATE?
I'm trying to add some more structure to my CMake project. One step of this process is to move source additions to the CMakeLists.txts in a few subdirectories, whereas they are currently added during target creation via add_library. Unlike add_library, however, target_sources gives you the choice between PUBLIC, INFERF...
CMake command add_library interprets its immediate sources as PRIVATE: the sources belongs only to the created target and aren't propagated to the target linked with the library. In general, non-PRIVATE sources has a very limited usage. If two or more targets are linked together and share a source file, then linker usu...
69,701,920
69,702,931
Why is my texture getting rotated by 90 degrees?
I am trying to draw a simple quad with a texture. I am using gluOrtho2d to set up an orthographic projection. I am unable to understand why the texture inside the quad is getting rotated 90° clockwise. The texture is a simple PNG file. This is the problematic code :- #include <GL/glew.h> #include <GL/gl.h> #include <GL...
glVertex*() calls "lock in" the current color/texture-coordinates/position for a vertex and hand off those values to the GL driver: glVertex commands are used within glBegin/glEnd pairs to specify point, line, and polygon vertices. The current color, normal, texture coordinates, and fog coordinate are associated with ...
69,702,266
69,716,583
SDL rect not appearing
I am trying to get an SDL_Rect to appear on screen with a texture from a bitmap. I run this program and the screen is simply white, with no image. #include "SDL.h" int main(int argc, char** args) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window* window = NULL; window = SDL_CreateWindow("window", SDL_WIND...
I got it working, I simply had to add SDL_RenderPresent()
69,702,267
69,702,395
"no instance of overloaded function "transform" matches the argument list" error with parallel execution
I have a seemingly simple problem with C++17. In below code only the last line is producing an error where I am trying to go with a parallel execution: vector<double> v(1000); transform(v.begin(), v.end(), v.begin(), [](double a) { return 2.0 * a; }); // This is fine transform(std::execu...
Found out the problem. Cuda was interfering with it. Switching to a non cuda console project fixed the problem.
69,702,522
69,702,652
Unable to store numbers using vector
vector<int> oper(int A, int B) { std::vector <int> arrayV; int addition = A + B; arrayV.push_back(addition); int mutiplication = A * B; arrayV.push_back(mutiplication); int subtraction; if(A >=B ){ subtraction = A - B; } else(B >A );{ ...
As I and others have pointed out in the comments, you forgot to return arrayV;. Also, your else has the wrong syntax std::vector<int> oper(int A, int B) { std::vector <int> arrayV; int addition = A + B; arrayV.push_back(addition); int mutiplication = A * B; arrayV.push_back(mutiplication); ...
69,702,654
69,704,688
What is the difference between ${CMAKE_CURRENT_LIST_DIR} and . (relative directory)?
I understand the difference between ${CMAKE_CURRENT_LIST_DIR} and ${CMAKE_CURRENT_SOURCE_DIR}, but I don't understand what the difference is between the former and simply .? For example, are there any scenarios where target_include_directories(foo PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) would behave differently than targ...
Simple counterexample: add_custom_command allows you to specify a custom WORKING_DIRECTORY. Passing relative filenames to such a command would be relative to the working directory. Explicitly making them absolute with CMAKE_CURRENT_SOURCE_DIR solves that.
69,702,807
69,702,895
Possible way to find the actual billboard locations in the Billboard Highway Problem [Dynamic Programming]
I've been learning about dynamic programming the past few days and came across the Highway Billboard Problem. From what I can understand we are able to find the maximum revenue that can be generated from the possible sites, revenue, size of the highway and the minimum distance between two certain billboards. Is there a...
Yes, it is possible to write down the sequence of the chosen sites. There are two max function calls. Replace them by own maximum choice with if, and inside branch where current site is used, add current position to list (to the emptied list in the first max clause, as far as I understand) For example, maxRev[i] = max(...
69,702,979
69,702,995
How to make the type of vector in struct determined by the user?
I have this struct that makes multiplication, addition, and subtraction on a matrix of integers. Now I want to make the type of matrix (i.e. the type of vectors) determined by the user of this struct i.e. int, double, long, etc.. struct Matrix { vector<vector<int>> mat1, mat2; vector<vector<int>> mult() {...
I want to make the type of matrix (i.e. the type of vectors) determined by the user of this struct i.e. int, double, long, etc.. You can make your Martix struct to be a template struct template<typename T> struct Matrix { std::vector<std::vector<T>> mat1, mat2; // .... replace all your int with T } Now yo...
69,703,067
69,703,422
Performing calculations on elements, and retrieving index the index of an element in a vector
Here I am trying to perform calculations and comparisons on elements in a vector, finding average, lower value, higher value and difference. I am also having issues printing the index of elements in a vector. #include <iostream> #include <string> #include <vector> enum class OrderBookType{bid, ask}; class OrderBookEn...
computeAveragePrice is a member function in OrderBookEntry but entries is a std::vector<OrderBookEntry>, not a OrderBookEntry so it doesn't have such a member function. I suggest that you move computeAveragePrice out of the class OrderBookEntry, which only holds information about one single OrderBookEntry. You could cr...
69,703,231
69,703,296
How to write in a buffer at specific byte in c++?
I have a char buffer of length 50 bytes. In this buffer, at 20-21 bytes, I want to write a short number, of size 2 bytes, say -1234, specifically at those bytes only? How can I do that?
Looks trivial. Not sure whether this is what you want. #include <cstring> char* pc = ...; short num = ...; std::memcpy(pc + 20, &num, 2);
69,704,747
69,704,937
How to access IP address of HTTP requests using uWS?
I am using uWebSockets to do a project. What I need to do is get the sender IP address out of incoming HTTP Requests. In the documentation I can see IP address can be taken out from the WebSockets. Do anybody have an idea to cast uWS to WebSockets to get the data or is there an other way to get it? #include <iostream> ...
According to the documentation, the remote address is an attribute of the response. Ergo: std::string_view remote_ip = res->getRemoteAddressAsText();
69,704,929
69,704,977
How to reverse a std::list at a given position?
I am trying to figure out how to reverse for example,grades{1, 2, 3, 4, 5, 6} starting at the third element. I know for lists we cannot do (grades.begin() + 2) to obtain the position, but I'm not sure how to go about it. This is what I have so far, where I'm just reversing the entire list: reverse(firstList.begin(), fi...
I know for lists we cannot do (grades.begin() + 2) to obtain the position, but [...] You are right about this. Providing the flexibility of list.begin() + pos means, it is cheap to do that. The std::list iterators(i.e. BidirectionalIterator) can not be randomly-accessed efficiently (i.e. it is expensive). Therefore,...
69,705,223
69,705,565
How can I read a file from a C++ file launched in a Python subprocess?
I'm trying to launch a C++ file using the python function "subprocess". I can begin the execution of the program, but it does not manage to read the data file I put in parameter. However, when I lauch the C++ file directly with the same path to the same data the program works perfectly. Do you have any ideas on why it ...
I think you are adding the datafilePath argument wrongly. Try to add all args as separate list items instead of concatenating (some of) them together as a string. e.g. subprocess.run(["./programName", "-f", datafilePath, (OtherOptionsWorkingFine) ], cwd="./pathToMyProgram")
69,705,494
69,708,672
Translate (Move) the center of TopoDS_Shape to origin
I am working on a step file reader where I load the file and look at its features. What I want to achieve is to move the step file towards the origin meaning that I want the center of the part to be on the origin. By the center of the part I mean the center of the bounding box around the part. However I am having a bit...
I figured out the way so here is the answer Bnd_Box box; BRepBndLib::Add(Old_Original_Solid, box); Standard_Real theXmin, theYmin, theZmin, theXmax, theYmax, theZmax; box.Get(theXmin, theYmin, theZmin, theXmax, theYmax, theZmax); ...
69,706,366
69,706,434
Function pointer to class method as argument
As you can see by my code, I'm trying to create a onClick event for a button that invoke a function from another class (I'm trying to make my custom button class instead of using win32 default ones for testing). But even if this does not throw any error, it just doesn't invoke the given method. This is the function sig...
It just doesn't invoke the given method! The passed pointer to member function has to be called to get in effect. I assume that the Button is inherited from the ButtonsHandler. Then, for instance, you can call with the pointer to member function with this pointer as follows: void Button::onClick(POINT pt, void (Butto...
69,706,413
69,706,796
How to disable long double in boost::math?
I have c++ source file, example.cpp, using some boost::math functions. My boost library is also built. To disable long double in boost::math, I did the following: g++ -DBOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS example.cpp -I<boost_header> -L<boost.*.so> My question is whether do I need to rebuild boost library with -D...
Yes, there might be a difference. However, in practice, there will usually not be: Boot Math docs: Building a Library The first thing you need to ask yourself is "Do I need to build anything at all?" as the bulk of this library is header only: meaning you can use it just by #including the necessary header(s). For most...
69,706,542
69,708,556
Please update includepath error at #include <string_view>
I have the following configuration in c_cpp_properties.json: { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ...
This is for conclusion for this error! * Only GCC 7+ version can use <string_view> https://sourceforge.net/projects/mingw-w64/files/Multilib%20Toolchains%28Targetting%20Win32%20and%20Win64%29/ray_linn/gcc-9.x-with-ada/ does not support 7+ version gcc. However, if you search "MinGW gcc 9 version", you can find upgrad...
69,707,032
69,707,310
C++ async and deferred show no difference in time compared to only async
I am creating a C++ program that uses 100 random number generators. The number generators are split into two groups: ones that create 100 numbers and ones that create 10 000 000 numbers. I am trying to see the difference between: Using deferred launching for the 100 numbers and async for the 10 000 000 numbers. Using ...
using launch::deferred or launch::async the same amount of work still needs to be done the only difference is whether it is done on another thread and the current thread blocks waiting for that thread to finish when you call gotNumbers.get() or whether the result is calculated directly in the current thread when you ca...
69,707,767
69,707,882
How to make a conversion from std::string_view to std::string
How is it possible that this code below with conversion from std::string_view to std::string compiles: struct S { std::string str; S(std::string_view str_view) : str{ str_view } { } }; but this one does not compile? void foo(std::string) { } int main() { std::string_view str_view{ "text" }; foo(str_vie...
The constrcutor you are trying to call is // C++11-17 template< class T > explicit basic_string( const T& t, const Allocator& alloc = Allocator() ); // C++20+ template< class T > explicit constexpr basic_string( const T& t, ...
69,707,960
69,708,337
How to stop crashes in a recursion loop
I made this simple function, but it crashes at p=29. It makes a stopped working error window. Please Help Me #include <iostream> using namespace std; char *primality(unsigned long,unsigned long i=0); int main() { for(int i=0;i<1000;i++) cout<<i<<": "<<primality(i)<<endl; }; char *primality(unsigned long ...
In your primality() function, char *primality(unsigned long p,unsigned long i) { if(i==0) { if(p<=1) return "NEITHER PRIME NOR COMPOSITE"; else if(p==2||p==3) return "\tPRIME"; else if(p%2==0||p%3==0) return "\tCOMPOSITE"; } i=5; if(i*i<=p...