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,022,178
62,022,946
Why am I getting nan as output for the code below?
I am trying to make a calculator for finding the roots of an equation. I used string to get the numbers and then converted the strings with stringstream to their numerical types for the calculation; because I wanted to make a loop so that a user can use the calculator as long as they want until they quit in any part o...
your code fails here: x1= (-b + (sqrt(d)))/(2*a); x2= (-b - (sqrt(d)))/(2*a); because of this: void root_calculator(string stra="", string strb="", string strc="") { int a=0,b=0,c=0; especially because the parameters stra, strb and strc are never used... so you end up dividing by zero....
62,022,482
62,022,573
std::sort causes segmentation fault in operator<
I am trying to sort a list (std::vector) of 3D integer vectors (IntVec). Somehow, std::sort causes a Segmentation Fault in the operator< of IntVec. Here is my code: #include <iostream> #include <algorithm> #include <vector> #include <fstream> struct IntVec { public: long x; long y; long z; // Using ints do...
Your operator's logic is broken (does not satisfy strict weak ordering requirement). The final clause needs a lhs.z == rhs.z too. Otherwise, lhs.z can be > rhs.z but you still get a positive result, leading to an inconsistent ordering. Standard library algorithms put the onus on you to get this right, and breaking the ...
62,022,808
62,099,892
Tesseract always missing a text line in picture
I am trying to extract data from a picture with OCR. I use Tesseract API in C++ to achieve this. The original picture is this: Now the for me important data is this: However the marked blue line is never recognized does not matter what I try. The code to analyze the picture with tesseract looks like this: std::string...
My reference is here. Note: You don't need to deal with preprocess steps because it seems you already have a pure image. It doesn't have noises much. My environment information: Operating system: Ubuntu 16.04 Tesseract version by the command of tesseract --version: tesseract 4.1.1-rc2-21-gf4ef leptonica-1.78.0 libg...
62,023,379
62,023,475
How to alias and instantiate a template function at same time?
I have a template function as following: using namespace std::chrono; using namespace std::chrono_literals; template <typename D> time_point<system_clock, D> makeTime( int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int ms = 0, int us = 0, int ns = 0 ); Normally, I call it like this: ...
You can get a function pointer to the function you want and then use that as your "alias". That would look like: auto makeTimeUS = makeTime<microseconds>; And can be used like: auto us_tp1 = makeTimeUS( 2020, 5, 26, 21, 21, 21, 999, 123 ); But this just lets you change the name. Since it is a function pointer the de...
62,023,435
62,023,565
Do you have to call glfwSwapInterval(1) in an OpenGL program?
I ran my program twice. The first time with glfwSwapInterval(1) and everything was just fine. The second time without glfwSwapInterval(1) and it was using 100% of my CPU. My Question: Is this normal and do I really have to call glfwSwapInterval(1) in order for my program to run properly. The code: glfwInit(); long wi...
If you want to sync your rendering loop to the refresh rate of the monitor you have to call it. The default behaviour is rendering as many frames as possible.
62,023,445
62,034,705
Windows Toast notification is not working with MS CPP sample code
I want to integrate Toast notification in my existing CPP/COM based desktop application. To add this, I have followed the step by step guide given at https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/send-local-toast-desktop-cpp-wrl(added GUID and etc in product.wxs and installed it as ...
But CPP/COM project from this git link is also not able to post the Toast notifications. By checking the official sample, there is a mistake in it. In the DesktopToastsSample.cpp file, the AUMID it registers in the RegisterAumidAndComServer method is "WindowsNotifications.DesktopToastsCpp", however, in the Product....
62,023,995
62,024,380
How to fill in an array with strings?
I'm having a problem filling a special array of strings in an automated way. The strings must be as follows: "01", "012", etc. until you get to "012...XYZ". I had thought of making a "reference" string like this: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" to be able to browse it and create the other strings based on it but...
Just browse the reference string and create the substrings. For that, using std::string::substr is rather useful. Difficult to get an easier solution. #include <iostream> #include <vector> #include <string> std::vector<std::string> get_subs(const std::string &ref) { int n = ref.size(); std::vector<s...
62,024,080
62,024,338
Why is there a value printed and not NULL/0 after incrementing a pointer in C++?
I am fairly new to C++, so excuse if this is quite basic. I am trying to understand the value printed after I increment my pointer in the following piece of code int main() { int i = 5; int* pointeri = &i; cout << pointeri << "\n"; pointeri++; i =7; cout << *pointeri << "\n"; } When I deferen...
The C++ language has a concept of Undefined Behavior. It means that it is possible to write code that does not constitute a valid program, and the compiler won't stop or even warn you. What such code does when executed is unknown. Your program is a typical example. After the line int* pointeri = &i;, the pointer is poi...
62,024,435
62,025,578
How to enable conversion template argument T to const T?
Suppose that I have a following class template <typename T> struct Node { T value; Node* next; }; Often one needs to write code similar to this (let's assume that Sometype is std::string for now, although I don't think that it matters). Node<SomeType> node = Node{ someValue, someNodePtr }; ... Node <const SomeType> c...
Is there a better, "proper" way to do it? There must be since your solution both has a weird behavior and is also invalid as specified by the C++ standard. There's a rule called strict aliasing which dictate what kind of pointer type can alias another type. For example, both char* and std::byte* can alias any type, s...
62,024,699
62,024,719
Temporary array defined inside for loop and assigned to a pointer belonging to an array of pointers
Here i have initialised a temp arr inside a for loop and assigned its address to a ptr belonging to an array of pointers but as we come out of the for loop the data stored in that address is lost. And if we print the value at that address it shows garbage value. How to fix this? int n;cin>>n; int* ptr[n]; for(int i=0;i...
You need to allocate memory for this pointer manually: int *arr = new int[k]{}; Otherwise, you are taking the address of an array that is local to the scope of the loop, which dies at the end of the loop. Note that when you are done with the dynamically allocated memory, you need to delete it manually as well: delete ...
62,024,784
62,024,961
How to set default parameters In case a user does not type in the other one
#include <iostream> class Person { friend std::ostream &operator<<(std::ostream &os, const Person &person); std::string name; int age; public: std::string get_name () {return name;} int get_age() {return age;} Person() : name{"Unknown"}, age{0} {} Person(std::string name, int age) : name{na...
Since C++11 you can take advantage of delegating constructors: you can provide an additional constructor overload that takes only an std::string for the name and delegates to the existing constructor that accepts the two arguments, std::string and int. Then, just pass 0 as the second argument to the delegated construct...
62,024,787
62,024,839
converting strcpy_s to strcpy CPP
can someone please convert this line: strcpy_s(this->name, SIZE_NAME, d.getName()); to a strcpy function instead of strcpy_s? thank you
strcpy(this->name, d.getName()); That was easy
62,025,176
62,025,347
What is the special status of the value 0 in c++?
This is purely a philosophical question. I assume that there's no reasonable context in which the result will prove to be useful (given nullptr). According to this - https://en.cppreference.com/w/cpp/language/integer_literal, the type of integral literals is either int, long int, long long int, unsigned int, unsigned l...
What happens "under the hood" that enables compilers to perform these int->void * conversions? Magic (or just a dedicated rule, if you prefer). Literal 0 (as well as 0u, 0l and other variants) is special. It's only when those exact tokens appear in the source, that the compiler considers the conversion to a pointer a...
62,025,462
62,030,603
curl_easy_perform() failed: SSL peer certificate or SSH remote key was not OK
Running this code i get an error "curl_easy_perform() failed: SSL peer certificate or SSH remote key was not OK" #include <stdio.h> #include <curl/curl.h> int main(void) { CURL* curl; CURLcode res; curl = curl_easy_init(); if (curl) { /* First set the URL that is about to receive our POST. Thi...
I found out you need to download the .pem file here https://curl.haxx.se/docs/caextract.html And add these settings... curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 1); curl_easy_setopt(curl, CURLOPT_CAINFO, "PATH TO FILE\\cacert.pem"); curl_easy_setopt(curl, CURLOPT_CAPATH, "PATH TO FILE\\cacert.pem"); ...
62,025,485
62,056,396
Get vector from exprTk as output
I can't seem to get a vector output from exprTk. I figure it should be relatively simple but in the manual I can only find how to input a vector and not how to output one. What I currently have is the following: typedef double T; // numeric type (float, double, mpfr etc...) typedef exprtk::symbol_table<T> symbol_table_...
I've found a method that does work, but hopefully there is a simpler 'one-line' method std::string expression_string = "var w[2] := { x, y }; z := w"; This creates an expression local vector w ([SECTION 13 - VARIABLE, VECTOR & STRING DEFINITION]), and then assigns the value to z As @NathanOliver mentioned, std::vecto...
62,026,092
62,027,213
Stack around the variable 'sortArray' was corrupted
Run-Time Check Failure #2 - Stack around the variable 'sortArray' was corrupted. I am getting this on final line, the program is meant to create a list of random numbers and then sort them(WIP). I thought it might be the array size being smaller than the number of lines in test.txt so I increased it from 100 to 101 to ...
You just need to make a few changes into your code. Include <algorithm> in the beginning of your code In the ofstream(...), add ..., std::ios::app) to append into the file. To sort the array, remove the entire block of conditional expression above the ofstream syntax and add std::sort(sortArray, sortArray + 100) outsi...
62,026,332
62,026,682
Qt static libraries undefined reference
I have this situation: libA.a that has no dependencies libB.a that depends on libA.a libC.a that depends on libA.a in B.pro i have LIBS += -lA in C.pro i have LIBS += -lA in app.pro i have LIBS += -lA LIBS += -lB LIBS += -lC But when i compile the linker gives me undefined references on libA classes that are used ...
LIBS += -lA are ignored in B.pro and C.pro. That option is applicable only for the linker, i.e. then a shared library or executable binary are built. To resolve the issue with the undefined references reorder libs in app.pro. The order of dependent libraries does matter. See The order in which interdependent linked lib...
62,026,613
62,200,711
Write FFMPEG frame to png/jpeg file
I have AV_PIX_FMT_YUV420P AVFrame, and I want to write it as PNG or JPEG file, it doesn't matter what format is inside (BGR, BGRA, RGB or RGBA). I tried to save it as AV_PIX_FMT_YUV420P, but I got 3 pictures in one, so I need to convert it to RGB24 first. I do it via: int destW = decCtx->width; int dest...
@parthlr provided acceptable solution in the discussion above. However, you also can read my comment under his preposition.
62,027,282
62,027,338
How do I programatically create multiple structs in C++
I am trying to read in data from a .txt file and use it to create several instances of a struct. I want to do this progromatically via code, as opposed to declaring each instance of the struct manually in a pre determined way (I want it to work for any number of structs being created/data rows in the input file). The i...
There is no reason to name the Person struct in the loop at all. You can simply push_back a Person onto the vector: while( inStream.peek() != EOF ) { inStream >> nameInput >> num1 >> num2 >> num3; //read in data to variables vecPerson.push_back(Person{nameInput, {num1,num2,num3}}); } This avoids naming the ...
62,027,304
62,027,631
How to get function parameters except the first one?
The following is my present implementation: struct Dual { float v; std::valarray<float> d; Dual(float v, std::valarray<float> d): v(v), d(d) {} Dual(float v, float d = 0.f): v(v), d({d}) {} }; Dual d0{1.f}; // OK. Dual d1{1.f, 1.f}; // OK. // Dual d2{1.f, 1.f, 1.f}; // Error. I wa...
You can write a constructor that takes a variadic number of arguments, like this: template<typename ...Ts> Dual(float v, Ts ...ts) : v(v), d({ts...}) {} Here's a demo. With c++20, you could simplify this to: Dual(float v, std::floating_point auto ...ts) : v(v), d({ts...}) {} This has the advantage over the previous v...
62,028,293
62,028,558
Operation of push_back on an element of Vector (C++)
I am a Python programmer trying to develop C++ proficiency. I have a silly question about vectors. Suppose I have a vector like this vector<int> adj; Assume it contains some values. What does this operation do ? adj[v].push_back(w) Does it create vector of vectors ? How is it different from having a, vector<vector<in...
In the provided class definition there is no vector. class Graph { int V; list<int> *adj; public: Graph(int V); void addEdge(int v, int w); void BFS(int s); }; There is declared a data member that has the type pointer to std::list<int>. In the constructor of the class Graph::Graph(...
62,028,821
62,028,928
Conditional branching evaluation
const int IX(int x, int y, std::size_t width) { if ((width * y + x) > 0) { return width * y + x; } else { return 0; } } const int IX(int x, int y, std::size_t width) { int value = width * y + x; if (value > 0) { return value; } else { retu...
This is a prime showcase of a push to get rid of unsigned types except for very narrow domains (i.e. bit manipulations). In your first function, where you check the value directly in the branch, (width * y) Given that width is unsigned (size_t) the result of this is also unsigned (in your case, quite large value), and...
62,028,912
62,029,649
How can I change the color of a QGraphicsItem object?
I try to cast it with a QGraphicsRectItem and then use the setBrush(Qt::QColor) method, but it didn't worked out. int r = rand() %itemList.length(); MyItem *item = itemList.at(r); QGraphicsRectItem *rect = qgraphicsitem_cast<QGraphicsRectItem *>(item); rect->setBrush(Qt::...
I can't reproduce it. It works fine. You may be changing some rect that's not visible on screen. Likely you have multiple overlapping rects at the same position, due to bugs elsewhere, and you don't see the changes even though they occur. The update() call is unnecessary: it'd mean that the implementation of the item i...
62,028,923
62,028,991
C++ - Comparison between negative and positive number returns false
I am implementing a Queue using Vector in C++ I use sz variable to keep track of how many free elements are in the queue at any insert/delete operation. I ran into an issue in my implementation where I was comparing: sz < vec.size() - 1 At some point, this line started to return 0 and the comparison was -1 < 5 One t...
This is why it is important no to mix signed and unsigned types. With sz < vec.size() - 1 you are comparing an signed integer to an unsigned integer. When you do that, the compiler converts the signed integer to the same type as the unsigned integer. When you do that and the signed integer happens to be negative, ...
62,028,941
62,028,989
Why is this while loop not ending in the code below?
Sorry, this code seems silly but I just want to get the logic. I am trying to end the program when the user enters quit as an input. I wrote name != "quit" && sname != "quit" as the while condition, so if any of them is quit, the loop would end (right?). But when I write quit as name, it still waits for sname input, ...
Good question! This has to do with how while loops work. In C++, a while loop works as follows: First, it checks if the condition in the parenthesized statement in the while loop is true. If so, it executes the entire body of the while loop, then jumps back to that first step. In other words, a while loop won't stop ...
62,029,068
62,030,760
Exporting functions from DLLs, LoadLibrary() needs the string cast with TEXT to compile without error
I'm learning to write and use DLLs and this is my first attempt at exporting a function from my dll. It works, but this line is what gave me trouble and what I've been able to find regarding the TEXT cast for UNICODE and ANSI I think I need some guidance. As far as I can find this question has not been asked elsewhere ...
LoadLibrary() is a preprocessor macro. It maps to either LoadLibraryW() or LoadLibraryA() depending on whether UNICODE is defined or not, respectively. LoadLibraryW() takes a const wchar_t* string as input, while LoadLibraryA() takes a const char * string instead. The string literal "MyDLL.dll" is a const char[10], wh...
62,029,129
62,029,367
While loop only doing 1 iteration
What I want to do: Generate a random sequence of letters with only the letters a,b,c,d in it. Let the user enter a sequence as a guess, output the position at which he has a correct letter, print the number of correct letters at wrong positions, repeat until the user guesses the sequence correctly OR after 10 wrong tr...
The problem most likely is the off-by-one out-of-bounds writing that happens with cin >> t[5]; This will read one single character from cin and write it to the sixth element of the five-element array t. This leads to undefined behavior. What probably happens in reality is that the next variable in memory, which is mos...
62,029,173
62,038,089
C++ application which reads file name from command line, use read() method to read the file's content
I have this code but after entering the name from the command line it starts working but the output is a never ending weird character array. The problem which i tried to make says: Write a C++ application that reads a file’s content using the read() method. The obtained data is displayed on the screen. Check the syste...
Okay it looks like i could solve all the bugs. So here's the good code: #include<iostream> #include<fstream> using namespace std; int main(int argc, char* argv[]) //using command line arguments { char arr[15]; ofstream wfile; if (argc == 1) { cout << "Enter file name from command line!"; ...
62,029,797
62,029,859
Most efficient file type for random data access
I am writing a password generation program. I have collected a list of around 30,000 English words and plan on picking from them at random by index. Currently, I have all the words in a .txt file each separated by a newline character and organized by length. My current plan is to write the program in C++ because that i...
30,000 words sounds like an insignificant amount of data to load. Even if it's ~50-500MB just load it in and forget about it. On a modern system this will take a fraction of a second to accomplish the first time, any SSD can do ~600MB/s+, and even less once it's in the OS disk buffer. You'd only concern yourself with n...
62,029,798
62,031,700
Why the standard preferred round brackets initialization for `make_<something>`?
The std::make_ functions in the standard, such as: std::make_unique and std::make_shared std::make_tuple std::make_from_tuple all use internally round brackets initialization rather than curly brackets. For example, make_from_tuple as presented by the standard is choosing to return T(params...) rather than T{params.....
Because it was not possible to initialize structure using braced-init-list in C++98. So for consistency new standandard library features have used the same initialization form as the one used in the STL. More over, it has never been changed to list-initialization for compatibility reason: list-initialization has not ne...
62,030,021
62,030,158
Different Ways of Data Initialisation in C++
I recently discovered that in C++ , we can initialize the integer , or for that matter other primitive data type in C++ using different ways. The first one that most would be familiar is : int i = 50; //initialised to 50 char c = 'a'; //initalised to 'a' //And in similar way for all other data types The one ...
Is one more efficient than other? No. Is there any scenario where one is preferable over other? Curly braces are often preferable, when they are an option, because they do not allow narrowing implicit conversions, which are often unintentional. Note that curly braces and parentheses affect the resolution of the co...
62,030,248
62,030,262
Updating an object inside a vector?
So I'm updating the "Missile" vector list. However, when I try to change the coordinates: x and y, they won't change? I don't understand why, especially not when everything else updates inside of it? private: std::vector<Missile> missiles; void shoot(Spawner spawn) { // 50.0f/3, 200.0f/3 M...
On this line: Missile index = missiles.at(i); you are making a copy of the Missile, so the original inside the vector is not modified. Instead, you could do: Missile &index = missiles.at(i); to take a reference to the Missile in the vector. Or simply: missiles.at(i).update();
62,030,267
62,030,627
(C++) Why this program is giving the "0" or "nan" in the output?
I have this simple C++ program where I have to input the marks of 5 subjects and calculate it's percentage. But I have no idea why in the output it shows "0" and if I remove those return 0 statements under input() and percentage() functions then it shows "nan" in the output. Here is the code: #include<iostream> using...
Your functions are promising to return a float, but they don't. That is undefined behaviour. And once your program contains UB anywhere, it becomes meaningless in its entirety.
62,030,341
62,030,407
What is this? catching polymorphic type X by value [-Wcatch-value=]
Does anyone know what the following compilation warning: catching polymorphic type ‘class std::out_of_range’ by value [-Wcatch-value=] warning means and how to correct it? I copied this code block literally out of Stroustrup's C++ 4th Edition. Thank you #include <iostream> #include <vector> #include <list> using std:...
If you look at the C++ Core Guidelines, you can find E.15: Catch exceptions from a hierarchy by reference This is exactly your case. By catching a value, you are effectively using just the base class of the exception thrown (regardless of the type actually thrown). Instead, catch by reference (or const reference, if ...
62,030,624
62,030,684
:CIN keeps printing what user entered after each loop
I am writing a basic make change function and it is working well (pretty sure there is a better way to do this) but I am new to c++ and I am having a weird bug. It keeps printing the y or n after a user presses it and I don't want that. I dont have it cout any for it to print to the console. Also I have tried clearing ...
In this code if(putchar(tolower(res)) == 'n' ) putchar writes a character to the console. Not sure why you added putchar I guess you just wanted this if(tolower(res) == 'n' )
62,030,752
62,075,838
clang++ undefined reference to function even though it exists
I'm trying to create some simple binary to call an exported function from the shared object libQREngine.camera.samsung.so This is the source code: #include <iostream> extern "C" int Java_com_samsung_android_qrengine_QRBarcodeDecoder_getRecogObjectCount(); int main() { int test= Java_com_samsung_android_qrengine_QRBa...
It was the symbol versioning which resulted in having 2 functions, one expected the "LIBNATIVEHELPER_1" version while the libnativehelper.so couldn't provide that version even though it had these functions. All I had to do was to compile libnativehelper.so through Googles AOSP build system (make sure you compile it in ...
62,030,819
62,030,936
C++ string operation
string ss = "1-1-10-8-9"; There is a string like above. I want to add element to string array between "-" string vector should be same as below vector<string> str = {"1", "1", "10", "8", "9"};
#include <iostream> #include <sstream> #include <vector> int main() { std::stringstream ss("1-1-10-8-9"); std::vector<std::string> v; std::string s; while(std::getline(ss, s, '-')) { v.push_back(s); } return 0; }
62,030,957
62,031,149
Could a re-sizable container be built on the on stack
I've searched this up but was unable to find answers. We all know that a lot of the STL containers are re-sizable (except for things like std::array, etc.), but they all are allocated on the heap. So I was wondering if a re-sizable container could be built on the stack and if somebody could give me an example. A though...
It would also have to be very limited in size due to limited size of the stack. What you could for example implement is a vector-like resizable container that has small constant storage, and thus small constant maximum size. You could also create a linked list within a recursive function where head is on the current fr...
62,030,964
62,030,995
Most efficient way to determine if an integer is odd or even using modern C++ techniques
I wrote this simple helper constexpr function: #include <cstdint> constexpr bool isEven(uint32_t value) { return ((value%2) == 0); } It is pretty straight forward. I was wondering if this would be considered the most efficient way to determine if some integer value is odd or even? I'm not worried about templating thi...
You can directly use the & ( AND ) operator. If x is your int: x & 1 // returns 1 if odd, else 0 This is probably the best way to find if an integer is odd or even.
62,030,974
62,041,474
How to extract RGB value from COLORREF in MFC?
Actually i am trying to extract RGB value from COLORREF but not getting Value in range of 0 to 255. Instead of that i am getting some string always. eg:0000017153665268 i used below method: COLORREF obj_Colorref = obj_CColorDialog.GetColor(); RGBTRIPLE rgb; rgb.rgbtRed = GetRValue(obj_Colorref); rgb.rgb...
The problem is with this: file << "#"<<"\n"<<"#"<< sRed << ","; file << sGreen << ","; file << sBlue << ","; It prints wchar_t based CString to char-based stream. wchar_t* does not print as string into basic_ostream<char>. Easiest way to fix is probably to avoid CString altogether: file << std::to_string((int)rgb.rgbt...
62,031,661
62,031,950
Nested class "does not name a type"
I'm getting the following error: main.cpp:18:5: error: 'Iterator' does not name a type 18 | Iterator begin() { | ^~~~~~~~ With this code: #include <iostream> #include <iostream> #include <memory> #include <fstream> #include <filesystem> using namespace std; class Numbers { private: int curre...
From a comment to the question Also - I have no problem calling member function f in member function q where f is defined after q. Can you explain why the latter example is different than the situation described in this question? According to the C++ 20 Standard (11.4 Class members) 6 A complete-class context of...
62,031,787
62,031,827
String serialization in C++
I have a following class fields: int _number; string _name; int _amount; bool _isAvailable; double _price; int _storageTime; int _entranceDay; int _entranceMonth; int _entranceYear; How shall I serialize/deserialize an object of that class? I tried this: void Serialize() { ofstream ofs("tmp.bin", ...
In Deserialize ifs.read((char*)& stringSize, sizeof(string)); must be ifs.read((char*)& stringSize, sizeof(int)); However note the compiler/byte order/etc must be the same when you serialize and deserialize, why are you not using standard external representation of number/string/... ? Note also by definition sizeo...
62,032,038
62,094,214
Preserving content of source blocks when exporting literate program to HTML with ReadTheOrg
Minimal example I wrote a program in org-mode using literate programming technique with :noweb extension(?). Typical piece of code looks like this: * Section In order to do foo with bar, we define a function ~do_foo~, which initializes object of a class ~BarParser~ with a value of parameter of the type ~bar_t~. #+nam...
IIUC, you need to specify an appropriate :noweb header. Try this: #+begin_src cpp :noweb no-export and refer to the noweb section in the manual for other values and more details.
62,032,201
62,032,240
Please describe the way the constructor is defined in this class in c++?
what does the : e(data) do in the following code? Why are the curly brackets { } empty in the folowing code? Also can constant members of a class be initialized in this way? Is this kind of definition specific to a constructor or it can be applied to all functions in C++? class binaryfile { private: const e...
binaryfile(const entry &data) : e(data){} Defines a constructor which takes one argument and initializes the member variable e to that argument's value. The braces are empty because the constructor does nothing more. It's called a member initializer list and it only works in constructor(s).
62,032,583
62,032,709
Division Round Up in C++
How can I round up when performing division on two int values in C++ without using std::ceil? Typically I end up doing something like the following: double res = ceil(a / (double) b); Is there any way I can duplicate the result without using std::ceil?
If a and b are both positive, you can avoid floating point completely and get both exact results (no problems with FP rounding) and faster execution time through the classical method: int res = (a + (b - 1)) / b; For negative a you don't need any correction - the truncation performed by integer division already has th...
62,032,886
62,073,289
How can I convert a 2D RGB array into a dds file using C++?
I've got a 2D array of RGB values that represent a plane's painted vertices. I'd like to store the final vertex colours of the plane in a .dds file so I can load the .dds file later on as a texture. How might I approach this?
Thanks to Chuck in the comments, I've found this solution works for me. There are likely improvements to be made. The approach can be broken into a few steps. Step one is to deal with capturing the device context and D3D device to use for rendering, and setting the correct texture description to be used when creating ...
62,033,074
62,033,522
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'T'
I try to compile the following code: class CFileOperations { ... template <typename T> inline void load_and_save_data(std::fstream* stream, T& value, const EOperation operation) { switch (operation) { case EOperation::OpSave: *stream << value; <-- here ...
My bad, one of the calls was with a 'class enum'. Of course, >> and << are not defined for it.
62,033,400
62,035,451
OpenGL GLM matrix/vector not initializing properly
I'm attempting to use GLM in an SDL/OpenGL project using MinGW-w64 as a compiler, and am unable to set a value for any matrix or vector I attempt to initialize (all the values in the structure are being set to 0.) I am not receiving any compiler errors or warnings and it seems like the memory is being allocated properl...
glUniform* sets a value of the uniform in the default uniform block of the currently installed program. Hence the program has to be installed before by glUseProgram: GLuint mvpID = glGetUniformLocation(shaderProg, "MVP"); glUseProgram(shaderProg); glUniformMatrix4fv(mvpID, 1, GL_FALSE, &mvp[0][0]); Since OpenGL vers...
62,033,512
62,033,824
Why is it not undefined behavior that `std::uninitialized_copy` typically dereferences an iterator to uninitialized memory?
I'm aware that dereferencing a pointer or iterator that points to uninitialized memory is illegal, unless it's a special iterator such as std::raw_storage_iterator. It then seems strange to me that the std::uninitialized_ family of algorithms seem to do this? E.g. The Equivalent behaviour for std::uninitialized_copy un...
I'm aware that dereferencing a pointer or iterator that points to uninitialized memory is illegal Not quite. The indirection alone is not illegal. Behaviour is only undefined in case of performing operations such as those that depend on the value. std::addressof does not access the value of referred object. It only t...
62,033,520
62,033,599
list.push_back seems to duplicate the last added element
Input: This_is_a_[Beiju]_text Expected output: This_is_a_[Beiju]_text Actual output: This_is_a_[Beiju]_textt It seems when the code ends, it adds an extra unwanted char (note the extra "t" at the end). Code: #include <iostream> #include <list> using namespace std; int main() { list <char> text; char current_...
This happens because of the newline character. Your input is actually This_is_a_[Beiju]_text\n. When cin peeks the \n it doesn't see an EOF yet. When operator>> then tries to read the next character, it fails, because it ignores the line break as whitespace and then hits the EOF. And so the value of current_char stays ...
62,033,598
62,033,687
Designated initializer different behavior before and after c++20
I came across this strange behavior and I can't find a good explanation of it. The code below will compile successfully before c++20 and only fail if explicit is used. struct Square { int area = 10; Square() = default; // only if this is explicit will the compile fail Square(const Square& other) = delete; Squa...
Why does it compile successfully before c++20 ... The program is ill-formed prior to C++20. Designited initialisers did not exist in the language prior to C++20. It compiles because of a language extension. What changed in c++20 that made it not compile anymore? The program is still ill-formed in C++20. Designated ...
62,034,520
62,035,167
Switching Vectors Supplied Iterators
I am designing my own generic tree container and am using the STL as a reference. However, when implementing my iterator class I noticed something about the STL's use of iterators. As an example, the std::vector class relies on iterators as arguments for many of its methods. (ie. erase(const_iterator position)) This g...
The iterator passed to a member function of a container must refer to an element within that container (or, in some cases, the past-the-end element returned by end()). If the iterator does not refer to the container you have Undefined Behavior. There is no simple way to avoid that. About the closest you can come is to ...
62,034,578
62,034,640
Why does not work with lambda with template
auto bind2nd = [] < auto func_object,auto second_arg>(){ return [=](auto&& first_arg){ return func_object(first_arg,second_arg); }; }; auto h =bind2nd.template operator()<std::greater<int>(),5>(); compiler result: <source>:9:60: error: no matching function for call to '<lambda()>::operator()<std::grea...
As a template argument std::greater<int>() is parsed as a function type (a function that takes no arguments and returns the class type std::greater<int>). This is where you can use curly brackets to help the compiler differentiate: auto h = bind2nd.template operator()<std::greater<int>{}, 5>();
62,034,689
62,034,769
C++. Logical expression
I am trying to solve the following task. Given an integer x, I want to compute 2 numbers (a and b) which are: 1) divisible by 2 or 3 (e.g a % 2 == 0 or a % 3 == 0 ) 2) x = a + b I wrote the following code, to find such a and b. cin >> x; if (x % 2 == 0) { a = b = x / 2; } else { a = x / 2; b = a ...
Examine your continuation condition carefully (where n is some arbitrary integer, possibly different in each use so, for example a != 3n simply means that a is not a multiple of three). I'll show the process: while((a % 3 != 0 || a % 2 != 0) && (b % 2 != 0 || b % 3 != 0)) ( a != 3n OR a != 2n ) AND ( b != 2n...
62,034,987
62,038,866
Is it slower to access std::map elements with at() than operator[]?
When I want get certain element from a std::map, as far as I know at() will do a bounds check. Does that mean it's slower than []?
Both std::map::at and std::map::operator[] check presence of key. Former throws exception when not found, later creates default value. Their complexity is mandatory to be log(n) (look-up). Performance by itself is not mandatory to be identical, but should be similar in practice. So choose the one to use from their beha...
62,035,048
62,035,184
Where I am going wrong in this stack operation?
This is a snippet of my code, which is not terminating due to loop error. I want to check the array elements which is in the form of stack or not, this is an example caused error. #include<bits/stdc++.h> using namespace std; int main() { int arr[]={5,4,3,2,1}, k=0; stack <int> s; for(int i=1; i<=5; i++) ...
The problem is that an empty stack has no top(). while(s.top()==arr[k] && s.size()>0){ The fix is to reverse the condition check. while(s.size()>0 && s.top()==arr[k]){
62,035,501
62,035,923
Why is this code considered a VLA even though it uses an int?
I thought that I understood what a VLA is, until I saw a question asked here about the difference between dynamic memory allocation vs variable length arrays. So I don't have any problem, at least for now, with dynamic memory allocations, but what I don't understand is why this code is considered a VLA: int size = 10; ...
First of all, variable length arrays doesn't exists in C++. There are no variable length arrays in C++. This answer only applies to specific GNU compiler extension to support variable length arrays in C++. why this is even a VLA size is still known to the compiler The question is not about "what is known to the comp...
62,035,651
62,035,895
Variant - are old values' cleaned up when assigning a new value?
Are previous variant's values cleaned up when a new value is assigned to the variant? std::variant<std::string, std::vector<int>> v; v = std::string("foo"); v = std::vector<int>(); // is string's destructor called above? I'm assuming the previous values for containers are automatically freed when new values are set in...
yes, the strings destructor is called before the vector<int> is copied in.
62,035,743
62,035,876
C++, problems with structures in classes
everyone if someone can help me I'll be very grateful. I've been trying to fill in the structure called m_Center by a function of the same class, I'm using eclipse to work and it gave the next errors messages: -'m_Center' was not declared in this scope -Field 'radius' could not be resolved -Symbol 'm_Center' could not...
Add the class name before the generate_obstacles method. void CObstacles::generate_obstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles) { ... }
62,035,798
62,036,918
how to use localtime() correctly?
In one of my utility programs, localtime() is used to covert unix timestamps to human readable date time. The following code used to work in VS2010 while it fails to work in VS2019: std::string sec = "1234123456"; int nsec = atoi(sec.c_str()); tm* t = localtime((time_t*)&nsec); // return null pointer If I change the c...
On most (if not all) modern compilers time_t is now a 64-bit integer. (time_t*)&nsec is therefore undefined behaviour as you are casting from one pointer type to a different one. You fixed version is well defined but you will run into the reason that time_t is now 64-bit as 32-bit numbers will only work for times up to...
62,035,945
62,036,228
C/C++ extension for Visual Studio Code "variable "u8"" is not a type name”
I am using VS Code for embedded C projects with the C/C++ extention from Microsoft. I have a given type naming scheme that I am not in charge of and can not change anything about. To use those names I have for example these following typedefs typedef unsigned char u8; typedef signed char s8; typedef unsigned short u16;...
Your code will still compile. It's just that from C11, u8 followed by a quoted string means that the following string is encoded in UTF-8. There are others too: U and L are particularly pernicious as you can see them being used as upper and lower in optimisation code, particularly that converted from FORTRAN. This is n...
62,036,121
62,036,771
Checking if guessed string has a correct character at the wrong position
I want to generate a random string with letters a,b,c,d then let the user guess it. My output should be which positions the user guessed correctly and how many letters the user guessed correctly but put them in the wrong position. Current attempt: #include <iostream> #include <cstdlib> #include <ctime> #include <str...
You should implement like this #include <iostream> #include <cstdlib> #include <ctime> #include <string> using namespace std; int main() { srand(time(0)); char lettres[4] = {'a','b','c','d'}; char rString[4]; int i = 0; //making random string while (i < 4) { int temp = rand() % 4; ...
62,036,131
62,036,271
Differences among `unique_ptr<Sample> sp1(new Sample);` `unique_ptr<Sample> sp1(new Sample());` and , `unique_ptr<Sample> sp2(new Sample{});`
What are the differences among unique_ptr<Sample> sp1(new Sample); unique_ptr<Sample> sp1(new Sample()); and , unique_ptr<Sample> sp2(new Sample{});? I found that they are all legal indeed.You could check it on http://cpp.sh/3icui. I am a novice in C++.I thought over and over but still could get the idea.I would be t...
They have the same efffect here. new Sample() performs value initalization, the object is initialized by the default constructor of Sample. new Sample{} performs list initialization (since C++11), as the effect the object is also value-initialized by the default constructor of Sample. BTW: new Sample has the same effec...
62,036,358
62,037,208
std::stable_sort vs std::sort
https://leetcode.com/problems/largest-number/ When I was solving the above problem, I came across the case where std::sort() was giving me a runtime error, but replacing it with std::stable_sort() then there was no runtime error. Why? Line is highlighted with the arrow sign on right Code: class Solution { public: s...
This is actually a very interesting bug! I have not tested whether this is a leetcode specific issue, but running this code with sort() on leetcode, we get the following error: Line 431: Char 55: runtime error: pointer index expression with base 0xbebebebebebebebe overflowed to 0x7d7d7d7d7d7d7d7c (basic_string.h) SUMMA...
62,036,634
62,036,916
Convert std::string("\x3B\xDE\x7C") to a readable hex string?
I am trying to parse the input string from a user which can be "\x3B\xDE\x7C" std::cout << std::string("\x3B\xDE\x7C") << std::endl; results in ;Ì| How do I parse it to result in: "\x3B\xDE\x7C", preferably "3B DE 7C"?
The \x is not stored in the string actually, it got detected as an escape sequence. Any escape sequence does not store the characters you see on the screen, it stores the actual character specified. Further, it converts to the Hex. For example, if you put: std::cout << std::string("\x3B"); The string will store ; char...
62,036,652
62,036,888
How to construct objects of nested class templates with the same argument?
How to construct objects of nested class templates with the same argument? How to write the constructor to make following code compile? template<typename T> struct S { T v; S(T v) : v{v} {} }; int main() { S<int>{0}; // OK. S<S<int>>{0}; // OK. S<S<S<int>>>{0}; // Compilation err...
You can add a second converting constructor. If you want to support any type, just make this constructor templated: template <typename T> struct S { T v; S(T v) : v{v} {} template <typename U> S(U v) : v{v} {} }; This work as follows: S<int>{0}; S<S<int>>{0}; S<S<S<int>>>{0}; ...
62,036,783
62,037,063
Using nested [ ] operations for std::vector
I am quite new to C++, and i have tried searching for an answer to this and running tests, but many times I'm having trouble figuring out what causes specific behaviors. My question relates to using nested [ ] operators to access or modify elements in a loop - example: //Declare std::vector<int> a1 {10,20,30,40} ; st...
This is perfectly correct. But in fact, you just want to iterate the elements of a standard container. C++ allows the range based for statement for that use case: for (index: a2) { a1[index] += 5000; } I find it more readable even if it is mainly a matter of taste... Disclaimer: this code makes no control of the v...
62,036,788
62,036,867
What are some use cases for function overriding?
I'm reviewing some c++ concepts (I used it a few years ago) and the concept of function overloading now makes a LOT of sense to me, especially to some scenarios I encountered in my powershell programming experience over the last year. For instance, now I could easily explain it to someone as its very useful for softw...
cant you just name the function in the child class something else, and call it directly that way without worrying about the parent class function? No, because it would be impossible to have runtime dynamic-dispatch which is the entire basis for polymorphism. (Dynamic-dispatch is implemented in C++ (and most other lan...
62,036,816
62,036,892
How to convert an array of string pointers into a vector of smart pointers of type string?
I have a code like this: std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; I need to get a vector like this: std::vector<std::unique_ptr<string>> vec; I also need to clear memory in the original string_ptr array and in the new vector. How to do it better?
If u want to transfer the ownership to a vector, you can do as follows (after this u won't have to free any memory. the vector will manage that) int main() { std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; // step 1 size_t sze = size(string_ptr); std::vecto...
62,037,479
62,276,220
Eclipse executable arch type
I faced with issue when I trying to create executable file for linux system on my mac using Eclipse and c++ project. I can prepare executable, but for arch x86_64 $ file <fileName>: Mach-O 64-bit executable x86_64 Sample executable that works fine on linux system before has ELF 32-bit LSB executable: $ file <fileName_o...
I have found instruction how to do so (thanks to advice). U need to: Install and setup SFTP on LinkIt Smart 7688 development board with opkg. Install Eclipse C/C++ GCC Cross Compiler Support and Remote System explorer End-User Runtime. Newer versions of Eclipse may have these packages installed already. Create an Ec...
62,037,841
62,037,933
C++ Integer Followed by char gets accepted as an input
I am using a function to check that my input in an integer only: int input; while (true) { std::cin >> input; if (!std::cin) { std::cout << "Bad Format. Please Insert an integer! " << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits...
That happens because chars in c++ are represented by their numeric value in the ascii table, you can try regular expressions like this: #include <regex> #include <string> std::string str; std::regex regex_int("-?[0-9]"); while (true) { std::cin >> str; if (regex_match(str, regex_int)) ...
62,038,445
62,038,484
How do you insert a string at the beginning of a .txt file in C++
I am trying to insert a line at the top of a txt file without deleting the entire file, is there a function or library that helps with this? I am using the fsream library but am unable to insert, only append using the ios::app feature for fstream.
You can't insert data at the beginning of a file. You need to read the entire file into memory, insert data at the beginning, and write the entire thing back to disk. (I am assuming the file isn't too large). Try this program. #include <fstream> #include <sstream> int main() { std::stringstream stream; stream ...
62,038,571
62,038,691
Function which accept any STL container
I need to implement a template function that accepts any STL container. And based on what kind of container to perform certain actions. Example: template <class Container, class T> void func(Container<T> container) { if (container == std::map) { ... } else { ... } } int main() { std:...
You can apply Constexpr If (since C++17) (with std::is_same) to check the type at compile-time, and apply parameter pack (since C++11) because these containers take multiple template parameters. e.g. template <template <typename...> class Container, class... T> void func(const Container<T...>& container) { if const...
62,039,089
62,039,538
How to design class inheritance
I provide 3 interface classes for others IA, IB, IC。 and then I need to implement these 3 interface classes. My implementation method is as follows, but the behavior of a() in the 3 classes is the same, how can I reuse the code。 class IA{ virtual void a() = 0; }; class IB : public IA{ virtual void b() = 0; }; ...
There are several ways: Create the common functions: void f() { /*..*/ } class A : public IA{ void a() override { f(); } }; class B : public IB{ void a() override { f(); } void b() override { /**/ } }; class C : public IC{ void a() override { f(); } void c() override { /**/ } }; use virtual inh...
62,039,240
62,041,105
Are clock_gettime() in C++ and time.time() in python equivalent?
I am using boost python and trying to measure latency of a switch from C++ to python and vice versa. But I think i am doing it wrong, I get the time in C++ by clock_gettime()(t0) and pass it as an argument to python function and from within this function I call time.time()(t1) to get the time. But when I try to measure...
I'd expect this latency to be on the order of nanoseconds so if you want to measure it, it'll important to use an accurate clock and make sure they're consistent. Also understand that at this level actually reading the clock will be a non-negligible cost, so it might not be a realistic goal in the first place. For pyth...
62,039,296
62,040,149
How to convert a string to given precision double?
Updated: I have been trying all methods I could find in stackoverflow, and still could not find a solution. My point is, I have a string "23.46" and would like to transfer it to double or float anyway. This is in order to be used in another library. But no matter how I trancate,floor,*100,add,round, it always gives me ...
Given that you say that using std::strtod is not giving you a solution to the problem, you can use stringstreams to parse strings as doubles, you can also use its flags to assert if the contents of the string are convertible. Here is an example with some conversions back and forth, and with checks to see if the whole s...
62,039,356
64,442,059
SAMD21: how to set PWM using TCC?
I'm programming a SAMD21 and I need PWM. When I chose pin with F function TCC0 output: PA22 - TCC0/WO[4] PA23 - TCC0/WO[5] I successfully configured TCC0 base counter: // enable clock for TCC0 - disable clock masking PM->APBCMASK.reg |= PM_APBCMASK_TCC0; // set GCLK1 as source to the TCC0 counter GCLK->CLKCTRL.reg = G...
There is a PWM library you can re-use code from; it comes with a table (under "extras") with timers, output pins, output channels, pin multiplexers etc. The library was written (by me) for SAMD21G-based Arduinos, but all the mappings and code you need are there, and it may help you in your efforts.
62,039,578
62,039,799
Not able to understand the logic behind the code which is an optimisation problem of generating prime numbers between two given numbers
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers! Input The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100...
Its pretty simple really. You precalculate all primes that exists in your range. Then for each multiple of prime, except first, you mark number as "not prime". Line you marked just calculates first occurence of particular prime's multiple in range M to N. Edit: More explanations. This method finds primes by first searc...
62,039,580
62,040,367
How to insert and iterate elements to this kind of map. C++
I tried on my own. But I was unable to do it. So, please help. unordered_map<string, pair<string , vector<int>>> umap; Or more precisely, how We can make pair of one string and one vector that can be used in map.
Well you can use insert function and insert them as a pair (Or precisely nested pairs). For example Checkout this program : #include <iostream> #include <vector> #include <string> #include <unordered_map> using namespace std; int main() { unordered_map<string, pair<string , vector<int>>> umap; //Insert like th...
62,039,880
62,039,998
Getting again a std::map changes the previous iterator
I can't find any similar questions. The moment I call a getMap, the previously iterator seems to change: //IF I COMMENT THE EVIL PRINT, THE PROBLEM DOES NOT OCCUR std::cout << "EVIL PRINT" << std::endl; Something something; auto mapElement = something.getTheMap().find("A"); std::cout << "Before: " << mapElement->f...
You did not include the most important parts in your question, namely std::map <std::string, int> getTheMap() { return theMap; } getTheMap returns a copy, so getTheMap().find("A"); returns an iterator to a temporary object (that stops existing after the call finishes). Therefore that iterator references an obj...
62,039,912
62,066,188
No response from Aerospike
I am writing my own Aerospike client in C ++ and I have a problem: although my request seems to reach the server (if you send nonsense, the connection will be dropped), the server does not return any response. Here is my code: #include <boost/asio.hpp> #include <boost/array.hpp> #include <iostream> void read_message(b...
You are calling socket.write_some() only once in your send_message() function. You are basically assuming that all the bytes will be sent in one call. There is no such guarantee. When I tried your code, it sent only 2 bytes in my run. Unless all bytes reach the server, it won't respond (obviously).
62,040,031
62,069,742
Butterfly pattern appears in random walk using srand(), why?
About 3 years ago I coded a 2D random walk togheter with a coleague in C++, first it seemed to work properly as we obtained a diferent pattern each time. But whenever we decided to increase the number of steps above some threshold an apparent butterfly pattern appeared, we noticed that with each run of the code the pat...
You never hit rand()'s period, but keep in mind you don't actually use the entire rand() range that in its entirety guarantees a 2^32 period. With that in mind, you have 2 options: Use all the bits. rand() returns 2 bytes (16 bits), and you need 2 bits (for 4 possible values). Split that 16 bit output into chunks of ...
62,040,152
62,040,272
Using push_back() with range based for loops
Please excuse me if my understanding isn't up to par yet, Im still learning C++, and Im coming from an interpreted language (R). My question is regarding the usage of vectors as index containers for range based for loops, In the following example : //Declare std::vector<int> a{5,1,6,9} ; std::vector<int> b{0,3} ; //R...
As long as b contains valid indexes into a your code is perfectly fine. A problem would arise if you would modify the container your iterating over with range for, e.g. this would be invalid: for (auto e : a) { a.push_back(...); } But you are not doing this so you are OK.
62,040,333
62,041,226
Why my compare operator is not comparing my point length and double value?
I create new operator to compare my point vector length and double value. I have condition to tolerate different which is less than 0.01. When i using this operator to compare my Point and my double value (both values after approaching are same) but the operator == is not returning true. class Point { private: doub...
This issue can be reproduced on gcc with 32 bit Intel architecture, without optimization. Here is an example of it happening: compiler explorer example. This is due to the infamous 323 bug of gcc, which struggles to work with Intel's 80 bit floating point registers, which are wider than the 64 bits of type double. Some...
62,040,361
62,084,619
C++11 Cereal Serialization - versioning
I have successfully serialized two members of my class. archive( cereal::make_nvp("width", m_width), cereal::make_nvp("height", m_height), ); Now, in a later version my code contains more members and I would like to archive them as well: archive( cereal::make_nvp("width", m_width),...
For future reference - here it is documented how to version: https://uscilab.github.io/cereal/serialization_functions.html#versioning
62,040,536
62,040,595
what happens to it = std::vector::end after emplace_back
I was wondering what would happen to an iterator pointing to the end of a vector after I emplace_back on it. Example: std::vector<int> v; for(int i = 0; i != 50; ++i) { auto it = v.end(); v.emplace_back(i); if(it != v.end()) cout << i << " "; } This code does what I kinda expected but it still feel...
The code results in undefined behavior: std::vector::emplace_back If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated. So the past-the-end iterator (end()) is invalidated in any ca...
62,040,541
62,040,980
Is this a proper way to extract a byte from a NEON uint8x16_t vector?
I am a beginner to NEON intrinsics, and I wanted to work with uint8x16_t and also uint8x16x4_t. While working with it I came across a situation, where I wanted to extract a byte from a uint8x16_t. Being naive to the details I accidentally began extracting bytes from it using the [] operator at runtime. But my compile...
Why am I able to use the [] operator on it directly Because gcc / clang define it in terms of GNU C native vectors (https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html), which do have well-defined rules for operators. ARM's docs probably don't guarantee that [] works, and there are probably some ARM compilers w...
62,040,707
62,040,819
Implementing derived class with templates
I have a templated base class A and templated derived class B defined in headers.h and the implementation goes to source.cpp Below code does not compile as x is not in the scope of B. The question is what am i doing wrong? I found that if A is not templated the code compiles fine (with relevant changes). // headers.h t...
Below code does not compile as x is not in the scope of B A<T> is a base class of the class template B: template<typename T> class B: public A<T> { // ... }; Although the member x from A<T> is actually inherited in B, it is not found in B because the name x, when used inside B, is not looked up in its base class A<T...
62,040,860
62,043,093
Overload of << operator in .h files
When i try to overload the "<<" operator in my .h file, i get the following error: multiple definition of `operator<<(std::ostream&, complex_number&)' But when i move my operator overloading in my .cpp file, everything works just fine. I don't really know what is happening. Any help? Here is my initial code: (main.cp...
Because your .h file is included from multiple .cpp files, and each .cpp file is compiled separately as different compile units, and then linked together, thus, your << operator function will be in each of the compile units, and they conflict each other during link stage. There are two options if you insist to leave it...
62,040,884
62,041,758
Compiler get error message (textc.exe has stopped)
C++ Program Here is some problem that i faced.After compile it opened a popup window and give me error message "textc.exe has stopped" then i got black screen. #include<iostream> using namespace std; int main() { int i,n,a[10],b[10]//a[10],b[10]; cout<<"enput array size: "; List item cin>>n; cout<<"Enter som...
Try this way to initialize: #include <iostream> int main(void) { unsigned int size; int *a, *b; std::cout << "Enter the size of array: "; std::cin >> size; a = new int[size]; // dynamic initialization b = new int[size]; // of arrays for (int i = 0; i < size; i++) a[i] = b[i] = 0;...
62,041,402
62,043,153
C++20 initializing aggregates from a parenthesized list of values, not supporting inner array
C++20 adopted p0960 - allowing initialization of aggregates from a parenthesized list of values. The exact wording ([dcl.init] 17.6.2.2) says: [...] if no constructor is viable, the destination type is an aggregate class, and the initializer is a parenthesized expression-list, the object is initialized as follows....
p0960 changed between r1 and r2: r2: This revision changes the mental model from the original “literal rewrite to a braced list” to “as if a synthesized, explicit constructor with appropriate mem-initializers was called” 1. This has the effect of allowing narrowing conversions in the parenthesized list, even when narr...
62,041,863
62,059,015
boost_multi_index iterator dereference gives const
This is related to dereference boost_multi_index hashed_index iterator. Please see the code below: using namespace boost; using namespace boost::multi_index; using Container = boost::multi_index_container< std::string, indexed_by<hashed_unique<const_mem_fun<std::string, size_t, &std::string::size>>>>; Containe...
Boost.MultiIndex iterators are const (won't give you non-const access to the element) because otherwise values could be changed without the owning multi_index_container knowing, which would result in elements being mispositioned, undefined behavior, etc. This is the same situation as iterators in a std::set, for instan...
62,042,238
62,043,864
Forwarding intializer list / aggregate inialization to std::array member
I have a class that encapsulates a stl compatible container type which is the only class member and gives a lot of vector math functions that can be applied on this vector. This class has various kinds of constructors, one of them is a constructor that takes an initialiser list: template <class Type, class VectorType =...
With tag-dispatching: template <typename T> struct type_identity { using type = T; }; template <typename Type, typename VectorType = std::vector<Type>> class MathVector { public: MathVector(std::initializer_list<Type> il) : MathVector(il, type_identity<VectorType>{}) {} private: template <typename T> ...
62,042,947
62,043,168
Unable to deduce type in class with constructor taking std::array
I am trying to create a templated class containing enum-string pairs and unable to make type deduction work. With a following code i have two problems: namespace { template<typename T, size_t S> using EnumStringArray = std::array<std::pair<T, const char*>, S>; } template<typename T, size_t S> class EnumToString { publ...
{..} has not type and cannot be deduced (except as std::initializer_list<T> or T(&)[N]). so regular constructor, or deduction guide doesn't help with CTAD here.
62,042,992
62,043,486
what is the difference between [=] vs [this]?
In some project found fix like this: - use([=](Foo* &df) { + use([this](Foo* &df) { delete df; df = nullptr; }); where use is: template<class LAMBDA> void use(LAMBDA callback) { LOCK lock(this->mutex); callback(this->data); ...
this is not a variable (it is a keyword). As such, normal rules of capturing variables don't apply. Both capture-defaults & and = capture the object pointed by this i.e. *this by reference. Since C++20, the implicit capture of *this when using = capture-default is deprecated. The obvious difference between using captu...
62,043,293
62,043,957
how do you split a string embedded in a delimiter in C++?
I understand how to split a string by a string by a delimiter in C++, but how do you split a string embedded in a delimiter, e.g. try and split ”~!hello~! random junk... ~!world~!” by the string ”~!” into an array of [“hello”, “ random junk...”, “world”]? are there any C++ standard library functions for this or if not ...
#include <iostream> #include <vector> using namespace std; vector<string> split(string s,string delimiter){ vector<string> res; s+=delimiter; //adding delimiter at end of string string word; int pos = s.find(delimiter); while (pos != string::npos) { word = s.substr(0, pos); ...
62,043,538
62,043,657
function pointer to overloaded static member - to use as custom deleter in unique_ptr
I have a class with static and overloaded member function. I want to use one them as a custom deleter in a unique_ptr there are lots of questions on this topic, none of them worked for me. #include <iostream> #include <memory> #include <functional> class A { public: static void release() { std::cout <<...
std::unique_ptr<int, void(*)(int*)> ptr(&i, &A::release); // ~~~~~~~~~~~~^ This way, std::unique_ptr's constructor will expect a specific type of a pointer, which will help the compiler resolve ambiguity. This: decltype(&A::release(int*)) is not a valid syntax. In order yo use decltype(e), you'd h...
62,043,831
62,043,897
Polymorphism calling a function from the base class
So I have these classes: class Base { public: Base() {cout << "made a base" << endl;} virtual void getType() const { cout << "Im a base" << endl; virtual ~Base() {} //other members... } class Derived: public Base { public: Derived() {cout << "made a derived" << endl; virtual void getType() const { ...
When you do Base* test = new Derived(): The V-Table pointer of object test is set to point to the V-Table of class Derived. Note that when the object is created - via new Derived() - you are explicitly calling a function (the constructor) of class Derived and not of class Base. And when this function is called, it sets...
62,043,960
62,044,087
Runtime Exception in converting set to vector and vector to string in c++
Hi I have just started learning c++ and i cant seem to make out why this code is giving me a runtime exception while converting a vector to set and set to vector. Please Help! #include <bits/stdc++.h> #include <iostream> #include <set> #include <vector> #include <algorithm> using namespace std; int main() { int n; ...
This code is wrong vector<int > v; for(int i=0;i<n;i++) {cin>>v[i];} Your vector is created at size zero, so v[i] is an out of bounds vector access whatever the value of i. Vectors don't grow just because you assign elements to them. Two possible solutions 1) Create the vector at the right size to begin with vector<i...
62,044,238
62,059,820
QDataStream read to QVector
I have a QByteArray containing 8 bits representing two floating-point numbers, what is the correct and simplest way to read QDataStream to QVector<float>? Code: QByteArray ByteFloatArray; QVector<float> qVecfloat; ByteFloatArray.append(0x41); ByteFloatArray.append(0x31); ByteFloatArray.append(0x99); ByteFloatArray.appe...
You can use QDataStream::atEnd() in a loop and read the float data like this : QDataStream myStream( ByteFloatArray ); myStream.setFloatingPointPrecision( QDataStream::SinglePrecision ); float f = 0.0f; while ( !myStream.atEnd() ) { myStream >> f; qVecfloat.append( f ); } qDebug() << qVecfloat; Output: QVect...