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,734,559
62,734,657
Why doesn't make_optional work for file streams?
I'm trying out the C++17 optional-type, and thought a fitting place to use it would be a function that attempts to open a file and maybe returns the opened file. The function I wrote looks like this: std::optional<std::fstream> openFile(std::string path) { std::fstream file; file.open(path); if (!file.is_op...
Your code will try and copy the stream, when you pass it to make_optional. Streams can't be copied, therefore, you need to move it, i.e., return std::make_optional(std::move(file)); or simply return file; (Depending on the age of the compiler, the latter might not work.)
62,734,791
62,734,857
expected '(' before 'val' Arduino error code
Okay so I'm new to Arduino coding. I am trying to create a program that will turn on a series of LEDs based on the analog input of a potentiometer. This is the code I wrote: #define red 4 #define blue 3 #define yellow 2 void setup() { pinMode(red, OUTPUT); pinMode(blue, OUTPUT); pinMode(yellow, OUTPUT); } vo...
You have incorrect C syntax in if's. Here is how to do it: if(val <= 341){ digitalWrite(red, HIGH); } if(val >= 682 && val < 1023){ digitalWrite(red, HIGH); digitalWrite(blue, HIGH); } if(val >= 1023){ digitalWrite(red, HIGH); digitalWrite(blue, HIGH); digitalWrite(yello...
62,734,894
62,735,061
Why does a local reference to a constant temporary value seem to outlive the method it's defined in?
I am quite puzzled to see why the following piece of code successfully compiles and seems to run correctly by displaying 7 twice. I suspect there is some undefined behavior lurking in both invocations. #include <iostream> template <typename T> const T& max(const T& x, const T& y) { return (x > y) ? x : y; } int m...
In your example, using var1 exhibits undefined behavior, as var1 is a dangling reference. Using var2 is fine. "The max() method creates two local reference variables to store temporary values 3, 7" No, that's not what happens. The caller of max() creates two temporaries, and passes references to them to max(). max it...
62,734,897
62,735,122
What is the point of `std::make_optional`
All the std::make_ are made redundant by C++17 with the introduction of Class template argument deduction (except make_unique and make_shared). So what is the point of std::make_optional? As far as I can tell it does the exact same thing as the deduction guides for std::optional. Is there a scenario where std::make_opt...
One example of the difference is when you want (for whatever reason) to make an optional containing an optional: #include <optional> #include <type_traits> int main() { auto inner=std::make_optional(325); auto opt2=std::make_optional(inner); // makes std::optional<std::optional<int>> auto opt3=std::optiona...
62,734,936
62,737,041
Can Windows's Wireless Network Connection Status window be opened programmatically?
Can a Wireless Network Connection Status window (see attached picture) be opened programmatically? The full title of the window is "Wireless Network Connection 12 Status", and its class is "#32770 (Dialog)". It belongs to EXPLORER.EXE process.
Doesn't seems if there's any other method to open an adapter properties either from command-line or programatically. A thread of Stack Exchange Super User says: There is no way to open up that specific property window directly. There's only a shortcut to the "generic" interfaces screen, being ncpa.cpl. There's simila...
62,735,210
62,735,332
Adding a struct into a map
I'm having trouble adding a struct into a map. I don't really understand the error. There are 2 errors: I can't declare a map with 'struct' type I can't use insert to 'insert' my struct into the map What am I doing wrong? #include <iostream> #include <map> int main() { typedef struct { std::stri...
There are several issues in your code: The struct should defined outside of the function main, can't see a reason why you want to define it there in this case, and since it is local inside of main, you can't use it anywhere else! You are using the C-style typedef struct ... StructName instead of simply using struct My...
62,735,290
62,735,628
what is std::exception::what() and why to use it?
I came from c++98, and i am trying to make my way in to c++11 and so on. i came across the public member function , std::exception::what, <=> virtual const char* what() const noexcept; from this example givin in c++ reference : what_example, i can understand the usage but i have a few questions: // exception::what #inc...
what is the noexcept at the end? It is a new specifier introduced in C++11. In very short, it means that the function will not throw an exception. noexcept has same meaning as throw(). did it bring something new? noexcept is an improvement over the old throw specifier, which has since been deprecated (C++11) and ...
62,735,351
62,735,506
Searching for and removing certain characters from strings in C++
I'm a novice programmer currently learning how to use C++. I'm trying to complete a challenge on CodeWars. The program is supposed to accept a string input, and remove all of the vowels contained in the string. First, I created a character array containing the vowels in lowercase and uppercase. Then I used the std::fin...
Problem with current code: str.erase(str[i], 0); This is incorrect. Let's look at string::erase function's signature in this case: basic_string& erase( size_type index = 0, size_type count = npos ); First argument is size_type, which is basically an unsigned long integer. It is the index of the char you want to r...
62,735,680
62,739,344
Is there a way to attach or anchor two QWidgets together?
I'm getting started with Qt and decided to build a full-screen text editor. I want to have a button (button with arrow in screenshot) attached to a QDockWidget which opens and closes it so the button is always visible to the right side of the screen and stay anchored to it when dock is visible or resized. My current ap...
You can achieve what you want by using a container for your text edit and the button. A QWidget instance can be used as an "invisible"*** container for other widgets. So in Qt Designer you add a widget as a central widget of the main-window, inside this widget you add the text edit and the button, then you set a vertic...
62,735,797
62,735,842
How can Arduino millis() - millis() equal anything other than 0?
So I know millis() returns the time passed since the program started running, right? Now I've run into a case where millis() is used in a delay like this: long dly = millis(); while (millis() - dly < 250) { yield(); // enough time to send response } How can the value of millis() - dly be more than 0? If the poi...
I am no ardunio coder, but having a look at the code: long dly = millis(); while (millis() - dly < 250) { yield(); // enough time to send response } At line 1, you define a variable that holds time passed since start then inside the while loop you retrive the current millis() until it is greater than 250ms. Exa...
62,735,918
62,736,087
Extending the lifetime of a temporary object without copying it
Consider the following code: #include <utility> #include <iostream> struct object { object(const object&) = delete; object(object&&) = delete; object() {std::clog << "object::object()\n";} ~object() {std::clog << "object::~object()\n";} void operator()() const {std::clog << "object::operator()()\n"...
Why is the lifetime of object x not extended past the function call even if a const reference has been bound to it? Technically, the lifetime of the object is extended past the function call. It is not however extended past the initialization of wrap. But that's a technicality. Before we dive in, I'm going to impose ...
62,736,279
62,736,680
Segmentation Fault in C++ implementation of Kruskal's Algorithm
I have written this code which implements the Kruskal's algorithm for Minimum Spanning Tree, which yields segmentation fault when I submit it to an online judge. I think I have narrowed the cause of segmentation fault to the part where I sort the edges. Still, I can't find the exact reason why this code fails. struct D...
Your compare function: bool compare(const pair<pair<int, int>, int> &p1, const pair<pair<int, int>, int> &p2){ return (p1.second <= p2.second); } does not provide a strict-weak ordering, since comparing 2 elements e1 and e2 with the same .second will return true for both e1 < e2 and e2 < e1, which is not allowed. ...
62,736,923
62,778,806
Attributes for main function parameters
Can I use attributes for main function parameters or is it implementation defined? Looks like main function has only 2 supported forms without attribute-list while the general function declaration syntax does have it. Example: int main([[maybe_unused]] int argc, char* argv[]);
Indeed there is no explicit requirement that attributes must be accepted for main function parameters basic.start.main. But on the other hand if you read dcl.attr.unused#5 you can't find anything special for main which says that is not allowed there. This attribute must be known by a compiler to be C++17 conformant, bu...
62,737,441
62,737,715
VS code C++ code runner setup in remote server
Hello I am trying to setup VS code code runner setup in a remote server so that I can use the VS code debugger. Usually when I run code from the terminal, I have to at first load the g++ module. My usual c++ compile and run sequence goes as: module load Compilers/gcc-4.9.2 g++ -o test test.cpp ./test Now after install...
In your Visual Studio Code UI below right, you'll find the possibility to call the setting for your workspace: You should be able to update your setting to find the installed compiler in your remote system. The JSON setting looks like this: { "configurations": [ { "name": "Linux", "...
62,737,525
62,737,736
How to fix "error: ‘_1’ was not declared in this scope"?
I'm currently trying to bind a function to an algorithm I'm intending to use. #include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ vector<int> coll{1, 2, 3, 4, 5, 6}; vector<int>::iterator pos; pos = find_if (coll.begin(), coll.end(), bind(greater<...
You need to include <functional> and use std::placeholders::_1 pos = find_if (coll.begin(), coll.end(), bind(greater<int>(),placeholders::_1,3)); An easier option is to use a lambda: pos = find_if(coll.begin(), coll.end(), [](int v) { return std::greater<int>{}(v, 3); }); or pos = find_if(coll.begin(), coll.end(), []...
62,737,701
62,737,755
Error with constructing a dynamic array of threads in C++, using the thread class
As a part of a uni project I have to create a program which can have an arbitrary amount of threads given as a command line argument. I first tried making a dynamic array of threads like this: thread* threads = new thread[numThreads]; ( Note: I want to use the threads class, not pthreads ). I figured it didn't work be...
Use std::vector<std::thread>, as follows std::vector<std::thread> threadsVec(threadsNumber); for(size_t i{}; i < threadsNumber; ++i){ threadsVec[i] = std::thread{.....}; } and when you put the args make sure you use std::ref(arg) when your function need a reference because std::thread takes rvalues only, hence you...
62,737,935
62,738,031
Is there a way to fill a map of vector in one line
I'm filling a map of vector, and I'd like to know if there is a way to do it in one line, instead of creating a temporary variable. I'm doing that : map<string, vector<AnEnum> > myMap; AnEnum tempEnum; vector<AnEnum> tempList; tempList.push_back(tempEnum); myMap["key"] = tempList; I tried to do this myMap["key"] = ve...
Using brace-initialisation (since C+11) you can do this: myMap["key"] = { AnEnum{} }; which will implicitly create a vector containing 1 AnEnum element for the key "key". You can have more elements by having more elements separated by commas (e.g. { AnEnum{}, AnEnum{} }) if you want. You can also create the whole map...
62,738,001
62,738,400
Using cout in the constructor of a class that is included in another class as a static member
Following code #include <iostream> struct A { A() { std::cout << std::endl; } }; struct B { static inline A a; }; int main() { } succeeds after compiling with gcc, but crashes with segmentation fault after compiling with clang. Is the code not standard or is clang wrong? https://godbolt.org/z/tE...
Cppreference on std::ios_base::Init reads: The header <iostream> behaves as if it defines (directly or indirectly) an instance of std::ios_base::Init with static storage duration: this makes it safe to access the standard I/O streams in the constructors and destructors of static objects with ordered initialization (as...
62,738,148
62,738,216
How to save and extract custom data from streams?
I am saving data with ofstream to a file and trying to extract from it with ifstream. Only the saving process works, but when I try to extract it's starting to give me garbage data. I want to save this way using ofstream ofstream & operator<<(ofstream &ofs, Item &i){ ofs<<"Item name "<<i.name<<endl; ofs...
This should work istream & operator>>(istream &ifs, Item &i) { string dummy; ifs >> dummy >> dummy >> i.name >> dummy >> dummy >> i.price >> dummy >> dummy >> i.qty; return ifs; } The purpose of the dummy variable is to read (and discard) the extra labels you added to the output Item name ...
62,738,208
62,738,267
Why does this case statement need an "if else" and not just an "if"?
So I am new to C++, and I am working through a pdf tutorial that is getting me started with basic stuff. I was writing a simple case program, and I experienced something weird. #include "pch.h" #include <iostream> #include <string> using namespace std; enum string_feeling { eGood, eBad, eOk, }; string_fe...
When none of conditions in the three if statements in hashit function become true, no return statement is executed in the function and undefined behavior is invoked. (Quote from N3337 6.6.3 The return statement) Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavi...
62,738,326
62,739,781
How to overload operator += in cpp?
I have some problem with overloading += operator I want to add a item to vector (getAuthorList) with += operator How can I do it in main ? Code snippet (header file) : class Author { public: Author(std::string firstName, std::string lastname, std::string affiliation); std::string getFirstName(); std::st...
You can overload += operator like this void operator+=(Author); Change the operator return type to void as you are storing it in Publication class so it does not make any sense to return The same author from this operator. you can write the operator definition like this void Publication::operator+=(Author auth){ t...
62,738,410
62,755,357
How to keep track of source code call stack
I'm trying to re-implement a C++ code in Go. Specifically, I'm focused on meshToVolume tool of OpenVDB library. As shown by a manually-prepared code flow screenshot, even a rough call stack map is pretty perplexing. I'm looking for a tool to help me keep track of call stack and the code flow. So far: I've looked at th...
Using Doxygen, I could finally visualize call graph! Approach Downloaded and installed Doxygen. Then ran Doxywizard i.e. Doxygen GUI front-end. OpenVDB has a doc directory which is set as the working directory from which Doxygen will run. Without selecting these options, call graphs didn't get generated for me: I hav...
62,738,560
62,741,750
How to access Sets of pairs in c++
#include<bits/stdc++.h> using namespace std; #define ll long long int main(){ set<pair<ll,ll>>s; s.insert(make_pair(5,6)); s.insert(make_pair(5,4)); s.insert(make_pair(3,7)); s.insert(make_pair(6,8)); auto it=s.upper_bound(make_pair(4,0)); cout<<*it.first<<endl; } It's printing: err...
In this expression: *it.first the operator . has higher precedence than *. So the expression becomes: *(it.first) which is not correct. You need to disambiguate with parentheses, like this: (*it).first or even better, use the -> operator like this: it->first
62,738,693
62,739,061
is there a way to cast a long double to a double and scale the range accordingly in c++?
I am working with the genetic algorithm in c++. In order to speed up evolution i am exponentiating fitness values in such a way that i use the entire range of long double. This makes the difference between scores greater and makes good scores much better than mediocre scores, such that the good scores are (exponentiall...
I would suggest to calculate the real fitness value and do the desired scaling in the selection step. Currently, you are mixing the fitness calculation with the fitness scaling. Dividing this two steps has also the advantage, that you can experiment with different fitness scaling strategies. You can look at the followi...
62,738,757
62,738,825
Ho to get a string till the last occurrence of a character
EDIT 1 I forgot to say that the string has to be taken from cin I have a string like "Hi; my;; name is Andrea; and I like C++". I want to create a stringstream initialized with that string and get everything before the last ;. This is what I've tried: string ex("Hi; my;; name is Andrea;; and I like C++"), text, fin...
Here is another solution using find_last_of: #include <string> #include <iostream> int main() { std:: string test = "Hi; my;; name is Andrea; and I like C++"; auto pos = test.find_last_of(";"); if ( pos != std::string::npos) std::cout << test.substr(0, pos); } Output: Hi; my;; name is Andrea Using a ...
62,738,817
62,738,882
how to change the visibility of a vector of unique pointers
In the ONG class i created an add function that adds a participant (director, administrator, staff) in a vector of participants. std::vector<unique_ptr<Participant>> ls; I tried to put the vector as the public variable out of function but it didn't work When I want to add inside the function everything works correctly...
The problem is that class ONG is an abstract class because it inherits from Participant which has a pure virtual function. If you define void tipareste() { //Do stuff } inside ONG (or inside a class which ONG inherits) then assign an ONG object to the ONG pointer int main() { std::shared_ptr<ONG> ong = s...
62,738,990
62,790,258
Resolve variadic argument to function pointer
Windows 10, Visual Studio 2019, C++17: Compile error: cannot convert argument 2 from 'int (__cdecl *)(int)' to '...' //////////////////////////////////////////////////////////////////// // This is the templated function that becomes a variadic argument // template <typename siz> int func(siz size) { // ... // ...
The issue is func is being treated as a function pointer, but pointers to template functions are not allowed in C++. You need to specify the type you plan to use when you reference func, like: result = usefunc(0, func<int>); You can use decltype to reference the type of a variable, to be a little more flexible: result...
62,739,119
62,739,948
Why does function call go directly to return statement?
I am a BEGINNER. I wrote a function to multiply big integers. When the function multiplybig(string a,string b) is called it goes directly to the return statement of the same function. I dont know where exactly the bug is. can someone please help me with this? #include<iostream> #include<string> using namespace std; str...
To sum up the comments: Don't use VLAs int ar1[a.length()] , ar2[b.length()] ; int ans[a.length()+b.length()]={0}; are VLAa. Those are not part of the standard, but a compiler specific extension. The right way would be to use std::vector: std::vector<int> ar1(a.length()); std::vector<int> ar2(b.length()); std::vector...
62,739,177
62,739,201
why the "function-try" is not work in C++?
Today I saw function-try in cppreference. When I wanted to use a test code to verify, I found that it can't catch exceptions; is there a problem with the way I use it? #include <iostream> [[noreturn]] void foo(const std::string& str) #ifdef _DEBUG try #endif { str[-1]; } #ifdef _DEBUG catch (const std::exception& ...
str[-1] will not throw. You can do str.at(-1) to throw an exception. If you do not use the results it might well be optimized away by the compiler. Do volatile auto val = str.at(-1);
62,739,186
62,742,275
Segmentation fault in array for max index difference problem
I wrote this c++ function to find the maximum index difference in an array given that arr[i]<=arr[j] this runs fine with the given test cases but when i submit the code it shows segmentation fault constrains :- 1 ≤ T ≤ 1000 1 ≤ N ≤ 10^7 0 ≤ A[i] ≤ 10^18 long long maxIndexDiff(int arr[], int n) { // Your...
It should not work properly for N=1, because in this case the while(low<high) loop will be finished without a single iteration and both i_index and j_index will stay unitialized.
62,739,337
62,741,411
Getting SIGSEGV (segmentation error) for the given problem. (Finding LCA of a generic tree)
So, I was trying to solve the below problem using the most basic method i.e. storing the paths and finding LCA. My code is working fine on VSCode and giving the right output. But when submitting on SPOJ, it gives runtime error (SIGSEGV). Problem Link: https://www.spoj.com/problems/LCA/ Problem Description: A tree is an...
Some bugs are easy to find, when you know how to find them. The tools every programmer should know about are valgrind and -fsanitize. Remember to always compile with warnings enabled and fix them. Compiling your code with: g++ -Wall -Wextra -fsanitize=undefined 1.cpp && ./a.out </tmp/2 results in a helpful warning: 1....
62,739,338
62,739,841
How does static_cast behave when cast to a totally different class?
I was making some excercise for learning inheritance and virtual methods in c++. So i found myself into this: class A{ public: virtual void f() const {cout << "A::f";} virtual void g() {cout << "A::g"; m();} virtual void h() {cout << "A::h"; f();} void m() {cout << "A::m"; f();} virtual A* n() { cou...
This casts a C* object to an A* object (via n()) and then casts an A* object to B* object. Finally it calls a virtual function. So what happens in practice? The compiler will look to the virtual table of the underlying object and find there what function f to call. The virtual table is an actual table in memory. So all...
62,739,874
62,740,048
Can i establish a tcp/ip socket with a python server but a c++ client?
I'm new to tcp/ip programming and I'm trying to establish a tcp/ip connection that sends a byte from my python server to a c++ client. Is this possible or does the client and server have to be written in the same programming language?
Tcp connection does not depend on programming language you could make connection between two processes one of them should be listen for another(server) and the other should send sync packet to request a connection(client). You could implement two mentioned components with every language programming.If you need more h...
62,739,886
62,739,927
How to check whether two std::vectors are equal in less than O(n) time complexity
We can compare two vector using for loop like this bool checkEquality(vector<int> &A, vector<int> &B){ if(A.size() != B.size()) return false; int i=0,j=0; while(i<A.size() && j<B.size()){ if(A[i++] != B[j++]) return false; return true; ...
is there any better way to check whether two vectors are equal Yes there is: A == B works fine, and is much simpler than your code. is A == B faster than O(n) No, that would be impossible in the general case. We can only do better than O(n) if we know something about the data, such as that differences are always f...
62,739,912
62,739,949
I'm not able to get the output for the following code
I want to print the numbers like this: 1| 2| 3| 4| 5| 6| 7| 8| 9| 10| 11| 12| 13| 14| 15| 16| So, I'm using a code like this: #include<iostream> #include<conio.h> #include<cstdlib> #include<stdio.h> #include<time.h> #define GRID_SIZE 4 using namespace std; class Game { private: char grid[GRID_SIZE][GRID_SIZE]; p...
So the problem is here char grid[GRID_SIZE][GRID_SIZE]; You are saying that the grid consists of single characters only. Since you want the grid to be made of numbers, why didn't you write this? int grid[GRID_SIZE][GRID_SIZE]; and this grid[x][y] = n; n++; If you really want the grid to be multiple characters then y...
62,740,086
62,740,118
Subroutine, without using pow, and with parameter and return
i don't understand what is wrong with my code it needs to have parameters and return, in c++ #include <bits/stdc++.h> int p(int,int); int main() { int a,b,c; scanf("%d",&a); scanf("%d",&b); printf("%d\n",c); return 0; } int p(int a,int b){ int t,i,c=1; for(i=1;i<=b;i++){ t=a; c=c*t; return ...
I expect you meant to write this code int p(int a,int b){ int t,i,c=1; for(i=1;i<=b;i++){ t=a; c=c*t; } return t; } In your version the return statement is inside the for loop. And as has been pointed out, you probably meant this printf("%d\n",p(a,b)); instead of this printf("%d\n",c);
62,740,130
62,741,899
Construct a span<shared_ptr<T>> from an array<shared_ptr<void>>
I've got an std::array<std::shared_ptr<void>, N>, and I have methods for accessing parts of this buffer as different types, which I would like to use std::span<std::shared_ptr<T>> for. Is there a way to construct a span like this without invoking UB?
No, this is impossible: regardless of the ability to convert void* to T*, you can’t convert void** (a pointer to your first pointer) to T** because there are no actual T* objects there, and you certainly can’t convert std::shared_ptr<A>* to std::shared_ptr<B>* for any distinct A and B—std::shared_ptr<T> isn’t just a T*...
62,740,290
63,069,837
identify equal named functions from different additional dependencies
I have a C++ project in Visual Studio where libs (oldVersion.lib, newVersion.lib) are added via project properties -> Linker -> Input -> Additional Dependencies. Both libs contain the same function (e.g. foo()). The functions are included by their header files and called via ::foo(). The code itself does not show an er...
I am sorry for that I should provide a better plan rather than a complicated method. Here is the method: Just tell the linker that the symbols in a library are known by some other name and use that name. You need to make a def file and provide the name translation in the EXPORTS section. The process would be to make a ...
62,740,510
62,740,714
how to add an element to the string position of a vector
I want the add function in the Carnet class to add a number to a position (position to be a string) and when I display myclass << ["string"] to display the number the problem is that when I run the instructions in the main it shows me wrong(7,7,7), instead of showing me 7,9,10 I think the problem is saving in vector bu...
The problem is here: Carnet add(string a, int b) { this->insert(this->begin() + atoi(a.c_str()), b); return *this; When you returning by value, you are making a copy, which means here cat.add("OOP",7).add("FP", 10); the second add will operate on a new object instead of on cat. You should use a reference inst...
62,740,877
62,740,968
What kind of memory allocation (dynamic or static )does the following code do?
#include <iostream> using namespace std; int main() { int n; cin>>n; int arr[n]; return 0; } The size of the array is entered by the user at the run time, but the memory is allocated on the stack. What kind of memory allocation is this? Static or Dynamic ?
with all the reserve associated to the variable length array in C++, this is a it is a dynamic allocation in the stack dynamic because the size if unknown at compile time and in the stack rather than in the heap because not like int * arr = new arr[n]; even this is dependent on the compiler. The associated problem is ...
62,741,185
62,742,199
Why is C++'s file I/O ignoring initial empty lines when reading a text file? How can I make it NOT do this?
I'm trying to build myself a mini programming language using my own custom regular expression and abstract syntax tree parsing library 'srl.h' (aka. "String and Regular-Expression Library") and I've found myself an issue I can't quite seem to figure out. The problem is this: When my custom code encounters an error, it ...
std::ifstream::getline() does not input the delimiter (in this case, '\n') into the string and also flushes it from the stream, which is why all the newlines from the file (including the leading ones) are discarded upon reading. The reason it seems the program does not ignore newlines between other lines is because of:...
62,741,362
62,741,440
Is it good practice to return an error to the caller instead of throwing the error right away in C++
Is it considered good practice to return an error to the caller function like in Go, or should my program throw an error instead when it encounters it?
There are different common practices w.r.t. error handling in C++ - as it is a multi-paradigmatic language. For example: Return status/error codes rather than results. Return results only, throw exceptions on error. Return value-or-error objects, such as std::expected. Each of these has pros and cons. The most import...
62,741,376
62,741,475
Compare with a value that is outside the sequence
What happens if you compare a value (that belongs to an array) with another value that does not belong to the same array (it is outside the sequence) char arr[] = "yo"; strchr(arr + 3, '\r') Can this ever crash a program? Or does it just compare to a char that is somewhere else?
arr if of type char[3]. arr + 3 is a pointer pointing to 1 past the last element of the array. It is legal to obtain a pointer to 1 past the last element of the array, but it is Undefined Behavior to dereference it. strchr expects the first argument to be a pointer to a null terminated C string. Passing the above point...
62,741,570
63,847,175
How a std::unordered_map search algorithm is implemented?
I understand that if it is necessary to implement a search in an ordered set, then we compare the data of each "cell" of the binary tree, which is the structure of the ordered set using the "<" operator of the appropriate type, but I don’t understand how everything works in the case of std::unordered_map. Where can I f...
You can search through a std::unordered_map for a key with a code like below: (here key variable equals to the key you are searching): if (your_map.find(key) != your_map.end()) { ... } If you want to search for a value you can use for loop like this: for (const auto& pair : your_map) { if (pair.second == the_v...
62,741,681
62,742,186
Vector valued function as argument in c++ class definition with Eigen
I'm writing a numerical methods for a specific ODE of the form y'(t) = A*y(t) + g(t,y) in C++, where A is a matrix and g is a vector function, i.e. a function that takes as input the time and a vector and return a vector. I'm using the library Eigen. I'm writing my own class, but I can't understand how to pass the vect...
Instead of using function pointers I prefer to use proper C++11 function objects. The function g(t, y) would then have the following type; std::function<VectorXd (double, const VectorXd&)> g; This type could be used in your class constructor. As you mentioned, the typical size of your vectors is n=8000. For that size ...
62,741,921
62,742,277
OpenGL 16 bit stencil buffers?
I am trying to create framebuffer with 4 colour attachments, a 16 bit depth buffer and a 16 bit stencil buffer. I need 16 bits for the stencil buffer because I store object ID's in them for object picking, and I have a lot more then 255 objects. I create two render buffers: glBindRenderbuffer(GL_RENDERBUFFER, mID); glR...
A separate depth and stencil buffer attachment need not be supported. See OpenGL 4.6 API Core Profile Specification - 9.4.3 Required Framebuffer Formats [...] However, when both depth and stencil attachments are present, implementations are only required to support framebuffer objects where both attachments refer to t...
62,742,373
62,742,693
Using std::set with a key-based comparator
Suppose I have a set (or map) of strings, and I want to use a custom comparator that compares only the first 5 characters. So "abcde" and "abcdef" are the same in my set. typedef std::set<std::string, Cmp> MySet; What is the best way to write Cmp? The obvious way is like this: struct Cmp { bool operator()(const st...
You can customize Cmp with a key policy. Minimal example: template<class Key> struct Compare_on { Compare_on(Key key = Key()) : key_(key) {} template<class T> bool operator()(const T& x, const T& y) const { return key_(x) < key_(y); } private: Key key_; }; struct First3 { std::str...
62,742,395
63,363,883
Can I embed the scaled method for a QPixmap derived class?
I would like to have each QPixmap derived object at the wanted size upon creation. Let's say I have this fictional class: #pragma once #include <QPixmap> #include <QString> class MyPixmap : public QPixmap { public: enum class Size { icon, veryVerySmall, medium, large }; static int toInt(Size size); MyPix...
As Igor Tandetnik stated, it's possible to create an immediately scaled pixmap by calling the scaled method and passing its return value to a copy constructor as follows: MyPixmap::MyPixmap(QString path, int height, int length) : QPixmap{ QPixmap{ path }.scaled(size, size) } { }
62,742,615
62,742,667
undefined reference class method minimal example
ive been programming alot of java lately and trying to get back into cpp. Im working on small example and have some issues importing classes/headers or whilst linking. I get a undefined reference using this code at line 5: mc.getval(). Hopefuly you can tell me where my import/linking is off. Thank you! minmain.cc #incl...
minclass.cc should look like this #include "minheader.h" int MinClass::getval() { return val; } And minheader.h should have the complete class definition including the val member variable. #ifndef MINHEADER_H #define MINHEADER_H class Minclass { int val = 5; public: int getval(); }; #endif It's...
62,742,911
62,811,762
Qt3D - Instance rendering of 2 squares. PrimitiveType? InstanceCount?
I'd like to display on the screen 2 squares using instance rendering. The problem is : When I draw 2 squares, they are connected. I can't draw multiple separate square. I know it has to do with PrimitiveType : i'm using Qt3DRender::QGeometryRenderer::LineLoop or Qt3DRender::QGeometryRenderer::TriangleFan but is there ...
Actually, I just found an example of instanced rendering here. They subclassed QSphereGeometry and performed the instanced rendering in a shader. You could create a RectangleGeometry which holds the vertices for one triangle and equip it with the same functionality as the InstancedGeometry in the example. Result:
62,743,191
62,743,213
C++ How to create a new object while assigning it to another
I want to transform this C# code into C++ : list.head = new LinkedListNode("head node data"); How can i do this in C++ with one line, i dont want to do this: LinkedListNode headnode("head node data"); list.head = headnode;
In c++, you would do: list.head = new LinkedListNode("head node data"); assuming list.head is of type LinkedListNode*. If list.head is of type LinkedListNode, then you can simply do: list.head = LinkedListNode("head node data");
62,743,201
62,743,258
No matching function in rectangle class
So im making a program the take the width and height, using 3 classes. The first to initialize the 2 variable, the second to print the value from the third class. #include<bits/stdc++.h> using namespace std; class polygon { protected: int width, height; public: polygon(int a, int b) { ...
Because you didn't specify a polygon constructor to call in the rectangle(int, int) constructor, it implicitly calls the default constructor from polygon -- but there is no such constructor, so you get this error. You need to explicitly chain to the appropriate polygon constructor, and then you can also remove the ass...
62,743,296
62,743,341
Assigning to struct member using structType*&
I am ok with pointers, but am confused when dealing with test*& t in this program. My understanding, which may be incorrect, is that t contains the address of root and root itself is a pointer to an undeclared(?) struct of type test. I understand what the error means. I am essentially saying 0="abc", but I am unsure of...
... when dealing with test*& t in this program. My understanding, which may be incorrect, is that t contains the address of root and root itself is a pointer to an undeclared(?) struct of type test ... root itself is a test*, that's correct. But t is a reference to root, not the address of root. So you should use t j...
62,743,667
62,743,749
Compilation error when trying to obtain a pointer to the size of a vector
I have a std::vector<int> instance called arr, and I want to work with its length using pointers. My declaration unsigned int *ptr = &arr.size(); gives me a compilation error: cannot take the address of an rvalue of type 'size_type' (aka 'unsigned long'). This error persisted even after I changed the type of the poin...
In this code: std::vector<int> arr; unsigned int* ptr = &(arr.size()); the result of arr.size() will be some temporary value, such as 42. You are simply not allowed to take the address of a temporary, regardless of whether the type of ptr is correct. If you want an iterator to the end of the vector, you can do: auto i...
62,744,123
62,747,694
What is a generic and portable way to get at underlying bits of a type in C++?
I want to take an arbitrary type that is no bigger than a pointer and get at its bit representation. I tried to use std::bit_cast, but that requires both types are the same size. But, because of genericity, I don't know what size the input type will be. I wrote this function: template<class To, class From> To sloppy_bi...
You can trivially arrange to have the correct amount of memory: template<class T> auto get_bytes(const T &t) { std::array<std::byte,sizeof t> ret; std::memcpy(ret.data(),&t,sizeof t); return ret; } This works even if T is not trivially-copyable, although you then can’t put the bytes back in a T. (std::bit_cast<...
62,744,390
62,744,466
Modified Fibbonaci C++ getting a large negative number
Ok so, I'm doing hackerrank's Fibonacci modified question. I am able to solve this question only when the iteration goes to 8 anything pass that and it starts returning a large negative number. I thought this was because of an integer overflow so I changed my types to unsigned long long yet the problems still persist. ...
In C++, the general range of an unsigned int is 0 to 4,294,967,295, so using an unsigned int will not be appropriate for this problem. The expected output is actually larger than the maximum possible value of even an unsigned long long int, which goes from 0 to 18,446,744,073,709,551,615. This means that you cannot use...
62,744,755
62,744,787
Reading from multiple lines from a txt file in a single iteration
I am working at the moment with linked lists, and my nodes have 4 elements( where each of them is a variable type string). In a .txt file there are groups of text where each group has 4 lines, for example: This is the first line This is the second line This is the third line This is the fourth line '\n' This is the fi...
Easy enough while (getline(in, node.string1) && getline(in, node.string2) && getline(in, node.string3) && getline(in, node.string4)) { ... string dummy; getline(in, dummy); // skip blank line } You can also use in.ignore(std::numeric_limits<std::streamsize>, '\n'); to skip the blank line, bu...
62,744,807
62,744,917
Declarations vs. Definitions at the top of your program (Best Practice)
Using a function declaration at the top of your function, then later defining it under main seems a bit redundant. Considering the practices of DRY, is standard practice in the C++ community to simply declare the function fully at the top (or even just define in a seperate functions.cpp file, with declarations in the h...
There are cases where you have no choice other than first providing a declaration and then the definition. For example when there is mutual dependency: int bar(int x); int foo(int x) { if (x == 1) return bar(x); return x; } int bar(int x) { if (x==0) return foo(x); return x; } Seperating declaration a...
62,744,862
62,744,932
C++ the system cannot find the file specified error
When i start my code i get 'the system cannot find the file specified' error. What's wrong? #include <iostream> using namespace std; int main() { cout << "Hello world"; return 0; } https://i.stack.imgur.com/QoY3I.png <--- Here is my problem
Your executable did not build. If you look in the console output you have an error: cannot include crtdbg.h. This is the error you have to fix. This might help: How do I get crtdbg.h file?
62,744,981
62,745,408
Check whether 2 trees have same inorder or not
I was solving this problem using 1 array but while traversing the second tree am always getting false as an answer. Couldnt able to understand where to put the true condition . I could have solved it using queue also by checking the front element and checking whether the queue is empty at the end or not but i would lik...
i don't understand why you are doing it this way. A simpler method would be to create a second vector from the second tree and compare the vectors. std::vector<int> v1; std::vector<int> v2; inorder(tree1,v1); inorder(tree2,v2); if(v1==v2) std::cout<<"the same\n"; else std::cout<<"not the same\n"; EDIT: if you ...
62,745,093
62,745,179
Specializing a template for std tuple without requiring users to do remove_cvref
As you maybe know since C++ does not support list of types except in special cases most people just use tuple as ugly list of types. So for example to check if some list contains only fp numbers one might do this: template <typename T> struct AllFp {}; template <typename... T> struct AllFp<std::tuple<T...>> { static ...
With Boost.Mp11, this is a short one-liner (as always): template <typename L> using AllFp = mp_all_of<std::remove_cvref_t<L>, std::is_floating_point>; Note that std::remove_cvref_t is actually C++20. For earlier standards, you can just do std::remove_cv_t<std::remove_reference_t<L>> or just std::decay_t<L> for brevity...
62,745,150
62,745,823
How can I get C++ to 'tally up' the results and produce a plan?
I'm doing an exercise where I have to write a program that will suggest a subscription plan based on the users answers to a series of yes-or-no questions. The exercise is based on this chart: https://imgur.com/a/AEMw5Ln Here's my code so you can see what I've done so far... // Firstly, Welcome the client! cout << " Wel...
A switch statement might make the code at the end with storage capacity look nicer, as well as being easy to implement but this is a matter pf preference alone, there is little to no benefit to the program itself. Also change the if statement contents from assignment operator (=) to comparison (==) as the comment said...
62,745,184
62,745,323
'using namespace {some namespace nested inside of another}`
Is it possible to access the type Foo under the namespace first by using a using declaration (or something similar) in the caller code? namespace first { namespace second { struct Foo { int i; }; } } int main() { using namespace first::second; first::Foo foo { 123 }; return 0; } I ge...
You have several options: using namespace first::second; Foo foo{123}; namespace ns = first::second; ns::Foo foo{123}; I guess you could also do namespace first = first::second;. Then first::Foo foo{123}; would work, but to access the contents of the actual namespace first (other than those in namespace second...
62,745,385
62,746,295
How to write unordered set of vector of vector, namely unordered_set<vector<vector<int>> set?
I wanna have a set to store several graphs, and each graph has several dots, and each dot has its own coordinate. So here is my code: unordered_set<vector<vector<int>> set; vector<vector<int>> graph; graph.push_back({1,1}); graph.push_back({2,2}); set.insert(graph); Then the failure shows that set expect two arguments...
I would declare class or struct named: Point that contain two int variables and push every point to the graph (that now need to be vector<Point>) and then push the graph to your set (you can also declare class or struct named: Graph that contain vector) and then your code should be : unordered_set<Graph> set; Graph gra...
62,745,686
62,745,743
Add bool variable to int
I have in my code a boolean function "lookup" which has the parameter byte: lookup(byte). My variable _size is an integer. Is it good practice to do stuff like following: _size += !lookup(byte); I mean the point is the implicit cast from bool and int. Otherwise I have to do something like this if (!lookup(byte)) { ...
The expression !lookup(byte) is guaranteed to have one of the values, true or false. When used as an int, these are converted to 1 and 0 respectively. So the following 2 snippets: _size += !lookup(byte); // true -> add 1, false -> add 0 and if (!lookup(byte)) { // if true _size++; // add 1 } are equival...
62,745,940
62,746,069
Vector of structs with unique_ptr
I've already read many answers for the similar questions, but still cannot find a solution for my problem. I have the struct: struct Param { std::string name; std::unique_ptr<Object> default_val; }; I have the class Function that stores a vector of Params. Somewhere I create a vector of this params and need to...
Param is not copyable, because one of its member isn't. Since a vector is as copyable as its contents, then a vector of Param is not copyable. When you do this: Callable(const Params & params) : params(params) {} You're trying to use vector's copy constructor. That won't compile. You'll need to instead move the input ...
62,746,213
62,780,431
Detect C++ inline symbols in COFF object file
I would like to generate a .def file for building a DLL with the MSVC compiler. I used LLVM to search through the compiled .obj files to find all definitions of C++ functions or variables. I would like to distinguish between normal definitions and inline definitions to only export the normal definitions in the DLL. I u...
I found a solution myself, the information is contained in the COMDAT section definition, see https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#comdat-sections-object-only. This is my code using LLVM to detect definitions: void process_obj(const llvm::object::COFFObjectFile &object) { std::vector<bool...
62,746,556
62,746,563
Template Argument Deduction for Tuple Index
template < typename TYPE, typename TUPLE, int INDEX > void fun( TYPE& a, TUPLE b ) { a = std::get<INDEX>( b ); } Calling the above is tedious: //... using tuple_t = std::tuple<int, double, double>; double d; fun<double, tuple_t, 1>( d, std::make_tuple( 1, 2.3, 4.5 ) ); //... Is there a better way? For instance: fun...
Make int INDEX the first template parameter. Specify it when calling the function, and allow the other parameters to be deduced: fun<1>(d, std::make_tuple(1, 2.3)).
62,746,705
62,747,244
What is the purpose of "quoted metafunction" in boost mp11?
I am trying to learn basics of boost::mp11, docs are ok, but one thing I do not understand is the following: what is the purpose of quoted metafunctions? Docs say this: A quoted metafunction is a class with a public metafunction member called fn, for example struct Q1 { template<class...> using fn = void; }; struct ...
From slide 14 in http://www.pdimov.com/cpp2/mp11_slides.pdf: So basically, this seems to be your guidance: When you get the "can’t expand into a fixed parameter list" error, try quoting the metafunction and using the _q algorithm instead
62,746,886
62,748,170
Why is the __stdcall calling convention ignored in x64?
I know what the differences between __cdecl and __stdcall are, but I'm not quite sure as to why __stdcall is ignored by the compiler in x64 builds. The functions in the following code int __stdcall stdcallFunc(int a, int b, int c, int d, int e, int f, int g) { return a + b + c + d + e + f + g; } int __cdecl cdeclF...
Why does x64 use mov rather than push? I assume it's just more efficient and wasn't available in x86. That is not the reason. Both of these instructions also exist in x86 assembly language. The reason why your compiler is not emitting a push instruction for the x64 code is probably because it must adjust the stack ...
62,746,971
62,747,183
Add a subchild in xml using Tinyxml
Hi im trying to add a subchild to my XML generated file. I've been reading through the manual and I can't quite figure out how to add it in my C++ code. Any ideas ? Current code: #include <Tinyxml.h> TiXmlDocument doc; TiXmlElement* msg; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChi...
You can just repeat those lines: msg = new TiXmlElement( "child" ); msg->LinkEndChild( new TiXmlText( "Welcome to my child" )); msgs->LinkEndChild( msg ); So, e.g. in a loop: for (int i = 0; i < 10; ++i) { std::string name = "child" + std::to_string(i); msg = new TiXmlElement(name); msg->LinkEndChild...
62,747,036
62,747,405
undeclared identifier with OpenGl in vertexShader, i have a problem drawing a triangle in the vertex shader
"Fallo al compilar vertexShader ", gl_position" : undeclared identifier. And: "assign" : cannot convert from "attribute 4-component vector of highp float" to "highp float" I get the error that is above when a i compile this script, and i don´t really understand why it gives that error in the VertexShader #include <G...
GLSL is case sensitive, you should use gl_Position instead of gl_position. Unfortunately, I can't reproduce the second error.
62,747,096
62,747,113
Quadratic formula outputting 0 and -0 regardless of the terms given
I am trying to make a program to find the zeros of any given trinomial, the formula seems right but I don't know why the output is always -0, 0. I thought it was a compiler or IDE error but nope, same error in both VS Code 2019 and Code Blocks. There is some weird logic error I am not seeing. Also, I am well aware I do...
cin >> a, b, c; really doesn't do what you want. It's pretty similar to cin >> a; b; c;, which is pretty similar to cin >> a;. You want cin >> a >> b >> c. As an aside... A reasonable compiler would also warn you about this behavior. Since it's unlikely what to be what you intended. > clang++ -o main main.cpp main.cpp...
62,747,274
62,747,290
Ambiguous call of overloaded class method
I am implementing a class for rational numbers. I've created a constructor with parameters and all of my methods. I tried to add a default constructor as well, in the case that no parameters were provided. These are the relevant sections of the code: Rational::Rational(int numer, int denom){ //Constructor numer = n...
The default arguments in the first constructor already handle the case where no values are given. You shouldn't also create a default constructor. Delete it and your code will compile. Rational::Rational(int numer, int denom){ numer = numer; denom = denom; } Rational::Rational(){ int numer = 1; int denom = ...
62,747,525
62,842,602
GLSL Simple example shows blanks screen on OSX
I'm trying to make a simple program to work. I am using SD2 + OpenGL Shading Language. Also, I'm trying to this on MacOS, more precisely 10.15.5. I know Apple is deprecating OpenGL in favor of Metal, but it seems they are still supporting at least up to OpenGL 4.1. This is a simplified version of the program I'm trying...
Ok. I made it work. The problem was this lines: glGenVertexArraysAPPLE(numVAOs, vao); glBindVertexArrayAPPLE(vao[0]); For some reason, the APPLE version of those doesn't work. What I did is: Install GLEW with brew (which I thought I didn't need) Update my cmake file to link glew correctly Add glew headers and glew_in...
62,747,560
62,747,581
Conditions in While loops
#include <iostream> int main() { int sum = 0, value = 0; // read until end-of-file, calculating a running total of all values read while (std::cin >> value) sum += value; // equivalent to sum = sum + value std::cout << "Sum is: " << sum << std::endl; return 0; } I studied while loop is used to loop over a given ...
The expression std::cin >> value returns a value (a reference to the stream std::cin). The value is implicitly casted to true if the read was successful and to false if the read failed. The function std::basic_ios<CharT,Traits>::operator bool is used for the implicit cast. I think cppreference can describe it better th...
62,747,634
62,747,675
Initialize members of a class in C++
I have a class with the following declaration: class OrderBook { std::string OrderBookType; std::map<double, vector<float*>> OrderBookData; std::unordered_map<int, float*> OrderPool; public: OrderBook(string); } I have 2 questions regarding the class initializa...
To 1. No, it's not valid. The types std::map<float, vector<float*>, std::greater<float>> and std::map<float, vector<float*>, std::less<float>> are different. You can't change the types at runtime. IMHO the best approach is to create an own comparator that expects an argument and is passed to the constructor of the ma...
62,747,734
62,747,766
Storing hexadecimal representation of int at std::vector of unsigned char
In this code: vector<unsigned char> result; int n; unsigned char c; c = (n >> 24) & 0xFF; result.push_back(c); c = (n >> 16) & 0xFF; result.push_back(c); c = (n >> 8) & 0xFF; result.push_back(c); c = n & 0xFF; result.push_back(c); I want, instead of add one single byte to the vector (c), add eac...
n is uninitialized so first take care of that. Depending on what your ultimately goal is the best solution is not to store the hex digits, but to keep the current binary representation and just print in hex. To do that you need std::hex and an integer cast: std::cout << std::hex << std::setw(2) << std::setfill('0'); st...
62,747,740
62,748,068
C++ Code that runs immediately when the program is turned on
struct First{ First(){ printf("first"); } }First; int main() { print("second"); return 0; } I know I can control the code that is executed first through the structure. So I want to use the following code to make it simple through macro. #define FIRST_INVOKE(NAME,FUNCTION) \ struct NAME \ { \ ...
You can automatically generate names based on the line number and use anonymous namespace to avoid multiple definitions across files. E.g, using the following macro: #define CONCAT_(A,B) A##B #define CONCAT(A,B) CONCAT_(A,B) #define NONAME() CONCAT(noname_, __LINE__) #define FIRST_INVOKE(FUNCTION) \ namespace { ...
62,747,934
62,748,191
How would I split up user input into a char and an integer?
I am working on a project where I have to parse data from user input. #include <iostream> // for cin and cout #include <iomanip> // for setw() #include <cctype> // for toupper() using namespace std; int main(){ string playerInput; cin >> playerInput; //Player would input strings like C13,C 6, I1, Z 16, e...
This is the simplest and the shortest way to achieve that (it also ignores spaces and tabs): int main() { char ch; int n; cin >> ch >> n; cout << "ch = " << ch << ", n = " << n << endl; } I think that other answers are a bit overcomplicated.
62,747,996
62,748,185
Can't initialize an enum with a value from its underlying type
enum class Color { red, blue, green }; Color x = Color{5}; The second statement gives me error (main.cpp:20:23: error: cannot convert ‘int’ to ‘Color’ in initialization). I was going through the c++ book it says it's OK to initialize the way in the second statement. I'm confused whether can we use int in initializing...
Initialization of scope enumerations with an integer without cast is a C++17 feature, see cppreference. You have to enable C++17 in your compile step.
62,748,135
62,748,224
Characters and Access level of inherated constructor
From a book I am referring, I found something like: Unlike using declarations for ordinary members, a constructor using declaration does not change the access level of the inherited constructor(s). For example, regardless of where the using declaration appears, a private constructor in the base is a private constructo...
Given the following code, class B { protected: B(int) {} }; class D : public B { public: using B::B; }; then D d(0); // error: calling a protected constructor of class 'B' Even the accessibility of using-declaration using B::B is public, B::B(int) is still protected and not accessible. It's the same if B::B(...
62,748,438
62,759,367
Why does boost::interprocess::managed_shared_memory throw a boost::interprocess_exception upon construction?
In the code below, I'm trying to initialize a managed_shared_memory object. When the constructor is invoked I see the below error message - terminate called after throwing an instance of 'boost::interprocess::interprocess_exception' what(): boost::interprocess_exception::library_error Aborted why is this exception bei...
It aborts because the size is insufficient for the segment manager control blocks. sizeof(test_obj) is just 56 bytes (on my system). If you give the segment 10 KiB, it reports 224 bytes effectively used: Live On Coliru #include <boost/interprocess/managed_mapped_file.hpp> #include <boost/interprocess/managed_shared_mem...
62,748,538
62,748,579
How to use function in other file
I want main.cpp to use run1 function in run.cpp (In windows) main.cpp: int main(){ run1(); } run.cpp: #include<windows.h> void run1(void){ int c = 0; while(1){ c++; Sleep(1000); } } If I use g++ main.cpp run.cpp,error occur error info: main.cpp: In function 'int main()': main.cpp:3:5...
try a function declaration. these are usually situated in header files ( .hpp ) in your case, having a line that says void run1(void) prior to main in the main.cpp will let main.cpp know that you plan on providing such a function when linking together files later. it would be best to put that line into a run1.hpp and t...
62,748,632
62,748,754
Store BASE-DERIVED class in same container
I have the conceptual (not real) class hierarchy as : struct Pet{}; struct Cat : Pet{}; struct Dog : Pet{}; and the object is as : Pet p("unknown"); Cat c("Kitty"); Dog D("Tommy"); Now how can I store object p,c,d in a single container like std::vector. But I can't figure out a way. When i have std::vector<Pet> other...
Usually the only reason you'd put them in the same container is to use them as the base type, making use of polymorphism to simply not care what the specific type is. This requires using virtual methods. For example: struct Pet { virtual ~Pet(); virtual void speak(std::ostream &) const = 0; }; Pet::~Pet() {}...
62,748,686
62,748,968
I am new to programming
https://www.urionlinejudge.com.br/judge/en/problems/view/1047 I cant find error anyone can help me ?! #include<iostream> using namespace std; int main(){ int a,b,c,d,h,m; cin>>a>>b>>c>>d; h = c-a; m = d-b; if (h<0) { h=24+(c-a); } if(m<0) { m=60+(d-b); h--...
Convert all to minutes before subtracting the end time for the start time. If the end time is smaller than the start time, it means it started one day and ended another. This case is handled in the if statement. #include<iostream> using namespace std; int main(){ int a,b,c,d; cin>>a>>b>>c>>d; int start_ti...
62,749,504
62,749,589
Failure to open fstream C++ file even though it's in same location as .cpp
I'm currently doing some schoolwork and I can't get this simple piece of code (I've extracted it) to work. I just need it to open the file so I can read and write to it. The file (Sedes.txt) is in the same location as both the .cpp and the .exe, in the current working directory. Even adding the path with C:\ or C:\ or ...
You are opening the file twice, once with the constructor and once with open fstream aSedes("Sedes.txt"); // opened here int main(){ string txtWrite = ""; string txtRead = ""; aSedes.open("Sedes.txt", ios_base::in | ios_base::out); // and here again if(aSedes.fail()){ Try this instead int main(){ stri...
62,749,636
62,749,815
How to create the map Of the vector of structure in c++
I have a map std::map<int, std::vector<Data>>myMap and my structure is defined as follows. struct Data { int x; int z; int y; }; in myMap key is int and value is vector of structure and I dont want create the temporary vector or structure while inserting to the map. I...
You don't need to explicitly initilize values in a map. When you access a key via operator[] that does not exist in the map it will be added with a default initialized value (an empty std::vector in your case). So you can safely do something like myMap[0].push_back(myInstanceOfData) even if the key 0 does not exist. T...
62,750,151
62,750,251
How to intitlialize an array partially to some default value?
I have an array (say for ex., unsigned int arr[1000]). I want to intilialize the elements of an array like this .. arr = {4, 10, 34, 45, 6, 67, UINT_MAX, UINT_MAX .. 994 times} That is until I assign some value, I want default value in the array to be UINT_MAX. Is there any way to do this ? Of course for loop is alway...
Please use a 2 stage approach. First, use an intializer list and then fill the rest with std::fill #include <limits> #include <algorithm> constexpr size_t ArraySize = 1000U; int main() { int arr[ArraySize] = { 4,10,34,45,6,67 }; std::fill(arr + 6U, arr + ArraySize, std::numeric_limits<int>::max()); ...
62,750,953
62,751,168
Template member function specialization in a template class
I have a template class and a member function print() to print the data. template<typename T> class A { public: T data; void print(void) { std::cout << data << std::endl; } // other functions ... }; Then, I want to either print scalar data or vector data, so I give a specialized definition and ...
Why does this member function specialization get error? When you instantiate the template class A for example A<std::vector<int>>, the template parameter T is equal to std::vector<int>, not std::vector<T>, and this a specialization case of the function. Unfortunately this can not be done with member functions as ment...
62,751,134
62,751,181
Class constructor acts strange
In this way #include <sstream> void f(void) { std::stringstream ss; ss << "hello"; } Everything went fine. But in this way, with an extra brackets #include <sstream> void f(void) { std::stringstream ss(); ss << "hello"; } I got a compiler error: [Error] invalid operands of types 'std::stringstream()...
This is an old problem in C++. stringstream ss(); could be interpreted in two ways. As a declaration of an object ss of type stringstream using the default constructor, or of a function ss returning stringstream and taking no parameters. The compiler chooses the function declaration, which here (and, in my experience,...
62,751,182
62,751,473
Where is the downside if the mutex and the data items are close together in memory?
In 《c++ concurrency in action》page 265, The data in the same cache-line with mutex-locks will be propagated because the mutex-locks are implemented as a r-m-w atomic operation. So the downside of this situation is the cost of ‘call to the operating system kernel’?
This is pretty low level computer architecture question so if you don't get something just ask questions. Knowing that let's get to the point. Firstly, data in processor L1 caches is organized in so called cache lines. These are usually about 64 bytes long. Note that a single cache line is something indivisible for the...
62,751,231
62,751,327
No match for operator+ in C++ while using accumulate
I am trying to calculate the average of the entries, but for some reason I am getting an unexpected error: error: no match for ‘operator+’ (operand types are ‘double’ and ‘const OrderBookEntry’) __init = __init + *__first;" ~~~~~~~^~~~~~~~~~ I am new to C++ and tried to solve this for a while, but not...
The problem is that you are asking the compiler to add OrderBookEntry objects but the compiler doesn't know how to do that. You have to tell the compiler what you mean by adding OrderBookEntry objects. One way to do that is to overload operator+ double operator+(double total, const OrderBookEntry& x) { // your code...
62,751,283
62,751,321
<Windows>Why does std::thread::native_handle return a value of type 'long long unsigned int' instead of void* (a.k.a. HANDLE)?
I need to suspend a thread on windows via Windows SDK on msys. I tried something like std::thread thread(somefunction, someparameters); HANDLE handle=thread.native_handle(); SuspendThread(handle); But gcc told me the return value of native_handle() is 'long long unsigned int' but not void*. So I tried HANDLE handle=re...
The returned "handle" is the thread id not the HANDLE as returned by CreateThread. You need to use OpenThread to get a handle from the id.
62,751,463
62,752,045
Inserting heavy objects into std::map
How many times exactly copies the VeryHeavy(args...) in this code? map.emplace(std::pair<VeryHeavyKey, VeryHeavy>(key, VeryHeavy(args...))); Or, maybe, there is better to use std::make_pair? Are there any standartized warranties on copying objects? What's the right way to insert heavy objects into std::map without cop...
What's the right way to insert heavy object into std::map without copying? prior to C++17 map.emplace(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple(args...)); post C++17 map.try_emplace(std::move(key), args...); The C++17 variant improves on the f...
62,751,544
62,751,980
Jupyter notebook error for C++ Kernel[cling]
I have installed cling kernel for using C++ in Jupiter notebook but after implementing the code #include <iostream> using namespace std; int main() { int a; a=9; cout<<a; return 0; } I am getting an error as ---> error: function definition is not allowed here int main() {
In cling you don't write the whole program code. It's like a script language. You just write the lines that should be evaluated. Don't write the main function: #include <iostream> using namespace std; int a; a=9; cout<<a; You can also define functions in cling but then you are not allowed to write other code into the...
62,751,566
62,752,583
How do you code merging different executables into a single window frame? Like browsers do?
OK, so a noob question here: How do you code this functionality that browsers have for example? You open a chrome browser for example and you can open multiple tabs open. Then you can move one tab out of the window and it becomes another window, having its own separate process. Then you can drag that tab into another w...
Windows-specific answer, though I think other OSs work pretty much the same: the HWND handle that you get for a window is global. If you send its numeric value to a different process, that process can use it to do things with the window: get its information, resize it, even draw on it. What it can't do is replace its e...
62,751,773
62,758,051
Is it a defect when the base class is a dependent type
Consider a example in the standard Example template<class T> struct A { typedef int M; struct B { typedef void M; struct C; }; }; template<class T> struct A<T>::B::C : A<T> { M m; // OK, A<T>​::​M }; The comment says M refer to A<T>::M, I doubt with this, because of these rule...
According to C++ Defect Report Support in Clang, currently (2020-07-06) Clang does not implement the resolution of CWG591, where the paragraph with the definition of dependent base class and the Example you cite in the question was added.
62,752,051
62,752,269
How to properly close boost thread
In my code i open a boost thread for io service and want to close the thread once the while loop is over. Currently the appilcation crashes in the debug mode and i get this error message. Microsoft C++ exception boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error...
As per the comment, it's not enough to simply call io_service.stop(). The thread on which the service is running must be joined to allow it to exit gracefully.
62,752,496
62,752,619
How do i choose where i output in a csv file
I know the title is a bit confusing, so i will try my best to explain it here. When outputting to an excel file you can move the output location down by outputting a "\n" or by using std::endl; is there something similar to move up? to make it easier to understand i have some code: std::ofstream outFile; outFile.open( ...
Moving the position in a file is possible, but it won't help you much, because your entries are all of different length. Text files are just a bunch of characters, there is no A1 or B2 in the text file. Instead of working on the text file directly, if feasible, you should load all the contents into a data structure tha...