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
66,876,806
66,876,827
Return last vowel in string
I need to return the last vowel (uppercase or lowercase) in a given string and return '!' if there aren't any vowels in the string. The code I wrote works but only if the string ends with a vowel. If it doesn't end with a vowel it always returns a '!'. How can I fix this? char lastVowel(string s){ char vowel = ' '...
You set vowel to ! every time you find a non-vowel character in your string. Instead, you need to simply do this: char lastVowel(string s){ // Default value is '!' char vowel = '!'; for(int i = 0; i < s.size(); ++i){ if(s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U' || ...
66,876,841
66,877,108
Pattern with pure virtual functions getting advantage of polymorphism
Suppose the following code: struct Piece_t { virtual ~Piece_t() = default; std::string type; }; struct Empty_t : Piece_t { Empty_t() { }; bool run() { return false; }; }; struct Pawn_t : Piece_t { Pawn_t() { type = "Pawn"; } bool move() { return false; } }; struct Boar...
Why is not letting me to compile the code with this modification? You are experiencing object slicing. std::vector<Piece_t> stores only objects of type Piece_t. Imagine a contiguous array of Piece_t classes back-to-back. There is no room to store anything more in between. Since Pawn_t is a Piece_t, it's sliced back d...
66,877,158
66,877,449
basic_streambuf<char> to uint8_t*
We have a file which is present in a data store (S3) which contains data in the form of byte[] (uploaded using Java language). Now when i download the file, the data i get is in the form of std::basic_streambuf (Ideally it should also be having bytes). Now i want to send this data to another API which takes uint8_t* as...
You have to read your data out of the buffer (since the buffer itself can be streaming the data in as it's available). One possible implementation is something like this: vector<uint8_t> bytes; do { bytes.push_back(buf->sgetc()); } while(buf->snextc() != EOF); // your data is in bytes.data() of type uint8_t* Of ...
66,877,211
66,877,373
How to force sorting a QTableWidget prior to displaying
I'm using Qt 5.21.3. I have a QTableWidget that, when initially displayed, shows the rows in the order they were populated. I've set setSortingEnabled(true) and all rows are sorted properly when I click the column headers, but I'd like the table sorted on a specific column, in this case column 0, before showing the ta...
You have to invoke the sort() method of the model: tableWidget->model()->sort(0, Qt::AscendingOrder); or sortItems() method: tableWidget->sortItems(0, Qt::AscendingOrder); after filling the table.
66,877,395
66,877,676
Understanding C++ constexpr Performance
I recently wrote a compile-time ray tracer using constexpr functions with C++17. The full source code can be seen here. The relevant code for this question looks like this: constexpr auto image = []() { StaticImage<image_width, image_height> image; Camera camera{Pointf{0.0f, 0.0f, 500.0f}, ...
Compile-time execution is going to be much less efficient than runtime execution. The compiler has to do more work to execute the same code. The point of compile-time execution is to do computations that you can't do at runtime. And sometimes, to compile-time cache simpler computations. Writing a whole, non-trivial app...
66,877,456
66,879,651
Replacing tokens inside string
What i am trying to do is to replace all the tokens with a similiar syntax [[VULKAN_SDK]] inside a string. I want to take the contents of the brackes(in this case VULKAN_SDK) and replace the entire token with a value i get from getenv by passing the contents of the brackets. Example [[VULKAN_SDK]] gets replaced by C:...
Using the in-built replace() function in C++17, you can accomplish the above stated task with minimal code. If the given string test = "abc [[vul [[hjh]] [[nj [[ hg[[gfgh]] ]]m ]]xyz" or "abc [[vul[[kan]] xyz" or of similar type then you can see this as a variation of the balanced parenthesis problem which is solved us...
66,877,727
66,879,202
hashtable from input to output
I would like to implement hashtable and so far I have reading from file and something not working when I want to write first string to Tabh. Code compile without errors but nothing appears in console. Can someone help me with that? I think that I wrong implement: if (Tabp[ite].substr(0) == "a"){...} #include <iostream>...
The one parameter version of substr returns a substring starting at the given index thru the end of the string. So your call to Tabp[ite].substr(0) will return a copy of Tabp[ite]. To get a substring of one character, you need to specify that using two parameter version, where the second parameter is the length of subs...
66,877,830
66,878,105
assigning x to point to where y is pointing to does that cause any memory leaks?
i am assigning x to point to where y is pointing to does that cause any memory leaks? If yes what is the correct way to do it? int *x, *y x = new int; y = new int; *x = 3; *y = 4; x = y; delete x;
When in doubt, draw pictures! We start here: int *x, *y; +---------+ | x |-----> ??? +---------+ +---------+ | y |-----> ??? +---------+ We have two uninitialized pointers, and that means that they're pointing basically "wherever." Next, we say x = new int; y = new int; +---------+ +----------+ | ...
66,878,093
66,878,141
Iterate over vector using loop c++
Let's say I have a vector of long long elements: std::vector<long long>V {1, 2, 3}; I have seen that in order to iterate over the vector you can do this: for (auto i = v.begin() ; i != v.end() ; i++) cout<<*i; i++ means i grows by 1, but shouldn't the address go up 8 bytes to print the next element? So "growing" p...
When you increment a pointer it goes up by the "size of" the pointer's type. Remember, for a given pointer i, i[0] is the first element and is equivalent to *(i + 1). Iterators tend to work in a very similar fashion so their operation is familiar, they feel like pointers due to how operator* and operator-> are implemen...
66,878,360
66,888,227
C++ capture value of all pointer wrappers in variadic template arguments
std::deque<std::function<std::string()>> log_queue; void store_log(T&& t, U&&... u) const { log_queue.push_back( [t, u...]() { return format_log(t, u...)); }); if (log_queue.size() > 1000) { log_queue.pop_front(); } } I use the above function to store the lates...
You might apply transformation before the capture: void store_log(T&& t, Us&&... us) const { log_queue.push_back( [tup = std::make_tuple(value(t), value(us)...)]() { return std::apply([](const auto&... args){ format_log(args...), tup)); }); if (log_queue.size() > 1000) { ...
66,878,373
66,878,406
Invalid operands to binary expression error upon printing vector values
My program is taking in file values separated by whitespaces, but I get this weird error when I try to print out the vector(in-loop vector works, but the one I saved the data to to be parsed afterwards, I get invalid operands error). This is what the error looks like: joj.cpp:36:13: error: invalid operands to binary ex...
data[i] is a std::vector<unsigned int> - there is no operator<< overload for that. You need to loop over the inner vector, too. Example: for(auto& inner_vector : data) { for(auto value : inner_vector) { std::cout << value << ' '; } std::cout << '\n'; // if you want a newline after each row } Or usi...
66,878,451
66,885,203
OSDynamicCast not compiling in basic driver kit example
I've got a very simple driver kit driver. It's almost boiler plate. I'm getting a build failure when trying to use OSDynamicCast, as per the below kern_return_t IMPL(MyHIDDriver, NewUserClient) { IOService* client; auto ret = Create(this, "MyTest", &client); *userClient = OSDynamicCast(IOUserClient...
Is the IOUserClient header #included somewhere in this compilation unit? It sounds like you're simply missing #include <DriverKit/IOUserClient.h> Entirely unrelated to the issue you're experiencing, but you may want to initialise the client variable to a nullptr to avoid issues with undefined behaviour in case Create ...
66,879,286
66,879,415
C++ Why does returning rvalue reference change caller's behavior when function signature does not return rvalue reference?
I've come across some behavior I cannot wrap my head around regarding rvalue return. Let's say we have the following structs: struct Bar { int a; Bar() : a(1) { std::cout << "Default Constructed" << std::endl; } Bar(const Bar& Other) : a(Other.a) { std::cout << "Copy Construc...
What's happening is you are seeing elision there. You are move-constructing on return std::move(x) with a simple type of Bar; then the compiler is eliding the copy. You can see the non-optimized assembly of GetBarRValue here. The call to the move constructor is actually happening in the GetBarRValue function, not upon ...
66,879,321
66,887,835
How do I complete this example?
Hello I'm trying an example and I don't know how to follow. I'm trying to set a map (or some other structure) that saves all the same class/type together. For that, my approach was to take all parameters on the constructor of my class (ResourceManager_t) and everytime that I'm adding a new resource to our map, check if...
It seems to me that you're looking for a std::tuple<std::vector<types_t>...>. The following is a full compiling C++17 example, with some simplifications #include <tuple> #include <vector> #include <cstdint> #include <utility> #include <iostream> #include <type_traits> template <typename T0, typename ... Ts> struct is_...
66,879,736
66,880,469
If I create two std::thread, how can I identify which thread ends first
I want to create two std::thread processes. Then I want to figure out which thread ended first and end the other thread if it is still running (probably by calling its destructor?). I would like to only use the std libraries. I'm guessing I need to do something with std::atomic and/or std::future, or implement a cal...
You can't just end a thread from outside the thread itself. You have to signal the thread in some way that it needs to stop. You can do this with a std::atomic_boolfor example. Something like this: // thread-safe output #define con_sync_out(m) do{std::ostringstream o; o<<m<<'\n'; std::cout<<o.str();}while(0) #define co...
66,880,020
66,880,301
std::thread member object crashes on destruction in terminate
I have a program where I want to run one of my classes in a separate thread with a higher priority than the rest of the program and I want it to update the GUI as it processes so I'm using std::thread. GUI.h #include <thread> class GUI { private: Worker worker; std::thread workerThread; public: GUI (); ~...
std::thread will std::terminate() on destruction if it manages a thread. Call .join() or .detach() for orderly ending, depending on what you need. Alternatively upgrade to C++20, which introduced std::jthread which joins instead of terminating.
66,880,263
66,880,343
Does std::move helps with objects on stack?
I just saw a college doing this optimization today: i.e., change this: std::string somestring = "somestring"; std::map<std::string, int> myglobalmap; std::string myfunction( const std::string& mystring, int myint ) { myglobalmap.insert( std::pair<std::string, int>( mystring, myint ) ); } myfunction(somestring, 1...
and I found out it does not move anything, it just makes my expression to return a reference. This is correct. Crucially, the result of the function is an xvalue. Then, if this is true, passing the value by copy would not be slower than passing it by reference and calling std::move or does calling std::move In case...
66,880,666
66,880,820
How to give access to public members with Pimpl?
pimpl.h #include <memory> class MyClassImpl; class MyClass { void Foo(); struct MyStruct { int a; int b; } variable_struct; private: std::unique_ptr<MyClassImpl> m_pImpl; }; pimpl.cpp class MyClassImpl { public: void DoStuff() { /*...*/ } struct MyStructImpl { int a; ...
How to give access to public members with Pimpl? You don't. The point of PIMPL is to hide all members of the Private IMPLementation, and having public access to them is entirely contrary to that point. If you want pubic access, then don't put the member in a PIMPL.
66,880,778
67,064,413
OpenCV G-API findContours: pass result to kernel?
OpenCV G-API defines gapi::findCountours result as GArray<GArray<Point>>. Fair enough. So, how do I pass this to a kernel? G-API only unpacks the outer most GArray translating it to std::vector. How do I make it unpack the GArray in the next level of the template, so I can get the desired std::vector<std::vector<Point>...
You don't have to unpack GArray<GArray<Point>> manually. If you want to pass that to a custom kernel, it has to take GArray<GArray<Point>> as input. If unpacking of complex G-types doesn't happen by itself, it can be a bug. Recently you could have faced such one if you had tried to write a custom kernel with GArray<GAr...
66,880,819
66,880,890
How do I allocate a 3D array in C++ on the free store?
I am currently learning how to utilize raw pointers in C++. I understand how to dynamically allocate a 2D array, however, as an exercise for myself, I attempted to apply my understanding of multiple levels of indirection to allocate a 3D array. My attempt is presented below: int main() { double*** matrix { new dou...
matrix[i] = new double*[i + 1] {}; for(size_t j {}; j < 10; ++j) { This is your error right here, you allocate an array of 'i + 1' element and then loop for 10, you either need to have i + 1 in both places or 10 otherwise this is undefined behavior. The same applies for deletion (the loop checks for 10 but you only al...
66,880,902
66,881,263
Do C++ modules make unnamed namespaces redundant?
C++20 introduced modules. Any symbol that is not exported in a module has module-internal linkage. While unnamed namespaces provide a mechanism to make definitions inside an unnamed namespace have file-internal linkage. Does this mean unnamed namespaces will become useless in future when modules become common practice ...
No: since (many) compilers see just one translation unit at a time, it’s still useful for optimization to indicate that an entity cannot be used in any other. It also avoids the possibility of accidental collisions between module units (even if those should be less likely than with broader codebases).
66,880,972
66,882,170
Undefined reference error on linking - Makefile and includes configured
I have two sources file, main.cpp & functions.cpp, and a header filed main.h, and finally a Makefile: main.cpp #include "main.h" int main() { Application game; game.update(); game.draw(); } functions.cpp #include "main.h" Application::Application() { window = SDL_CreateWindow("SDL GAME", ...
Suppose you have a self-contained source file, foo.cpp. You could build the executable foo in one step: g++ foo.cpp -o foo Or you could build the object file, then build the executable from that: g++ -c foo.cpp -o foo.o g++ foo.o -o foo Now suppose you have two source files, main.cpp and functions.cpp. The code in ma...
66,881,554
66,881,695
C++ string conversion inside vs outside printf
I'm extracting text from a PDF using Poppler and used the following code to print the text: for (std::vector<poppler::text_box>::iterator it = currpg.begin(); it != currpg.end(); ++it) { const char *txt = it->text().to_latin1().c_str(); printf("%s\n", txt); } It worked fine for all but one string: "Exemptions/...
The pointer txt outlived a temporary variable. it->text().to_latin1() // returns a temporary const char *txt = it->text().to_latin1().c_str(); // stores the pointer to an internal buffer of the temporary printf("%s\n", txt); // the temporary destroyed, the dangling pointer is used The first example involves the undefi...
66,882,018
66,882,223
Types of char in C++ (confused by C++ primer explanation)
The book states the following: Unlike the other integer types, there are three distinct basic character types: char, signed char, and unsigned char. In particular, char is not the same type as signed char. Although there are three character types, there are only two representations: signed and unsigned. The (plain) ch...
If an integer type is signed it means that it holds negative and positive values and the value 0. If an integer type is unsigned it means that it holds positive values and the value 0. It cannot hold negative values. Some types have "more names". E.g. long, long int and signed long int are all names for the same type. ...
66,882,175
66,883,399
E0349:no operator "=" matches these operands when using JSON using nlohmann-json
I'm using nlohmann-json on my C++ project on Visual Studio and I caught an error of E0349:no operator "=" matches these operands at the code below: #include <nlohmann/json.hpp> using json = nlohmann::json; void myFunc(unsigned int** arr) { json j; j["myArr"] = arr;//E0349:no operator "=" matches these operan...
nlohmann json only supports creating arrays from c++ standard library containers. It wouldn't be possible to create an array from a pointer as it has no information about the size of the array. If you have c++20 then you can use std::span to convert your pointer (and a size) into a container: #include <nlohmann/json.hp...
66,882,354
66,882,432
Getting Unchecked return value from library?
Calling remove(file.txt) without checking return value. This library function may fail and return an error code I am getting above warning in below code- bool chkfile() { std::remove(file.txt); return true; } How should I remove this warning?
You can refer to this link to see the issue. You have to check if there is no issue during remove operation. Your code should be something like this, bool chkfile() { if (std::remove("file.txt") != 0) { // error handling } else { // success return true; } }
66,882,438
66,882,473
Create a 10x10 matrix filled with random integers from 1 - 99 using functions (C++)
I am writing some code that has 2 functions. The first function I believe has no problems. The first one is to create the 10x10 matrix filled with random numbers, the second function is to print the matrix. The problem that I am having is that even with the declaration of the row and column sizes, the matrix prints out...
The problem is that you're not ever printing an end of line character. Setw(n) will tell cout that every chunk of text that you write has to be printed using exactly n characters, but it doesn't say that that chunk of text has to end in a newline. To make sure that there's a new line after every row of your matrix, you...
66,882,455
66,882,487
My code to find no. of a substrings in a string. Why is j<=str.length() - 3 causing runtime error?
#include <iostream> #include <string> using namespace std; int main() { int T; int count = 0; cin>>T; for(int i = 0; i<T; i++) { string str; cin>>str; co...
String lengths use unsigned math; 2-3 becomes 2^64-1. Try j<-3 || j+3<=str.length()
66,882,633
66,883,802
Is it safe to pass lambda to function that is going out of scope (lambda executes after the method returns)?
I am learning C++ so maybe my question is dumb. I am creating a function that takes a lambda as a parameter. I just want to know if its safe to call it when the lambda function goes out of scope. With code is easier to explain what I mean: struct SomeStruct { // store pointer to callback function void (*callba...
A lambda expression is like a class. It is a blueprint for instantiating objects. Classes exist only in source code. A program actually works with objects created from the blueprint defined by a class. Lambda expressions are a source code blueprint for creating closures. Each lambda expression is transformed into a cla...
66,882,764
66,882,821
Why does this program in c++, visual studio code shows error
//function overloading #include <iostream> using namespace std; //declaration of function protype int area(int); int area(int, int); float area(float); int main() { cout << "calling the area() function for computiong the area of a square (side=5) - " << area(5) << "\n"; cout << "calling the area() function fo...
Type area(5.5f) to force the value to be a float. The compiler does not know if it should cast your double value to an int or a float. Therefore, it is ambiguous.
66,882,803
66,883,873
C++ regular expression sscanf
I wanto to use sscanf to extrat the 2 first integer (5 and 10) in a string rssi = 5 ber = 10 like this : #include <stdio.h> #include <iostream> #include <string> using namespace std; int main() { std::string str = "\r\n+CSQ: 5,10\r\n\r\nOK\r\n7556\r\n"; unsigned char lBufRX[100]; char *rssi, *ber; if((ssca...
You have several errors. You're using char* although you want to read two ints. But then you don't allocate memory for them. Also, you're expecting two successful parses but check with != 2. Here is some code that works: int main() { std::string str = "\r\n+CSQ: 5,10\r\n\r\nOK\r\n7556\r\n"; int rssi, ber; if((...
66,883,341
66,883,434
I defined a list of arrays in c++ for representing a graph. But i can't seem to access the elements of the arrays
basically this is what i did, a list of int pointers to be used as a list of arrays: #include <list> list<int> *l; l = new list<int>[V + 1]; I can push_back(integer) into l[x] to create the array at "x" position on the list and i get no error. But when i use l[x][some_index] to access an element of the array at positi...
std::list in C++ is implemented as a doubly-linked list. It does not support random access to its elements, therefore it does not have the [] operator available. You can use front() and back() to access the first and last elements, and you can use iterators to iterate and access the content of the list. In your example...
66,883,653
66,884,145
Merge 2 sorted arrays into vector c++
Hi I'm trying to merge 2 sorted array into a vector. The following is my code. I believe that I am using the correct algorithm however, when I print the vector out its only prints 1,2. Can someone please take a look at my code? #include <iostream> #include <vector> using namespace std; vector<int> merge(int arr1[],int...
A function parameter that has an array type is adjusted by the compiler to pointer to the array element type. That is this function declaration vector<int> merge(int arr1[],int arr2[]); is adjusted by the compiler to the declaration vector<int> merge(int *arr1, int *arr2); On the other hand, arrays used as function a...
66,883,958
66,884,007
Find the sum of an entire matrix using functions (C++)
I am writing some code that writes a matrix with a 10x10 size and prints it using functions. What I need is a function that takes the sum of the entire matrix array. What I have done is that I tried to sum up each row and column separately and add the total together. The problem with mine is that I believe that it only...
What you have done is sum of last row + last column. This should be enough: void sum(int matrix[][COLUMN_SIZE], int ROW_SIZE, int COLUMN_SIZE){ int sum = 0; for(int i = 0; i < ROW_SIZE; i++){ for(int j = 0; j < COLUMN_SIZE; j++){ sum += matrix[i][j]; } } cout<<"The sum ...
66,884,357
66,885,070
Hexadecimal to decimal conversion problem.Also, how to convert a char number to an actual int number
Please help me to identify the error in this program, as for me it's looking correct,I have checked it,but it is giving wrong answers. In this program I have checked explicitly for A,B,C,D,E,F,and according to them their respective values. [Edited]:Also,this question relates to how a character number is converted to ac...
Your problem is in the elsecase in which you convert num[i] from char to its ascii equivalent. Thus, for instance, if you try to convert A0, the 0is converted into 48 but not 0. To correct, you should instead convert your num[i] into its equivalent integer (not in asci). To do so, replace : else { last_dig...
66,884,643
66,919,653
Qt5 CMake can't find C++ STD library if a definition is added in CMakeLists.txt
Here is the problem I am struggling with. I am using CMake to build my Qt5 GUI project. I am using a custom module QML-material project from GitHub. The problem is that as it is said in the project documentation - in order to setup the module for your project, you should add a definition: add_definitions("-DQPM_INIT\(...
Most of the compilers does not tolerate function like definitions. Adding such a macro with add_definition is a workaround as it adds the macro to CXX_FLAGS, not to CXX_DEFINES, but apparently it doesn't work properly too.
66,884,904
66,886,280
Add QCombobox inside QTreeview specific cell
I was trying to insert a QCombobox only in some specific cells of my QTreeview. As I read, I think that I need to create my delegate (that I've created). But I don't understand how to insert this in my treeview. I want to realize this: This is my code: #include <QTreeView> #include <QStandardItemModel> #include <QStan...
QTreeWidget makes widget items convenient. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { treeWidget = new QTreeWidget(this); setCentralWidget(treeWidget); treeWidget->setColumnCount(2); auto root = new QTreeWidgetItem({"Root"}); root->setCheckState(0, Qt::Checked); treeWidget...
66,885,694
66,886,022
QML: Can I rounded the start and end point of an arc painted with canvas
How can I rounded the end and the start line of this arc painted with canvas in QML? Canvas { id: canvas property real degree: 180 anchors.fill: parent onPaint: { var ctx = getContext("2d") var x = 90 var y = 90 var radius = 85 var startAngle = (Math.PI / 180)...
Canvas has lineCap property: ctx.lineCap = "round"; That should do it. Note that it's pure js and not particularly related to QML so you'll probably have better luck searching for stuff like that without c++ and qml keywords.
66,885,749
67,473,124
Problems with C++ red-black tree implementation
I'm trying to make a C++ implementation of RB tree. But when I try to delete an element - I find out that some leaves of tree has different value of black height. Before calling remove functions everything works fine - insertion and rebalancing after tree insertion works correctly. But after a single call of remove fun...
I mostly agree with your algorithm. But I disagree with attempting to fix a node when only 1-child. Once you found the node to delete - count its children There are 3 situations where a deleting node is easy, cheap to do. Those are 0-children and the node is red => just delete it 0-children and the node is the root no...
66,885,976
66,889,630
Unable to pass TCHAR as parameter in C/C++
Here is Minimal example :- #include <stdio.h> #include <Windows.h> using namespace std; void myFunc(TCHAR Path) { printf("pathLen : %lu\n", sizeof(Path)); printf("character size : %lu\n", sizeof(*Path)); printf("pathLenInBytes : %lu\n", sizeof(Path) * sizeof(*Path)); } int main() { TCHAR selfPath[MAX...
I make an attempt to answer In your first version, your prototype must be myFunc(TCHAR *Path) or myFunc(TCHAR Path[]) because a path is an array of TCHAR, thus a TCHAR* (a starting documentation can be found here or here) What you obtained from the first code that compiles is only what you have asked. Let us see: p...
66,886,390
66,886,888
can cppclean be ran in windows?
So this is probably a very newbie question (which I am) but looking for tools for C++ code I found cppclean, so I follow the instructions on the repository cppclean but when running cppclean from a cmd terminal I get cppclean is not recognized as an internal or external command I guess I am missing some steps apart fro...
You have to add the Python scripts path, e.g. C:\Users\USER\AppData\Local\Programs\Python\Python37-32\Scripts, to your system environment Path variable. (Replace USER with your actual user name and Python37-32 with your actual Python version). It's described here
66,886,650
66,886,788
Avoid control sequences(like ^[[C) from C or C++ standard inputstream
Code: #include <iostream> #include <string> using namespace std; int main(){ string s; cout << "Enter a string : " << endl; cin >> s; cout << "The Entered String is : " << s << endl; cout << "The Length of Entered String is : " << s.length() << endl; return 0; } Output: ┌─[jaysmito@parrot]─[~/...
Cursor movement, function keys and other special keys are handled differently in different terminals. But in most cases some escape sequence is generated. Program prompt in most languages is a simple read from stdin, it will read escape sequences as-is. So e.g. ←[D, ←[C correspond to left/right cursor movement. If you ...
66,886,720
66,886,831
C++ storing std::future form std::async in vector and wating for all
I want to do several tasks in parallel with std::async and then wait until all the futures have completed. void update() { // some code here } int main() { std::vector<std::future<void>> handles(5); for (int i = 0; i < 5; ++i) { auto handle = std::async(std::launch::async, &update); handles.emplace_bac...
You initialized your handles array with 5 default-constructed elements, then you emplaced 5 more into it. It now has 10 elements, the first 5 of which are default-constructed and therefore not associated with anything to wait for. Don't create the vector with 5 elements. I think you were trying to reserve space for 5 e...
66,887,566
66,888,562
can't figure out where the heap overwriting is
#include<iostream> using namespace std; class Text{ public: ~Text(){ delete data; } char* data{}; int mSize{}; void fill(char* stringInput) { mSize = strlen(stringInput); data = new char [mSize]; for (int i = 0; i < mSize; i++){ data[i] = stringInput[i]; } ...
I have fixed all your memory errors, with the help of address sanitizers The main change here is: Add copy constructors and copy assignment operators Manually delete the last element in the function delString Though that the code now works, it's not a true modern c++ style code. I highly recommend that your using std...
66,887,904
66,888,444
Qt Chart Series remove not shown data crashes
I'm trying to make a live plotting graph class in qt and the scrolling works. But when watching my program in Task Manager I recognized that the CPU and RAM usage increases by time (and data). So I thought it would be a good style to use the remove function to delete data which is not shown anyway. Here's my code: void...
You are confusing the index of the data points in the vector m_series and their x value. When the data point with x = old_x_min goes out of the window you want to display, then that data point is at index 0 not at index old_x_min. Replace m_series->remove(m_axisX->min()); with m_series->remove(0); to remove the oldes...
66,888,732
66,888,905
Allow scalar and vector types in a template
I am working on a class template for a signal processing library that is supposed to hold scalar samples or vectors of scalar samples (which is common in, e.g., frame-wise signal processing). The class is essentially a facade for the std::vector with some added convenience methods and members. For scalar types, everyth...
You might use overloads instead of SFINAE: template <typename T> std::ostream& print(std::ostream& os, const T& obj) { return os << obj; } template <typename T> std::ostream& print(std::ostream& os, const std::vector<T>& v) { os << "{"; const char* sep = ""; for (const auto& e : v) { os << sep;...
66,889,262
66,889,524
Finding greatest power devisor using recursion?
The question asks me to find the greatest power devisor of (number, d) I found that the function will be like that: number % d^x ==0 I've done so far using for loop: int gratestDevisor(int num, int d){ int p = 0; for(int i=0; i<=num; i++){ //num % d^i ==0 if( (num % (int)pow(d,i))==0 ) ...
Here is a simple method with recursion. If ddivides num, you simply have to add 1 to the count, and divide num by d. #include <stdio.h> int greatestDevisor(int num, int d){ if (num%d) return 0; return 1 + greatestDevisor (num/d, d); } int main() { int num = 48; int d = 2; int ans = greatestDevisor...
66,889,423
66,891,033
Parallel programming for tasks in main function - c++
is it possible to define two tasks and let them work parallel in C++? I found something about parallel funtcions, but not about parallel tasks in main function like that: int main() // task 1 int a = 0; for(int i = 0; i < 150; i++){ a++; std::cout << a << std::endl; // do more stuff } // t...
Yes, you can run the two in parallel, using std::async and lambdas. Here is an example: int main() { auto f1 = std::async(std::launch::async, [](){ // task 1 int a = 0; for(int i = 0; i < 10; i++){ a++; std::cout << a << std::endl; // do more stuff } }); auto f2 = std::async(s...
66,889,853
66,889,891
Convert char[] variable to uintptr_t variable C++
I have a variable of type char [] with an address. Example: char addr[11] = "0x01234567";. How do I convert this variable to type uintptr_t? I want it to be equivalent to uintptr_t add = 0x01234567;.
"0x01234567" is a textual representation of an integer. std::uintptr_t is an integer type. You can use any standard formatted input functions to do the conversion. There are several options, but I recommend starting with a string stream.
66,889,878
66,890,159
Check if function has an empty body
Is it possible to check (at compile or runtime) if function or class method has an an empty body? E.g void empty_body_function(){} void non_empty_body_function(){int i;} int main() { assert(magic(empty_body_function) == true); assert(magic(non_empty_body_function) == false); } P.S.I define non empty body like...
To the best of my knowledge, there's no way to do that. But C++ metaprogramming is complex and it's hard to say about something that it's impossible. I'll add - in compile time, for any function that is declared but not defined, it's absolutely impossible. The compiler knows nothing about what the function does except ...
66,890,051
66,989,842
CComboBoxEx debug assert failure: afxcmn2.inl Line 334
Please note that I have found that I need to add COMBOBOXEXITEM values much like LVITEM based on this book: Image Lists and ComboBoxEx Controls | Programming Windows with MFC, Second Edition (flylib.com) FYI, I am getting the above error on the SetImageList call: // Add color icons to combobox for (int nCount = 0; nCo...
This is how I ended up adding a color swatch to the combobox dynamically without using *.rc files or *.bmp files. In the parent windows class OnCreate function where a key argument is CBS_OWNERDRAWFIXED which causes the DrawItem function to be called every time the combobox is opened by the user: int ParentToolbarWind...
66,890,063
66,890,107
The standard type_traits library produces unexpected beavior with some type aliases that use decltype
Let me illustrate. Let's take std::is_same_v and std::is_base_of_v for example. Consider the following code: #include <iostream> #include <array> #include <type_traits> using namespace std; struct base {}; struct derived : base { int foo; }; array<derived, 10> my_array; int main() { using c1 = decltype(*begin(m...
Your issue is that you have extra reference: using c1 = decltype(*begin(my_array)); // derived& using c2 = derived; is_same_v<derived, derived&> is false. std::decay_t or std::remove_reference_t might help. And the typeid are identical: Refers to a std::type_info object representing the type type. If type is a refer...
66,890,169
66,890,728
How do you make unique_ptrs with the these initializations?
What are the equivalent versions of making std::unique_ptr using std::make_unique with the following initializations? // Single object // 1: Indeterminate value new int; // 2: Zero initialized new int(); // 3: Initialized with 7 new int(7); // Arrays // 1: Indeterminate values new int[10]; // 2: All zero-initial...
The counter parts are: // Single object // 1: Indeterminate value new int; std::make_unique_for_overwrite<int>(); // since C++20 // 2: Zero initialized new int(); std::make_unique<int>(); // 3: Initialized with 7 new int(7); std::make_unique<int>(7); // Arrays // 1: Indeterminate values new int[10]; std::make_unique...
66,890,356
66,890,565
C++ overload pattern : call resolution with mutable lambda
Considering this well-known C++ pattern : template <class... Ts> struct overload : Ts... { using Ts::operator()...; }; template <class... Ts> overload(Ts...) -> overload<Ts...>; // clang needs this deduction guide, // even in C++20 for some reasons ... I wonde...
With auto functor = overload{ [](int &&){ std::cout << "int\n"; }, [](auto &&) { std::cout << "smthg else\n"; } }; functor(42); // prints `int` both closures have const qualified operator()'s so int&& is a better match as it is not a template. With auto functor = overload{ [](int &&...
66,890,871
66,891,792
Cannot get boost::process to find gstreamer plugin
I'm trying to load a gstreamer plugin using boost::process to call gst-launch. When I load the plugin via the command line everything works well: gst-launch-1.0 videotestsrc ! privacyprotector ! fakesink If I use the full path to the executable, it also works well: bp::child c("/opt/intel/openvino/data_processing/gstr...
I think the arguments need to be a vector: https://www.boost.org/doc/libs/1_75_0/doc/html/boost_process/design.html#boost_process.design.arg_cmd_style https://www.boost.org/doc/libs/1_66_0/doc/html/boost/process/args.html So, try Live On Wandbox #include <boost/process.hpp> #include <iostream> namespace bp = boost::p...
66,891,087
66,891,167
Dealing with subvectors in costant time
I'm implementing an algorithm and I need to be really efficient. My algorithm works on a set of equal and constant size vectors of bools, and I would like to keep them consecutive in memory to avoid cache misses. Since it's used a lot of time, my solution at the moment is to concatenate all the vectors in the set in a ...
I only need to read the content and not modify it during the algorithm execution Well first off you can't use vector<bool> like this because it acts as a bit field so you can't "extract" sequences of it. Use vector<char> instead. That said, you can easily get a pointer to your data, like: char *array = concatenation....
66,891,236
66,891,289
Give specific options for a struct in C++
I was attempting to create a struct in C++ that was a single Ternary digit. It is similiar to a bit but has three different values instead of two. Is there any way of limiting the options to -1, 0 or 1. Any help is appreciated. what I have so far is: struct trit { char digit; // I dont just want a character. I onl...
You can try enumerators. enum Ternary_digit { down = -1,zero = 0, up = 1 };
66,891,368
66,892,838
Template parametric type Allocator in C++
I have the following toy code that works: #include <cstdlib> #include <vector> template <typename T> struct Dummy { using value_type = T; using size_type = size_t; using difference_type = ptrdiff_t; using pointer = value_type*; using const_pointer = const value_type*; us...
I think I found the way to fix the issue even though I'm not sure I fully understood all the details. Thanks to: this and this I managed to write template <typename T, size_t align> struct Dummy { using value_type = T; using size_type = size_t; using difference_type = ptrdiff_t; using po...
66,891,816
66,892,234
Will there be a memory leak in this Linked list
Hi Currently i have been honing my skill in the data structure so that i can become a good Game Developer, i am Learning Linked list and made a Linked list Program with Insertion ,Deletion and Recursive insertion and Reversing a Linked list Can you Guys tell me am i here Clearing the assigned memory Created with the ne...
You're writing C-style code; in C++, you should avoid explicit calls to new. Your example is far too long to rewrite, but here is a very small start: #include <memory> class Node { int data; std::shared_ptr<Node> Next; // ... void Insert(std::shared_ptr<Node>& Head, int x) { auto temp = std::make_shared<N...
66,892,158
66,898,398
"Assertion '__builtin_expect(__n < this->size(), true)' failed" error in Visual Studio Code Python
I know there is already a lot on Assertion Failure. But none was useful for me. Hear me out. This is the code: import numpy as np, pandas as pd from outliertree import OutlierTree ### random data frame with an obvious outlier nrows = 100 np.random.seed(1) df = pd.DataFrame({ "numeric_col1" : np.r_[np.random.normal...
Author of the library here. There was a bug in the code which would only trigger when the setup has defined a macro _GLIBCXX_ASSERTIONS and would otherwise not show up. It should be fixed now in the latest version (1.7.0) - please try again (pip install -U outliertree) and comment in the github issue tracker if the pro...
66,892,508
66,892,662
Why does the program print 0 instead of the average?
Wrote a function that calculates the average length of words in a sentence. Why does the program print 0 instead of the average? Please help me fix my mistake. If you know how to make an implementation in one function, please write. #include <iostream> #include <string> using namespace std; int CountWordsAndLetters(ch...
Here, you are allocating an uninitialized array of char: char* str = new char[size]; You put nothing in it. You then pass it to CountWordsAndLetters: // here -------v CountWordsAndLetters(str, words, letters); You should consider simply sending array instead: CountWordsAndLetters(array, words, letters); Here's...
66,893,292
66,893,673
What does each depointer/dereference syntax make the variable mean?
EDIT: Since there is no difference between int * x, int* x, and int *x, I removed that section to better clarify what I'm confused about. The question: The differences between "pointers" and "references" are explained in the answer to What are the differences between a pointer variable and a reference variable in C++?,...
The rules for this are pretty simple. It does not matter where you see a declaration, if it is in main, some_namespace, inside a class, or in the parameter section of a function, a declaration means the same thing. Knowing that, whenever you see type_name * variable_name you are declaring a pointer. Wherever you se...
66,893,401
66,893,726
Segmentation fault error with 2D arrays C++
I dunno why I have segmentation error when I'm trying to set or get any element from created array!! Here it is in line with A[0][0] = 1; I'm using g++ 9.3.0. What do I do wrong? #include <iostream> #define SIMULATIONS 30 using namespace std; void init_matrixes(int a_rows, int b_cols, int vec_len, double **A, double...
TL;DR version Use std::vector or a matrix class like the one described here. This will eliminate the need for special allocation and deallocation functions thanks to the magic of RAII. What went wrong? A pointer is just another variable, but one that can contain the location of another object. Like any other variable, ...
66,893,543
66,895,191
What is the Time and space complexity of sort() in C++ with custom comparator function?
Consider the following code- bool cmp(pair<string,int> &a, pair<string,int> &b) { return ((a.second > b.second) || (a.second==b.second && a.first<b.first)); } vector<pair<string,int>> v; sort(v.begin(),v.end(),cmp); For this case, what would be my complexity? Will it be O(nlogn) ?
std::sort has time complexity: O(NlogN) custom comparisons. But in your case the comparator function cmp also performs string comparison, (a.second==b.second && a.first<b.first) std::basic_string operator< has time complexity linear in the size of the strings. Hence, worst case complexity is O(K*NlogN) char comp...
66,893,551
66,895,390
Display Output Data for conversion between 2 Classes
I implemented a conversion for feet to Meters as noted below but I am unable to print out the results in my main. Below is the code generating the error in Ftr cnum1(2); Mtr cnum2 = cnum1.toMtr(); std::cout << cnum1.getNum() <<" feet = " << cnum2.getMtrNum() << " meters \n\n"; I’m unable to use the getNum ...
If I understood correctly, there are two points you would like to do: Fix the code so it shows the conversion value Make the print without creating getMtrNum() For the second point, if you want to keep your member private, you will need to create a getter/printer function in any case. Probably a bit more elegant if y...
66,893,586
66,893,977
String type alternative in C
I currently have a function defined in a header that looks like this void foo::GetValue(std::string& str); This function basically assigns a value to str. I need to come up with an alternative to str (basically, nothing that employs the standard library). The implementation of the above function is like this in the .c...
For a given C++ function like this: std::string foo::GetValue(std::string& str) { return bar.someMethod(str); } Then your equivalent C code looks like this: void foo_GetValue(char* str, char* res, size_t size) { std::string str_arg = str; std::string result = bar.someMethod(str_arg); strncpy(res, result.c_str(...
66,893,607
66,893,750
How to define an array with n number of elements inside of a class
I've been making a program in C++ that calculates the surface area of a polygon with a shoelace method. I've already checked in the main code and that part works fine. The problem appears when I try to put that same code into a class. This is the code for a header file: #include "Tacka.h" class mnogougao{ public: T...
You are missing a semicolon at the end of the class definition. This will trigger the error error C2533: 'mnogougao::{ctor}': constructors not allowed a return type in MSVC (Visual Studio). Demo
66,894,216
66,901,093
How can I define a template operator inside a template class scope?
I have a problem with a matrix class that I am trying to "templatize". The idea is to be able to multiply two matrices of different type without explicitly overloading the multiplication methods. For instance let's say we have a type A and a type B. if I multiply a matrix<A> by a matrix<B> and if I know that multiplyin...
You had some problems. The changes are self-explanatory I think. Let me know if not. godbolt: https://godbolt.org/z/ErMdbfEnc #include <typeinfo> #include <type_traits> #include <iostream> template<typename T1> class Matrice { private: T1 table; public: const T1 & getTable() const { return table; ...
66,894,267
66,898,337
Do C++20 concepts enable fixing template function as template argument problem?
If you try something relatively simple in C++20 it implodes with unhelpful error message spam. int main() { auto as = std::vector{1,3,24,}; auto bs = std::vector{1,4,10}; auto cs = std::vector<float>{}; std::ranges::transform(as, bs, std::back_inserter(cs), std::max); std::ranges::copy(cs, std::ostr...
No. std::max names a template function. Template function names with incomplete template parameter lists are turned into functions during overload resolution. Overload resolution requires converting the function name to a pointer to a fixed signature, or invoking with ()s. Concepts don't help. Now you can use an olde...
66,894,570
66,895,157
Histogram Equalization without openCV, C++
I'm trying to implement histogram equalization to improve the contrast in a grayscale image, but no matter what I do, my program only seems to make the image overall darker. Can someone point me in the right direction? Here's the code I'm working with right now, as well as some sample images void calcHisto(int w, int h...
According to the wikipedia ( Histogram Equalization ): I have improbed histogram calculation performance, by removing inner loop. PDF/CDF computation is broken (according to the wikipedia formula). PDF is no needed. Please check my version below. I don't see cdfmin computation in your code. void calcHisto(int w, in...
66,896,165
66,897,423
getting a segfault when I try to deep copy `unique_ptr`s
Why can't I return a unique_ptr from a clone function? I thought I could do this. I have a base class for different mathematical functions called transform. I have a container of pointers to this type because I am using polymorphism. For example, all these derived classes have a different implementation of log_jacobian...
In get_transforms(), you are looping over the entire m_ts[] array, calling clone() on all elements - even ones that have not been assigned by add_transform() yet! Unassigned unique_ptrs will be holding a nullptr pointer, and it is undefined behavior to call a non-static class method through a nullptr. The easiest fix ...
66,896,675
66,897,026
why is a double pointer being used to create a Queue?
I have two classes Node and Queue. In Queue constructor we need to create an array of type Node in the heap. My question is why we should use a double pointer Node **Q and then create an array Q=new Node*[size] like this when we could have done created an array of Nodes with a single pointer? like Node *Q and Q = new N...
First, let's make it clear that we are looking at two distinct data structure: A binary tree, which is defined by Node objects. A queue backed by a fixed-size buffer (possibly it's a ring buffer). There is also an algorithm that uses these data structures. Based on one of the comments, this algorithm builds a binary ...
66,897,068
66,897,681
Can trim of a string be done inplace with C++20 ranges?
Inspired by cute cppreference example of trim with C++20 I have written the following code(I have changed the return type to void and arg to std::string& since my "problem"(I am inventing problems to learn C++20) does not exist in original code that uses std::string_view arg and returns std::string). void trim(std::str...
Perhaps something like this? void trim(std::string& s) { auto not_space = [](unsigned char c){ return !std::isspace(c); }; // erase the the spaces at the back first // so we don't have to do extra work s.erase( std::ranges::find_if(s | std::views::reverse, not_space).base(), s.end()); ...
66,897,952
66,898,263
Is there a c# equivalent of c++17 string_view?
C# string's Splice method seems to copy remnants into an array of strings instead of just reading them. Is there a c++17 string_view equivalent to bypass copying? For those not familiar with string_view, here is some background information. From Microsoft's <string_view>: The string_view family of template specializa...
ReadOnlySpan could work. Have a look at All About Span: Exploring a New .NET Mainstay A second variant of Span, called System.ReadOnlySpan, enables read-only access. This type is just like Span, except its indexer takes advantage of a new C# 7.2 feature to return a “ref readonly T” instead of a “ref T,” enabling it to...
66,898,242
66,906,296
How to reference/use the variables initialized by the constructor in other methods in a mfc application
So, like the title said I can't seem to use the variables initialized in the constructor in the mfc application. // CMFCApplication1View construction/destruction CMFCApplication1View::CMFCApplication1View() noexcept { // TODO: add construction code here int x1 = 0; } but when I use those variables in the onDr...
You probably have a file like MFCApplication1View.h. Your class will be declared in that file or a similarly named file. Find the class declaration in the header file and modify like this: class CMFCApplication1View { // ... other stuff int x1; }; You can even initialize it in the header file instead of the con...
66,899,036
66,899,102
how to access a local variable in another function?
I just go through an interview where i was asked how can i access local variable of function to other function. code flow- class A{ public: void fun1(int a){ int local_var=a; } void fun2(){ // here i want to use local_var of fun1 //you are not allowed to do any changes either...
Local variables do not exist if the function is not currently executing and even then, they only "exist" in a very narrow scope. Here local_var is a short-lived int that only springs into being during fun1 executing. The instant that function is done, it's gone. fun2() has no access to it because it doesn't exist at th...
66,899,669
66,899,694
buinding and running in different gcc
environment A: centos7(same os) / gcc.7.3.1(higher gcc) environment B: centos7(same os) / gcc.4.8.5(lower gcc) I have built an C++ executable in environment A and run it in environment B. I haven't had a problem so far, but could there be a problem with this approach?
Technically, building a static executable improves portability. So compile your C++ files with g++ -O -Wall -Wextra -g and link the object files with g++ -static *.o Alternatively, use dynamically only libc.so, not the C++ standard library. So link with g++ *.o -Bstatic your libraries -Bdynamic -lc For details, read th...
66,900,393
66,900,568
Why can't my loop detect \0 symbol in const string?
#include<iostream> #include<string> #include<sstream> #include <typeinfo> #include<cmath> #include<vector> #include <algorithm> using namespace std; class Mystring { char *arr; public: Mystring(const char pointer[]) { int i = 0; while (pointer[i] != '\0') { i++; cout <<...
You forgot to add '\0' at the end of your arr[]. Moreover, the size or arrshould be increased to incorporate this \0, as noted in @user7860670's answer. Moreover, using string as a variable name, in addition to using namespace std;, is confusing at least. #include<iostream> #include<string> #include<sstream> #include <...
66,900,585
66,900,805
i dont why it isnt printing the linked list
this is my code for inserting a node at the head of the linked list. there is no error but my printllist function is not working I don't know why. I think I have done silly somewhere. help me out I am stuck here for 3 hours. #include <iostream> #include <bits/stdc++.h> using namespace std; class Node { public: ...
You need to pass the head of the linked list by reference so that the changes which are made in the insert function actually remain preserved between the function calls. Also, keep in mind that all the new nodes are inserted at the beginning of the linked list. So, for example if you enter 1,2,3 as the three elements o...
66,900,692
69,733,247
G++/CMake Profile Guided Optimization cannot find generated .gcda files
I am compiling an application using CMake 3.16.3 and G++ 9.3 on Ubuntu 20.04. This is the current source directory: . (this is called MyApp) ├── src │   ├── /* source files */ │   └── CMakeLists.txt ├── tests │   ├── /* source files */ │   └── CMakeLists.txt ├── build-release │   └── pgo /* folder for .gcda files */ ├─...
For anyone wondering... I did not write the original build system of the project. I discovered that it compiled one executable and one library from the same source. Whilst the executable was profiled and recompiled successfully (PGO was done flawlessly), the library was not used anywhere. Hence the missing profile file...
66,901,141
66,901,579
Google protobuf repeated fields with C++
I have a requirement to build the following Metadata message using serialized key value pairs in C++. message MetadataValue { string key = 1; google.protobuf.Value value = 2; } message Metadata { repeated MetadataValue metadata = 1; } So I can have the values for MetadataValue from the following for statement ...
I think this code works, I just checked the generated APIs by protoc. If the typeof(p.second) is not a google::protobuf::Value, you need to add conversion like auto v = google::protobuf::Value(); v.set_number_value(p.second); // or p.second is string // v.set_string_value(p.second); Metadata metadata; if (buffer.ha...
66,901,310
66,907,072
Got an Error when using C++20 Polymorphism Lambda Function
I'm trying to write a higher-order function via Lambda in C++, and got this code. void ProcessList::SortCol(std::string col, bool flag) { auto CmpGenerator = [&]<typename T> (std::function<T(const Process &itm)> func) { return (flag? [&](const Process &a, const Process &b) { ...
The primary problem in this example is that a lambda is not a std::function. See this question. CmpGenerator deduces its argument as std::function<T(Process const&)>, but a lambda will never match that, so deduction fails. Furthermore, the body of CmpGenerator tries to return one of two different lambdas - which have d...
66,901,349
66,935,235
Trying to print out the elements of a linked list (with multiple classes)
So I have an issue that has been bugging me for days now. I have 3 classes : Film, Csalad, Dokumentum. These 3 classes describe movie/film categories, basically "Csalad" is family friendly films, "Dokumentum" is a document film. And everything else is in the Film class. The Film class is the parent class, which has a f...
A virtual print() function solved the problem, I didn't tought that it would be that easy. I over thought it.
66,901,525
66,901,807
Having trouble about 6 errors in my array code
I can't seem to correctly run the code. Would be of a great help in finding the 6 errors. I am stuck and somehow no idea where to find the error for my simple array code. Here are the errors I get. // This program uses two arrays to record the names of 6 types of pizza // and the sales numbers for each of these types ...
First of all it should be const int ARR_SIZE = 6; Next, your array elements are strings but you are defining the array as int. Another error is that when you declare an array, it should be enclosed within curly brackets instead of square brackets. There was a mistake in the logic when you were trying to accept the sale...
66,901,673
66,901,742
Why my C++ Recursion Program keeps on forever
I am coding an Inversed pyramid console application, when you enter a number, For example 3, It'll output it with the number of staircase, ***** *** * It works and everything is fine but when it outputs the pyramid. It keeps spamming spaces till the program crashes. Here's the source code: Note: This is a recursion...
Your stop condition in your recursion is wrong. Here is what I did and it displays the star pyramid correctly int Pyramid(int n, int index) { // your stop condition is wrong (not index>n but index ==0) if (index ==0 ) { return 0; } //until here for(int i=index+1; i<=n; i++) { ...
66,902,173
66,903,060
non-blocking call of std::async: how is this version dangerous?
Some time ago I was looking for a way to invoke std::async without the need of storing std::future, thus not blocking the execution at the end of the scope. I found this answer which uses a captured std::shared_ptr for an std::future, therefore allowing to make a nonblocking call to std::async. Another way of deferring...
It's undefined behaviour to end the lifetime of a non-trivial object without calling it's destructor, which happens as soon as there is a second call_async invocation. "heap-allocation related overhead" is a misnomer if the only alternative is undefined behaviour. The future returned by async has to live somewhere. The...
66,902,176
66,961,948
Avoid too many "declare same elements of Rcpp List" in nested loops
I would like to ask about how to save computational time about accessing List in nested loop. Here is an Rcpp example including two functions: #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] #include <Rcpp.h> // [[Rcpp::export]] void first(const Rcpp::List ETA ,const int N ,const int...
You're doing an implicit conversion and a deep copy during every loop, so it's no surprise that the compiler can't optimize that away. What you can do is pre-calculate all the etas and store them in a vector. (I filled in some work within the loop, since empty loops can be optimized out completely). // [[Rcpp::export]]...
66,902,278
66,902,429
How to fill a random position of a size 10 1D array with 1s and 0s the rest
how i fill 10size 1d array randomly 1 and 0 the rest like 0 0 0 0 0 1 0 0 0 0 or 0 0 0 1 0 0 0 0 0 0 or 0 1 0 0 0 0 0 0 0 0 #include <iostream> #include<cstdlib> #include<ctime> #include<windows.h> using namespace std; int main() { srand(time(NULL)); int x[10] = { 0, }, i; while (true) { Sleep...
Instatiate an array of int like int x[10] = {};, in this way you will get an array fill of zeros. Than you can simply use rand() % 10, it will produce a random number in [0, 9], and it will be the position in the array where the 1 is: srand(time(NULL)); int x[10] = {}; x[rand() % 10] = 1; for (int i = 0; i < 10; i++) {...
66,902,531
66,903,155
If pointers are just integers that hold an address (4 bytes - 32 bits), how do they store the extra addresses in 64-bit memory?
When using the sizeof() function in c++ programs, the pointers I've looked at seem to all return a size of 4 bytes. I've seen online that pointers are just integer memory addresses. How does this make sense in 64 bit architectures that would then potentially have memory addresses that cannot be accessed in 4 bytes?
Most modern 64-bit operating systems support a 32-bit mode for backward-compatibility. If sizeof(void*) == 4 with you, then you are probably targetting the 32-bit platform of your operating system, so that your program will run in 32-bit mode. Check your compiler's documentation on how to target the 64-bit platform of ...
66,902,584
66,902,872
C++ Variable number of async tasks
In this example i have 3 tasks which should run parallel. This works realy well. But now the number of tasks is variable. How can i handle that? I tried something like vector of lambda expressions but that doesn't worked. Thanks for helping ! #include <iostream> #include <future> #include "myclass.h" #define N 3 ...
Use a loop and create a new lambda with different binding context every iteration: std::vector<std::future<void>> tasks; for (auto& instance : instances) { tasks.push_back( std::async(std::launch::async, [&, instance]() { bool finish = false; while (!finish) {...
66,902,654
66,903,195
C++ addition operator overloading multiple times
i am trying to get some mathematical construct working which contains 'Cells' which represent a mathematical function with a set of inputs and outputs. Each mathematical operation gets their own class which inherits from Cell. Using some operator overloading, I would like to spawn a new Add-Cell when i call operator+ o...
We have 2021 so use C++11 std::unique_ptr and std::make_unique from C++14. class Cell{ private: using ptr = std::unique_ptr<Cell>; ptr A; ptr B; public: Cell() { std::cout << "default constructed" << std::endl; } Cell(Cell&& A, Cell&& B) { this->A = std::make_unique<Cell>(std:...
66,902,856
66,917,864
Entry point errors when running OpenCV projects with MingW
I have installed MingW C++ compiler on Windows 10. I built the OpenCV libraries successfully. Then I wrote a test project as follows. #include <iostream> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> using namespace std; using namespace cv; ...
The culprit is: There are two 64-bit libstdc++-6.dll files in my PATH. The older one unfortunately is on the top so any request to 64b-bit libstdc++-6.dll will be bounded to the top one. As a result, my applications that need the new one gets crashed. Swapping them solves the problem. Using 32-bit version of MinGW can ...
66,902,889
66,904,401
Inside result of regex matching
I have a character stream, producing one char each step. Step 1: produced character '1', final string '1' Step 2: produced character '2', final string '12' and so on... Each step I want to know if the produced final string (sum of every char produced) has possibility to be matched by regexp in the future. Example reg...
Following on from the comment, you could make use of boost::regex and its boost::regex_constants::match_partial flag... boost::regex re("^(\\d{5})$"); boost::smatch caps; std::string text = ...; if (boost::regex_match(text, caps, re, boost::match_default | boost::match_partial) { /* * Matched successfully. N...
66,903,102
66,903,541
Side-effect of std::srand/rand and libuuid uuid_generate
For testing I need reproducible random numbers. The randomness isn't that important. Currently I'm setting a seed std::srand(x) and use std::rand() to generate. As expected the numbers are always the same on multiple runs with the same seed. For some other parts I need UUIDs. I use the utils-linux libuuuid. But running...
As expected the numbers are always the same on multiple runs with the same seed. Until they are not. rand() is not required to use a certain algorithm. It can change if you upgrade - or if you compile on a different platform. It may also be affected by other functions as you've noticed. You could use a generator from...
66,904,973
66,905,213
I have a list of pointers to objects of the items class. How do I access the object's functions?
I managed to write the data to the objects from the file. But I can't output this data to the console. I already wrote-ListtForLoad.first().getName() But can't get such access I attach the full code of my program. #include <QCoreApplication> #include <QFile> #include <QString> #include <QDebug> #include <QIODevice> #in...
You are storing QObject*'s in the QLinkedList so when you do the below, you get a QObject* back: ListtForLoad.first() // <- QObject* here .getName() To derefernce a pointer, you need to use -> instead of . so: ListtForLoad.first()->getName(); However, QObject doesn't have a getName() member function. You should prob...
66,905,604
66,905,829
Clang warning when returning a lambda-capturing lambda
The following (simplified) code trying to wrap a lambda gives me a warning with some Clang versions, but not all and not gcc. template<typename Lambda> auto wrapLambda(Lambda lambda) { return [&lambda]() { lambda(); }; } auto wrappedLambda = wrapLambda([](){ return 0; }); warning: address of stack mem...
Problem is exactly same as for this code: SomeType& foo(int x) { SomeType bar{x}; return bar; // undefined behavior returning reference to local object } Your lambda is capturing local object by reference, so when you return it, this will lead to undefined behavior since, captured object is no longer alive. Mo...
66,906,094
66,906,589
Is it possible to call a function without a direct reference in C++?
beginner here I am trying to make a "logger" for my c++ learning project, I´ve already set up code to manage the logging itself, but I can´t get the function to work from other classes. Here´s my "Debugger" class class MSEdebug { MSEdebug(){logOutput.open("log.txt");} ~MSEdebug() { logOutput.close...
The canonical way is to use the singleton pattern to have a unique instance of the class MSEDebug that is easily accessible. class MSEdebug { MSEdebug(){logOutput.open("log.txt");} public: ~MSEdebug() { logOutput.close(); } void debuglog(std::string info) { #ifdef DEBUG ...
66,906,476
66,907,084
SDL2: Could not create window: No available video device
I'm running Ubuntu 20.04 and trying to use the SDL2 library to build a C++ program. I've installed the library from apt, so didn't compile it myself. I'm also using CMAKE. The problem is that I can't run the program because it reports an error saying: Could not create window: No available video device I've read this ...
If your DISPLAY environment variable is not set, you can either set it inline along with your app command DISPLAY=:0.0 ./yourApp or set it permanently in the console where you execute your app: export DISPLAY=:0.0 ./yourApp To set environmental variables from CMake, you can use cmake set command set(ENV{DISPLAY} :0.0...
66,907,071
66,907,116
What are the differences between running a command in bash and running a command in a Makefile?
I have this command that compiles my program. c++ -O3 -Wall -shared -pthread -std=c++11 -fPIC $(python3 -m pybind11 --includes) f1.cpp f2.cpp -o exemple$(python3-config --extension-suffix) I created the following Makefile. test: c++ -O3 -Wall -shared -pthread -std=c++11 -fPIC $(python3 -m pybind11 --includes) f1.c...
Makefiles run commands in /bin/sh (by default). That can sometimes make a difference, if you're using bash features; but you're not so that doesn't matter. The issue here is that the $ character is special to make: it introduces make variables. If you want to pass a $ to the shell you have to double it: test: ...
66,907,162
66,907,386
How to reorder function parameters?
Look at the pseudo-c++ code below: typedef *** SomeType1; typedef *** SomeType2; typedef *** SomeType3; void BFunc(SomeType1& st1, SomeType2& st2, SomeType3& st3) { /*some work*/; } template <typename T1, typename T2, typename T3> void AFunc(T1& p1, T2& p2, T3& p3) { BFunc(???); } There are two functions wit...
You can use std::get to fetch a value by its type from a tuple and std::tie to bundle your arguments into a tuple of references. Obviously, this only works if your argument types are unique. Make sure std::get uses a reference type to avoid unnecessary copies. #include <tuple> // arbitrary argument types struct SomeTy...