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,969,326
62,969,632
Increment an integer pointer and assign the value of the incremented pointer to another variable in C++
I wrote the following code in Microsoft Visual Studio: #include <iostream> using namespace std; int main() { int i = 1; int *p; int val; p = &i; *p = 101; val = *(p + 2); cout << val << endl; cout << i << endl; return 0; } In the line val = *(p + 2), since *(p + 2) returns the ...
You got it all wrong. p points to i. It means that p stores the address of i. Which adress it is, is unpredictable. It may be 123456. We only know that at this adress, the number 101 is written. *(p+2) is the integer which is stored in memory at 2 positions after i. For instance, if i has address 123456, and intege...
62,969,746
62,969,846
Facing some problem in 2D array to add each row-wise elements in c++
In c++, I wrote a code for 2d array to add each row-wise elements. But I don't understand why I got sum=3 in row 5 and 6 where I would get the sum = 2 instead of 3.but in my code others row gave the correct results. I don't know where is the problem? #include<iostream> using namespace std; int main(){ ...
Look how big a_row is int a_row[4]={0}; Now look how big i is for(int i=0;i<8;i++) Now look how you use a_row and i a_row[i]=a_row[i]+a[i][j]; See the problem? Actually there's no need to a_row to be an array at all. A simple int variable would work just as well. You don't always have to use an array just because yo...
62,969,824
62,969,864
Common print function for all variants of maps C++ STL
I am brushing up some skills on C++ STL and I wrote a basic insertion/deletion code for maps. Below is the code. It is taking some inputs from user and inserting/deleting accordingly. Very simple code. But the issue is I have to write separate print functions for every map variant. Is there anything I can do to make it...
Well, yes, that is, indeed, what templates are used for, right? template<typename T> void print(const T& mp) { cout << "Contents of map: { "; for(auto& it: mp) { cout << it.first << " -> " << it.second << " "; } cout << "}" << endl; } This'll work as long as only maps, or reasonable facs...
62,969,837
62,969,860
Why this C++ code is not counting properly?
I have written a code in c++ to count zeros. The input have to take as string. The input will be a digit with 1 and 0. Example: Input: 1000000001 Output: 8 The answer should be 8 but my code is showing 0. Where is the problem in the code. Code: #include <bits/stdc++.h> using namespace std; int main() { string play...
you need to compare with char not int: if (players[j] == '0')
62,969,947
62,970,004
why am I getiing 0 as a result,I want the return value as the result?
I want the result to be the returned value from the mystery function,but the result is always 0 .but I want the program to return a value that's collected from the mystery function #include <iostream> using namespace std; int Mystery(int n) { // int k; if (n <= 1) { return 0; } else {...
Let's desk check what happens when you call Mystery(2). The final return value is: ((k* Mystery(n/2)) + (8* Mystery(n/4))) We know that n == 2 so let's substitute that: ((k* Mystery(1)) + (8* Mystery(0 /* by integer division of 2/4 */))) This will call the function recursively twice with the respective arguments 1 a...
62,969,972
62,970,008
Why address gotten from the pointer is always the same?
I am a bit confused now. So, if i write the following code: int x = 5; cout << &x << endl; compile it and run, I'll get something like 0x920FC7D which is the normal hexadecimal value for memory locations. But when I compile and run the following code: #include <iostream> using namespace std; void add(int a, int b){ ...
If you take a look at the overloads for the operator << with a std::ostream& as the left hand operand, you'll find that there are no overloads for pointers to functions as right hand operand. But you are inserting function pointers. So, what is being inserted? Well, function pointers are implicitly convertible to bool,...
62,970,070
62,970,103
why cout is not printing this string?
So, I'm new to C++ and I can't figure why this is happening. I have a string with all the alphabets and I copied 10 characters from it into a new string s2, character by character using a for loop as follows and when I execute it the cout function is printing a blank line. #include <iostream> using namespace std; int...
Both your code have undefined behavior. string s2; just initializes s2 as an empty std::string which contains no elements. Trying to access element as s2[i] leads to UB, means anything is possible. (Even it appears to give the correct output in your 2nd code snippet.) You can use push_back to append element as for(int ...
62,970,201
62,970,294
What decides where on the heap memory is allocated?
Let me clear up: I understand how new and delete (and delete[]) work. I understand what the stack is, and I understand when to allocate memory on the stack and on the heap. What I don't understand, however, is: where on the heap is memory allocated. I know we're supposed to look at the heap as this big pool of pretty m...
The memory is managed by the OS. So the answer depends on the OS/Plattform that is used. The C++ specification does not specify how memory on a lower level is allocated/freed, it specifies it in from of the lifetime. While multi-user desktop/server/phone OS (like Windows, Linux, macOS, Android, …) have similar ways to ...
62,970,606
62,980,245
Simultaneous STL container insertion with strong exception guarantee
I want to insert into several STL containers simultaneously, and either have all succeed, or all of them remain unchanged. How can I do this elegantly? In my example, I have a custom container with various STL containers as data members. An insertion operation inserts into various containers, but if one of them fails, ...
I don't address the actual clean up operation nor what is the most efficient way to do that. You will need to record at what stage the insertion failed and proceed accordingly. struct DataItem { int x; float y; char c; }; class SomeException : std::exception { public: SomeException(char *c) : std::exceptio...
62,971,306
62,971,855
C++: Static member function returning an object of self static for a class with private constructor
I've a C++ snippet as below. The "getInstance()" function is trying to return a static object of the same class "CAbc". This class has a private constructor so that objects of this class can't be created. While calling this function in main(), like in below snippet, the returned object is not being collected anywhere i...
As @tkausi says, the static member function can create an object, as it is a member (thus having access to private methods.) What this code does is having an instance of the class, only one object (_self) and returning it for use. Why nobody gets the return value? Because the call is there only to create the instance. ...
62,971,540
62,971,627
What is the need of using comparator function inside structure?
I cannot understand what is happening inside the struct comp and the bool operator() function. And how does the the map and iterator behave if I write map<int,int,comp> ?
Your properties are recursively calling themselves. Take your Sid property public int Sid { set { if (Sid <= 0) Console.WriteLine("Id must be positive."); // here, also validation wrong--use value else Sid = value; // here } get { return Sid; } //here } Where I've marked, the getter an...
62,971,688
62,981,765
boost::asio::async_accept the handler is not called
took example from boost https://www.boost.org/doc/libs/1_70_0/doc/html/boost_asio/example/cpp11/ssl/server.cpp exactly as it is assembled it started it works. then took the implementation from the interface to SSL_Server.h, SSL_Server.cpp, Session.h, Session.cpp, main brought it to Serv.cpp As a result, the handler is ...
I see nothing wrong with the code. In fact it works for me. HOWEVER, you need the certificate, key and DH param files present in the working directory. I don't see a lot of of explicit error handling, so I suppose this is your likely problem: context_.use_certificate_chain_file("server.crt", ec); if (ec) throw boost::s...
62,972,295
62,973,467
What is the point of including array's size in a function declaration?
I understand how arrays can be passed to functions in c++, but I don't understand what is the point of including array's size in a function declaration when this size is ignored anyway, because what we are really passing to function is a pointer to the first element of the array. For example if we have following code: ...
One of C++’s major design goals was far reaching compatibility with C. Not supporting all aspects of C-array usage would have been seriously detrimental to this goal. Your examples even give a good indication that compatibility is indeed the intent, and that C++ would work differently if that hadn’t been the case. Cons...
62,972,809
62,972,862
Random numbers produced in output (C++)
I am reading data from a text file and running the code below. However, I am getting random numbers in mu output along with the correct numbers. I can't figure out where I am getting these random numbers from. My text file includes the following: Fred Blue 20 Harry Blue 35 Tony White 43 Hilda Blue 12 Paul White 34 Tom ...
The problem is that you are asking the program to print out all 10 members of the array when you don't have 10 valid entries in the array. That's why you get random numbers at the end. You need to change (for example) printArray("White", white_members, white_scores, 10); to printArray("White", white_members, white_sco...
62,973,197
62,973,341
Failing to get line numbers with Boost stacktrace + backtrace
I'm trying to reproduce the first and simplest example in the Boost Stacktrace documentation. #define BOOST_STACKTRACE_USE_BACKTRACE #include <boost/stacktrace.hpp> #include <iostream> void bar(int n) { if (n <= 0) { // ... somewhere inside the `bar(int)` function that is called recursively: std::...
To get more information in the stack track uses a debug build. For GCC compile a project with the flag -g or -fno-omit-frame-pointer.
62,973,780
62,973,867
How do I convert a UE4 FString into a string?
TextLine2 needs to be a regular string however I receive the error no instance of constructor matches the argument list. void AAH_Ver1_2::GetEachTextFromLine(FString TextLine1) { string TextLine2 = TextLine1; istringstream iss(TextLine2); }
You can convert an FString to an std::string with the TCHAR_TO_UTF8 macro: std::string const s = TCHAR_TO_UTF8(*fstring);
62,973,857
62,977,603
C++ how to flush stdin
I have a program where a client is in receiving mode and it's waiting to receive some data; while the program is "blocked" if the user write on the terminal, when the program come back from the receiving i have a std::getline() that has to read from the stdin but it read the input given by the user when the program was...
What you need is a so called Reactor. There is a design pattern for that. You want to wait for an event from 2 or more sources. To solve this, you can use one of the many existing functions like select or poll or epoll. With this functions you can register a desired event on a certain handle (like a socket, or a file h...
62,973,993
62,974,017
Determine how to destruct an object of a given type
So I am currently in the process of making my own version of a std::vector to use in kernel mode. However I have ran into an issue: I am not sure how to determine how to properly destruct a given element. For example, you could fill an array with integers and you wouldn't need to do anything to destruct it. But for a c...
You don't have to. You can call obj.~T() for any object o of type T you wish to destroy. If it has a trivial destructor this call will likely result in no operations emitted by the compiler. Furthermore, you should also placement new trivial types, even if they don't have an explicitly implemented constructor. MWE: #in...
62,974,021
62,974,246
MSVC use additional include directories of referenced static library project
I have two projects in my C++ MSVC solution: A static library project A .exe project that has a reference to the Project #1 (the static library project) Project #1 has additional include directories, C:/addincdir . Project #1's header file, p1header.h includes the header hd.h from C:/addincdir. Project #2 includes...
No. There is no way to automatically add the folders. (step 5 in Walkthrough: Create and use a static library - Use the functionality from the static library in the app) To include a header file (listed in the additional include folders) you need to use <... > #include <header.h++>
62,974,472
62,974,591
Is it possible to have a C++ function or macro that writes the code of another function to file as a string?
Is it possible to have a function write the contents (i.e. the actual code) of another function to a file? For instance say we have a function that adds two numbers: int add(int a, int b){ return a + b; } would it be possible to have another function or macro that would write this function as a string to a file? v...
I don't have much recent experience with C++ but I think it's possible to at least read the contents of a text file and copy it over to another? Obviously you can't have the code you'd like to copy running at the same time but if you need just to copy the contents and save it to a different location that's possible. Th...
62,974,553
62,980,923
Setting cursor for the gap in between controls
I have statically added few .cur files to the executable. I can get them well; wc.hCursor=LoadCursor(hInstance,MAKEINTRESOURCE(151)); //before registering window class HCURSOR cursn=LoadCursor(hInstance,MAKEINTRESOURCE(151)); HCURSOR cibeam=LoadCursor(hInstance,MAKEINTRESOURCE(152)); Then I use this method I've found ...
I figured out that "the gaps" between controls are called nonclient area and setting cursor like this; case WM_SETCURSOR: { if(LOWORD(lParam)!=HTCLIENT) //the opposite of the example documented on MSDN { SetCursor(cursn); return 1; } break; } It may be nonstandard and disapproved but it...
62,974,692
62,974,732
while and for loops no. of iterations known
I read that while loop is used when number of iterations are unknown and for loop is used when number of iterations are known ... such as when I have to print a statement 5 times I have to initialize the variable in both while and for loop and also I need to give iteration condition in both (i++) and i also have to men...
There is no real difference between while and for. { int i = 0; while(i < 5){ //stuff i++; } } is the same as for(int i = 0; i < 5; i++){ //stuff } But as you can see, the for is easier to use when you have a known condition. For example, suppose you are running an algorithm that finishes when a list...
62,974,774
62,974,884
Find current base of output stream
Is it possible, when overloading the << operator to write to an output stream, to get what numeric base this stream is currently in? E.g. if std::hex was called before calling my overloaded operator, can I find out if the stream is currently in "hex mode"?
Okay after digging a little about how this base change actually works, I found out that there are basically only these 3 bases to choose from (std::dec, std::oct, std::hex). Calling std::setbase() with a value other than 10, 8 or 16 simply defaults to dec. As Paul Sanders figured out one can get the current flags via s...
62,974,829
62,974,841
Overloading [] operator of Matrix class with const
I'm having some troubles trying to understand the following. While writing a simple Matrix class with vector and templates I tried to overload the [] operator to acces the elements. This is the class #pragma once #include <vector> #include <iostream> template <typename T> class Matrix { private: std::vector<std::v...
The method being const means that the member variables are treated as const and can’t be modified. You’re currently returning a std::vector<T>& which means a caller could modify it (but that goes against the const qualifier). Change the return type to const std::vector<T>&, so that callers can’t modify the returned val...
62,974,883
62,976,381
Is there a way to generate the corners of a regular N-gon without division and without trig, given N as input
Edit: So I found a page related to rasterizing a trapezoid https://cse.taylor.edu/~btoll/s99/424/res/ucdavis/GraphicsNotes/Rasterizing-Polygons/Rasterizing-Polygons.html but am still trying to figure out if I can just do the edges I am trying to generate points for the corners of an arbitrary N-gon. Where N is a non-ze...
There's no solution which avoids calling sin and cos, aside from precomputing them for all useful values of N. However, you only need to do the computation once, regardless of N. (Provided you know where the centre of the polygon is. You might need a second computation to figure out the coordinates of the centre.) Ever...
62,975,308
62,983,337
Taglib read ID3v2 tags from arbitrary file c++
I'm trying to use the TagLib C++ API to read ID3v2 metadata from an arbitrary audio file. This file is not necessarily an .mp3 file, and may be of the other common audio formats. I have the following: std::string readId3v2Tag(std::string filePath, std::string tagName) { // read from file TagLib::FileRef f(fileP...
Always read the manual: it tells you to not use the file() approach. Also properties() won't give you ID3v2 tag frames - you should iterate all of them to see their keys and values. Instead use MPEG::File (see manual) and from there go/read on over ID3v2Tag() (see manual) to frameList() (see manual). It's pretty stra...
62,975,764
62,975,779
Extracting value from a vector in C++
I have a vector that consists of an array of data after reading in a config file. Now, I will like to extract some values in the vector and passing it as int. I am able to get the value range but I am not sure how to continue from there on. Example: string MapXInput, MapYInput; vector <string> placeholder; cout << pl...
An easy approach is to use a std::istringstream: std::istringstream iss{MapXInput}; // e.g. "12-20" char c; if (!(iss >> x_start >> c >> x_end && c == '-')) { std::cerr << "unable to parse MapXInput\n"; exit(EXIT_FAILURE); } You can think of iss >> x_start >> c >> x_end as meaning "can I parse/extract 3 value...
62,976,069
63,006,160
Change the font displayed as you type QTable
The font in the cells is large but the font is small when you enter it . Is it possible to configure the font when entering text without using "qt designer" so that you can change it dynamically
ui->tableWidget->QWidget::setFont(QFont("Times",89,QFont::Bold));
62,976,212
62,976,292
complex number addition and using copy constructor
#include<iostream> using namespace std; class complex { float real,imag; public: complex(complex &c) { cout<<"copy constructor"<<endl; real=c.real; imag=c.imag; } void showData() { count<<"the sum is"<<endl; cout<<real<<"+i"<<imag<<endl; } c...
You need to define two constructors for the complex class to solve it: complex() {} complex(float rl, float im) : real(rl), imag(im) {} The value were never initialized since there were no constructors given to put 2 & 3 in real & imag respectively. The class object c1 will require complex() {} constructor.
62,976,329
62,976,401
Is it possible to initialize a constexpr std::array from a constexpr function?
Im trying to make an array that should be {1, 2, 3, 4, 5, 6, 7, 8, 0} and i would like to do simething like this: constexpr std::array<int, 9> getFinalTable(){ std::array<int, 9> result{}; for (size_t i = 0; i < 9 - 1; ++i) result[i] = i + 1; result.back() = 0; return result; } But Visual Stud...
It'll correctly work in -std=c++17 (C++17 and above) compilation. From the first answer to this question, the comment from the OP indicates that the line: result.back() = 0; Won't let the compiler compile it due to: main.cpp: In function 'constexpr std::array<int, 9> getFinalTable()': main.cpp:9:21: error: call to non...
62,976,470
62,976,547
printing a priority queue of objects in c++
I am trying to print a priority queue however it is giving me the following error: [Error] passing 'const value_type {aka const Horse}' as 'this' argument of 'void Horse::print()' discards qualifiers [-fpermissive] here is how my code is laid out: struct horse { std::string horseName; int win; void print() { ...
std::priority_queue::top() returns a const &, which means you can only call const functions on this reference. Since print does not change the state of the object you should make it const: // VVVVV void print() const { std::cout << "name: " << horseName << std::endl; } Some unrelated hints: Code like i...
62,976,831
62,977,159
Are C keywords/functions not enclosed in std namespace in C++?
The following piece of code works fine on my local system but threw compile error on an online platform. #include <iostream> int32_t time[int32_t(1e5)]; int main() { int32_t n; std::cin>>n; for(int32_t i=0;i<n;++i) { int32_t temp; std::cin>>temp; --temp; ++time[temp]; ...
The standard says that when you include any standard include file it is possible that this will include other include files. It is implementation dependent which ones and how many of them. The implication is that your code simply must not define any global name that is also standard. I can understand this seems a diffi...
62,977,330
62,977,418
Is there an compiler bug in vc++? (I am a beginner)
There are different effect between vc++(debug mode) and g++, with this code test.hh class Test { public: int a, b, c; Test(int a, int b, int c) : a{ a }, b{ b }, c{ c } { } Test& operator++(); Test operator++(int); }; std::ostream& operator<<(std::ostream& os, const Test& t); test.cc std::ostre...
Unfortunately << has a psychological effect of pushing the idea of "sequencing". While std::cout << a() << b() << c() conveys the idea of computing a(), then b() and then c() this is (was) false. You only know they will be put in the output stream in sequence, but they can be computed in any order (before C++17). This ...
62,977,402
62,977,461
When I am trying to enter a node between doubly circular linked list it gives wrong output
Here I created a doubly circular linked list and try to add a node between the list but it is giving wrong output I first created a doubly circular linked list and then displayed it and then I added a node between them and then again displayed it #include<iostream> using namespace std; class node ...
You are printing the head node instead of the tail node due to the extra temp=temp->next; after the loop in the disp() function. You are adding val instead of val1 after the loop in the main() function. void disp() //display function { node *temp=head; while(temp->n...
62,977,877
62,977,902
Dynamic Memory Allocation relieving Trigger Issue
When I tried to relieve 2 dynamic memory allocations at the end of the code, Trigger issue had been popped up. I assume that I set unspecific array so it's likely that compiler define the size of memory to be relieved bigger. how can I correctly modify these 2 lines delete[] msgs; and delete[] imageFile; ? Here's the c...
In this case, each elements of arrays are pointers to dynamically allocated objects but the arrays itselfs are not dynamically allocated. Therefore, you should remove the delete[] lines and use delete for each elements instead. for for (size_t i = 0; i < sizeof(msgs) / sizeof(*msgs); i++) { delete msgs[i]; } for (s...
62,978,069
62,978,109
Trying to use std::find with a vector of custom type objects (C2679, binary '==': no operator, rhs, 'const _Ty'), Visual Studio 15.9.25
Dear StackOverflow community, Having the type Couple defined like this: class Couple { public: Couple(Thing* aa, Thing* bb) : a(aa), b(bb) {}; public: bool operator == (const Couple& rhs) const { return this->a->unique_id == rhs.a->unique_id && this->b->unique_id == rhs.b->unique_id; } bool operator != (con...
So I think you have a few problems, but the most fundamental is this std::vector<Couple*> couples; You have a vector of Couple pointers. no amount of overloading operators for the Couple class is going to help you find things in vector of pointers. Another problem you have is that you are pushing pointers to locally s...
62,978,324
62,978,363
Alternative to push_back for 'new' dynamic array?
I am required to use the keyword 'new' to create a dynamic array (part of learning purpose). The program will read a text file and then extract each line and put it into the array. I have done it successfully for the vector method but I can't see how to change the method to make it work with 'new'. This is my vector me...
You should define a counter variable and use it for selecting elements to use. string * placeholder1 = new String[5]; int pos = 0; while(getline(filename, linedata)) { if (pos < 5) placeholder1[pos++] = linedata; } or string * placeholder1 = new String[5]; int pos = 0; while(pos < 5 && getline(filename, placehol...
62,978,669
62,978,870
C++ functors behavior
#include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; struct cmp { bool operator()(const int& i, const int& j) const{ return false; } } ; struct cmp2 { bool operator()(const int& i, const int& j) const{ return false; ...
One part of this is that cmp2_item is not a type, its an instance of the type cmp2. So you can't pass that as a class type. You might be able to do: set<int, cmp> s; //# WORKS set<int, decltype(cmp2_item)> s2; //# NOW WORKS For these: // Not ok because cmp is not a function comparison object, its a type ...
62,978,801
62,978,865
Create an array of objects using std::unique_ptr
I am currently learning smart pointers and am trying to do the following: #include <memory> #include <string> int main() { std::unique_ptr<std::string[]> str_array(new std::string[5]); for (int i = 0; i < 5; i++) { std::getline(std::cin, str_array.get()[i]); } return 0; } This code simply scan...
It's caused by the fact that new std::string[5] is a dynamic array allocation, and so it has no (fixed/defined/calculable) size (if you don't save it before the allocation), infact auto p = new std::string[5]; std::cout << sizeof(p); Will print 8 that is the size of a pointer. And so the debugger sees that ptr as a po...
62,978,969
62,979,084
how to get hdd's free space
I want to get free hdd's size in a remote system with ssh. I found this ways: 1-do it via command line: hdd's totalsize - sum of partitions size on that hdd + sum of free spaces on all partitions on that hdd; There are some problems with this way. first, I prefer not to use commands, because it will get way complicated...
you do not give the results you have, so I can see two reasons : First may be you have an overflow when doing buffer.f_blocks * buffer.f_bsize and buffer.f_bfree * buffer.f_bsize because your unsigned long are on 32b, so do for instance : const double total = ((double) buffer.f_blocks) * buffer.f_bsize / GB; const doub...
62,978,989
62,979,147
Running multiple executables with a single command in CMake and collecting the resulting output in a .txt file
I have a simple toy project with the following structure: (base) ciaran@DESKTOP-K0APGUV:/mnt/d/TestProject$ tree . . ├── CMakeLists.txt ├── first.cpp └── second.cpp 0 directories, 3 files //CMakeLists.txt cmake_minimum_required(VERSION 3.18) project(TestProject) set(CMAKE_CXX_STANDARD 14) add_executable(FirstProgra...
How can I gather the executable targets FirstProgram and SecondProgram together so I can easily run them? add_custom_target(run_them_together_easily COMMAND $<TARGET_FILE:FirstProgram> COMMAND $<TARGET_FILE:SecondProgram> ) How can I capture the output of these programs and write them to a file? A "proper ...
62,979,099
62,979,387
How a dynamically allocated object is deleted if an error occur in the program in C++?
I was wondering how a dynamically allocated object is deleted if an error occured in the program. Imagine this one: int main() { int *ptr = new int(); int result = 15 / 0; delete ptr; } Division by 0 is completely impossible, so the int associated to the ptr will never be deleted?
How a dynamically allocated object is deleted if an error occur in the program in C++? It isn't deleted. And because the pointer value will be lost, it cannot ever be deleted. This is known as a memory leak. Division by 0 is completely impossible, so the int associated to the ptr will never be deleted? Note that be...
62,979,124
62,980,875
Loop over vector exits with error Process finished with exit code -1073741819
LE: In case it has any relevance i am using CLion. The program doesn't print anything. I need to process a vector that contains vectors of string in the form of name card_type and display all cards in alphabetical order and the number of instances for each one. Output should look something like: a_card 1 mastercard 4 v...
@xampierre here a simpler function without using std::sort and the algorithm lib void stats(const std::vector<std::vector<std::string>>& vec) { std::map<std::string, int> orderedCards; for(auto & client : vec) { auto it = orderedCards.insert(std::make_pair(client[1],1)); if (!it.se...
62,979,810
62,982,743
How can I check if CreateProcess is working or running?
I use CreateProcess to start a .exe of mine. I want to know if everything worked fine or if it encouter errors when I tried to start this .exe. From what I can tell, I need to use GetLastError(), but I tried to simulate an error in the process path but it return the same last error code. So I want to catch if CreatePro...
All the information you are looking for is spelled out in the documentation for CreateProcess: If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError. Note that the function returns before the process has finished ini...
62,979,959
62,981,773
opencv draw rectangle function behaves different in C++ , python
I am getting bounding boxes from Yolo implementation in C++, the detected bounding boxes draws correctly using cv::Rectangle function in C++, but when drawed same bounding box coordinates in python it's localising objects incorrectly, C++ cv::Rectangle function output, Python cv2.rectangle method output, I also made ...
I came to conclusion that, cv::Rectangle function takes , offset values for width and height arguments , so suppose rect = cv::Rect(x,y,w_offset,h_offset) cv::rectangle(img, rect, cv::Scalar(0x27, 0xC1, 0x36), 2); c++ implementation for cv::rectangle function internally manages offset values with there respective endi...
62,980,187
62,980,439
Rust vs C++ : Returning objects from functions
I am new to Rust and trying to understand how ownership is passed when objects are returned from functions. In the following reference based implementation , since reference doesn't have ownership , when "s" goes out of scope, it gets drops and deallocated. fn dangle() -> &String { // dangle returns a reference to a S...
Both rust and C++ are value typed languages, so objects/structs are not allocated on the heap unless explicitly asked for. So in neither of the cases given is the string object/struct in question allocated on the heap. In both languages strings use a dynamically allocated backing buffer which is stored on the heap, but...
62,980,343
62,980,421
How do I iterate vector
I have such a code #include <iostream> #include <vector> #include <string> using namespace std; void removeFirstFromVec(vector<int> & vecLink) { // remore first element from some vector vecLink.erase(vecLink.begin() + 0); } int main() { vector<int> myVec; myVec.push_back(1); myVec.push_back(2); ...
In the range-based for loop for (auto & i : myVec) { cout << myVec[i-1] << endl; } i is the element of the vector, not the index. It should be for (auto & i : myVec) { cout << i << endl; }
62,980,365
62,980,636
Unrolling and forwarding arrays
I'm having trouble unrolling and forwarding a parameter pack of std::arrays to another function Suppose we have a function that takes a single std::array and I want to unroll it and pass it as an argument to some other function I can do so by doing this: template<typename T, typename...Ts> void other_function(T, Ts...)...
You might have a "generic" getter template <std::size_t I, typename Container, typename ... Containers> decltype(auto) get(Container&& container, Containers&&...containers) { constexpr std::size_t size = std::tuple_size_v<std::decay_t<Container>>; if constexpr (I < size) { return container[I]; } els...
62,980,562
62,980,712
Cout empty when there are two getline?
I am trying to cout my array but it keep showing empty whenever I try to. int array_size = 0; int pos; string line; ifstream inFile; string filename = 'test.txt'; inFile.open(filename); for(array_size = 0; getline(inFile, line); array_length++); string * array_holder = new string[array_size]; while(getline(inFile, ...
for(array_size = 0; getline(inFile, line); array_length++); This loop reads inFile, one line at a time, until the end of the file is reached. After this loop terminates, the entire file has been read. After all, that's exactly what your program tells your computer to do: read one line at a time, incrementing the count...
62,980,710
62,981,176
How to write a prepared update query?
I've been trying to write an update function that takes the user to be updated(usr), the flag which then translates to the field to be updated and the new value. Here's the function, bool DBManager::updateDB(User* usr, int flag, QVariant& value) { QSqlQuery query; bool status = false; QString temp_value = "...
Cause First problem It is not hard to guess, that value binding works only for values, not for field names. For more info, please read about Inserting, Updating, and Deleting Records. Second problem Found by @JimCastro: You have a typo in your query. UPADATE should be UPDATE. Solution Use a string concatenation to form...
62,981,142
62,981,181
Array of Structure within an Array of Structures within an Array - C++
I will try to describe my problem as best in English first starting from the top: This starts with a structure named 't' which there needs to be 6 of (this never changes), which contains some simple variables - but also needs to contain an array of structures called 'p' which there needs to be 4 of per 't' object. 'p' ...
The problem here is of the order of declaration/definitions. You need to at least have the type declared before the compiler can understand and use it (which then would be an "incomplete type", since it's not yet defined. These incomplete type can only be used in certain cases, like declaring pointers to them etc). In ...
62,981,197
62,981,287
C++ modifying Object data constructed with stack arguments
Guys I can't seem to do simple modification of a container object member stored in a vector. This member is an object itself. Both the container and its member are allocated on the stack. I think it is trying to deallocate a stack variable of the original name of the device when assigning a new one. Please give me a cl...
You need to fix your setName method, is not returning anything and is marked to return a string. string setName(string newName) { m_name = newName; return m_name; //this is missing in the original code }
62,981,214
62,981,291
Why does the ranges library define two names for each view?
In the ranges library for c++20, all the views have a second version. For instance, std::ranges::views::filter According to cppreference: The expression views::filter(E, P) is expression-equivalent to filter_view{E, P} for any suitable subexpressions E and P. We have the actual class, std::ranges::filter_view, and th...
all the views have a second version No, they do not. filter_view is a type. filter is a functor. By calling the filter functor, you can create an object of the corresponding filter_view type (or near-enough). But you can also call the filter functor with only one parameter: the filtering predicate. The return value f...
62,981,248
62,981,264
Command Line Arguments With "-" Prefix
I'm trying to write a program which I'll be able to start with custom arguments. Like in this example "program.exe -width 1920 -height 1080". I wrote a simple code, which should work. #include <iostream> int main(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { if (argv[i] == "-width") ...
You are comparing pointers, not strings. To compare strings via ==, you should use std::string. Also you should check if the elements argv[++i] exists. #include <iostream> #include <string> int main(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { if (argv[i] == std::string("-width") && i + 1...
62,981,532
62,981,702
how to erase a thread after joined it?
Multithreading program in c++, the problem is: i have a vector of threads, where i push_back every thread i create, and i want to make a kind of "steal-work scheduling", in such a way that when a thread is joined, so i assume his job is terminated, i delete it from the vector of threads and i push_back a new thread ass...
for (thread &t : tids) { Range iteration is implemented using iterators from the underlying container. A simple Google search gives you the equivalent code, which obtains the beginning and the ending iterator from the container, and then iterates over this sequence. erasePosition(t,tids); At this point, the inter...
62,981,632
62,981,755
C++ Linked List Overwriting Previous Data
so I'm working on a project and I can't figure out what my issue is. I'm new to using and learning pointers, so it's probably something obvious I'm just not seeing, but when I run the print method it shows every item in the list with the same value as the last item. I'm not understanding why it's not only adding to the...
You only have one Bid object called bid in the main function. Every time you pass &bid to the Append function, you are passing the address of the same object. So your linked list contains a bunch of pointers that are all pointing to the same memory. One way to fix that would be to allocate new memory within Append, lik...
62,981,634
64,622,981
calling destroy on a coroutine handle causes segfault
I've recently begun experimenting with C++ coroutines using gcc-10. The below code executes exactly the way it was intended to up till main exits, that destructs the task instance causing the _coro.destroy(); statement to segfault. Why does this segfault? #include <iostream> #include <coroutine> class task { public: ...
A few things: It's advised to use suspend_always or to return a coroutine_handle for resumption from final_suspend and then manually .destroy() the handle in the destructor. ~my_task() { if (handle) handle.destroy(); } This is because returning suspend_never can cause the handle to be destructed for you, as Raymon...
62,981,720
62,981,786
Split string into vector
For example, any character different than a b c..x y z or A B C..X Y Z or - needs to be seperated and put in a vector. How can I achieve this ? std::string inputLine; vector<string> inputs; getline(std::cin, inputLine); at this point I got the string from the user input, how can I split it ? For example: hello,sir my ...
This is an simple algorithm Create an empty vector of strings inputs Create an empty string s Iterate over each char c of your input string inputLine If c in 'a' 'b' 'c'..'x' 'y' 'z' or 'A' 'B' 'C'..'X' 'Y' 'Z' or '-' Append c to s Else Append s to inputs (you could also check if s is empty) Clear s Append la...
62,981,928
62,981,974
Segmentation fault when inserting new integer into dynamic array
Getting segmentation fault with my dynamic array when I am trying to insert new integer into it. void function1() { ... string * array1 = new string[array_length]; function2(array1, array_length); ... delete [] array1; } void function2(string *array_frm_function1, int &array_length_frm_function1) {...
Simple enough int new_array_pos; should be int new_array_pos = 0; You should initialise variables before you use them, and you should pay attention to the compiler that warns you when you aren't doing that.
62,982,180
62,982,439
Read the input and print factorial in Qt GUI Application using C++
Using QTCreator, I created the design of a GUI Application. I want to read the input entered by the user from lineEdit and when pushButton is clicked, it should print the factorial of that entered number on the same page. I've read some tutorials but don't understand how to code this using qtc++.
A minimal example is like that: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QWidget> #include <QLineEdit> #include <QPushButton> #include <QHBoxLayout> class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void ...
62,982,423
62,982,541
c++ struct as map key and operator overloading
I am trying to track 2d coordinates in a map or set. The following code results in this error: error C2678: binary '<': no operator found which takes a left-hand operand of type 'const _Ty' (or there is no acceptable conversion) struct Coord_T { uint64_t x, y; inline bool operator==(const Coord_T& o) { return x...
Overload operators as const functions: #include <iostream> #include <map> struct Coord_T { uint64_t x, y; inline bool operator==(const Coord_T& o) const { return x == o.x && y == o.y; } inline bool operator<(const Coord_T& o) const { return x < o.x || (x == o.x && y < o.y); } inline bool operator>(...
62,982,677
62,982,756
Pointers to Class Members into a class with a private constructor
Lets say that I have a class with a private constructor and that class will be used to represent a single object. Lets say that I have some non-static members that I want to access without using the scope resolution operator. I've noticed that I can achieve this by creating a pointer to the class type to do so. I was w...
When you declare a pointer of some type, that type doesn't have to be constructible. In fact, that type doesn't even have to be complete. So, this line: OnlyOne* two = nullptr; is perfectly fine. Note that this line: two->Location(); invokes undefined behavior, since there is no object pointed at by two, and so there...
62,982,749
62,982,844
Is it possible to update a makefile variable from within a target section?
I have my simple Makefile, it's something like this CXX = g++ CXXFLAGS = -std=c++17 ... ... all : $(TARGETS) % : src/%.cpp $(SRCFILES) $(CXX) $(CXXFLAGS) $(MACROS) $(INCLUDES) $^ $(LDLIBS) -o $@ I want to add a profile targets that when called adds the -pg option to the CXXFLAGS variable and then calls the all ta...
As you've discovered that syntax cannot work. Recipes are not makefile commands, they are shell scripts and are run in a shell. You should use target-specific variables for this: profile: CXXFLAGS += -pg profile: all I should point out that while this seems useful, it's not always as handy as it could be. If you wan...
62,983,441
62,983,789
Nan When using Bhaskara's formula
I am making a simple program using Bhaskara's formula and I get the titled error; by the way, I am using Dev-C++ Here goes the code: #include<iostream> #include<math.h> using namespace std; int main() { float a, b, c, resultado1 = 0, resultado2 = 0; cout<<"Digite el valor de la variable a: "; cin>>a...
NAN occurs when you try to calculate something invalid like divide by 0 or sqrt() of negative value, so, just check this possibility before calculate. https://godbolt.org/z/1Ks1xd
62,983,612
62,983,843
Including CMake Project Libraries
I'm in the process of putting together a small c++ project using CMake for the first time. My current project structure is ├── bch │ ├── CMakeLists.txt │ ├── gf │ │ ├── CMakeLists.txt │ │ ├── include │ │ │ └── gf.h │ │ └── src │ │ └── gf.cpp │ ├── include │ │ └── bch.h │ └── src │ ...
If you want to decouple the project from dependencies, then I would suggest splitting cmake project into two separate, exporting the dependent target and then importing it with 'find_package'. Here is quick google find for that topic: https://visualgdb.com/tutorials/linux/cmake/find_package [edit] For a more general ap...
62,983,799
62,985,746
Arduino / C++ - IF INT value = X Then
i have an INT in my arduino code that i constantly update it's value and i want to check the value and compare it to static values and run IF statments out of it. Something like this INT = 3 If (int = 1) { run1() } If (int = 2) { run2() } If (int = 3) { run3() } the above example just overwrites the original INT valu...
In C++ = is the assignment operator. Please use == to compare: int i = 3; if (i == 1) { run1(); } if (i == 2) { run2(); } if (i == 3) { run3(); } Also note the lowercase if and that int is a keyword which you can't use as variable name. You might want to check out The Definitive C++ Book Guide and List - it has some ...
62,983,814
62,984,906
C++: Initialising an object of a parameterized class inside another class
I want to write a C++ program in which an object of a parameterized class A-'a' has to be initialized inside another class B. I should not/can not initialize like 'A a(parameter list);' of class A while declaring the object variable 'a' which is outside the constructor of class B. The necessary parameters to the object...
The feature you are looking for is member initializer list. In your example it would be used like this: class B{ B(string path) : a(path) { } };
62,984,448
62,985,184
is constexpr const Type necessary in template in order for functions to return compile time const values?
looking at the implementation for std::array in c++ i see something i can't quite wrap my head around.. for example, the function that returns the first element in the array is defined as: constexpr const-reference front() const noexcept {.......} where const-reference is defined as const value_type&, so the whole exp...
so the whole expression above evaluates to constexpr const value_type& Not exactly: constexpr, for a function/method, mean that the function/method can be executed (also) compile time, not that the returned value is constexpr. my question is why are they using both constexpr and const on the same line? isn't the con...
62,984,626
62,985,938
How does the double pointers work for a linked list implementation?
The following code works fine: #include <iostream> using namespace std; struct Node{ int data; struct Node *next; Node(int data, Node *next = nullptr){ this->data = data; this->next = next; } }; void push_back(Node **head, int data){ if(*head == nullptr){ *head = new Node(d...
void push_back(Node *head, int data){ if(head == nullptr){ head = new Node(data); } else{ Node *current = head; while(current->next != nullptr){ current = current->next; } current->next = new Node(data); } } you can't change the value of pointer head ...
62,984,662
62,984,787
What do I use for better performance : vector of pairs or 2d array?
What should I use for better performance : vector<pair<string, string>> or string myArray[10][2] (10 is example number, 2 because I need to store 2 strings), or there is some better way I should stick to?
For better performance, you should use the one which is faster. If neither is significantly faster, then you should use the one that is more convenient. You can find out which is faster in your program by measuring. It could be either, depending on how you use them. or there is some better way I should stick to? In s...
62,985,153
62,985,201
Is it better to keep functions in header files or source files
Is it better to keep functions in header files and include them into the main source file, or to keep functions in source files and link them in the main source file? Some libraries keep functions in their separate source files which are declared in a special header file. When you include that header file in your main ...
Header files should not contain any code or data definitions. In header files: Function prototypes Types declarations (typedefs, structs, unions etc) extern objects declarations Macro definitions and as an exception static inline functions definitions. All other code or object definitions should be in the .c source...
62,985,376
62,986,024
How can I create an LRU cache bounded by size in bytes (rather than number of items) in modern C++?
I'm currently using C++17 and I'm looking for a way to implement an LRU cache, but have it be bounded by the size in bytes of the cache contents (e.g. 100MB) rather than the number of items the cache contains. I'm not concerned with a templatized, generic structure; it can be specific to the type. I know how to make a...
The main problem here is there's no "deep" sizeof in C++. You have to keep track of the object size manually by recursively estimating it. This answer has some hints for that. You can use a custom allocator with STL containers to help with the estimation (see this answer for an example). Alternatively you can use an 3r...
62,985,401
62,985,517
For loop doesn't terminate in an int function without a return statement
On an Arduino Uno, for loops behave very strangely when in an int function that doesn't return anything. void setup() { Serial.begin(9600); } void loop() { foo(); Serial.println("Never reached"); } int foo() { for (int i = 0; i < 9; i++) { Serial.println(i); } } This outputs the following...
The C++ language has a notion of undefined behavior. It is possible to write code that does not constitute a program. Once example of undefined behavior is not returning a value from a function declared as int foo(). From the standpoint of an optimizing compiler the function never returns, since it's an impossibility t...
62,985,845
62,985,972
Why does Return Value Optimization not happen if no destructor is defined?
I expected to see copy elision from Named Return Value Optimization (NRVO) from this test program but its output is "Addresses do not match!" so NRVO didn't happen. Why is this? // test.cpp // Compile using: // g++ -Wall -std=c++17 -o test test.cpp #include <string> #include <iostream> void *addr = NULL; class ...
The language rule which allows this in case of returning a prvalue (the second example) is: [class.temporary] When an object of class type X is passed to or returned from a function, if X has at least one eligible copy or move constructor ([special]), each such constructor is trivial, and the destructor of X is either...
62,986,055
62,986,299
Function template: point of instantiation and declaration
I have a question on code from Stroustrup C++ 4th Ed Page 749-750. This code is trying to show point of instantiation binding. Stroustrup says just before this code that "Each use of a template for a given set of template arguments defines a point of instantiation. For a function template, that point (of instantiati...
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS. Is the point of instantiation f(i)? It is a use of a template for a given set of arguments. If not what is it? No, whilst f(i), in this example, refers to the f<int> specialization in a way that requires it to exist, the poi...
62,986,317
62,986,395
Type safety of Boost Qi/X3 parse
Consider this code using Boost Spirit X3 (conceptually same goes for Boost Spirit Qi): string command; string value; x3::parse(command.begin(), command.end(), "float:" >> x3::double_, value); Why is this code not generating any error during compilation? Shouldn't "float:" >> x3::double_ parser have attribute of ...
It's because automatic attribute propagation into a container is very flexible. And std::string is a container. Perhaps if we do the following experiment it makes a bit more sense: Live On Coliru #include <boost/spirit/home/x3.hpp> #include <iostream> namespace x3 = boost::spirit::x3; int main() { //std::string co...
62,986,371
62,986,394
Using #include when initializing a constexpr (string ?)
I came across this piece of code and I don't know how it works--I've never seen include used this way: static constexpr auto VAR_NAME = #include "path/to/file/FileName" ; and the file path/to/file/FileName contains the contents of some string, i.e. R"( contents of string )" Could someone please explain what this...
It's exactly what it says: the contents of the named file are "included" into your source code. This can be done on any line of your source. It just literally pastes the file contents in. So, the resulting code is: static constexpr auto VAR_NAME = R"( contents of string )" ; Presumably it was of use to the original a...
62,986,552
62,991,178
How compile from the Visual Studio Command Prompt?
I'm trying to compile the following sources and the header: 5-book.cpp #include "book.h" int main() try { string isbn = "0-321-99278-4"; Book b {"harry potter","jk rowling",1998,isbn}; } catch(runtime_error& e) { cerr<<"error: "<<e.what()<<'\n'; } book.h #include <std_lib_facilities.h> class Book { ...
This is a bug in your version of Stroustrup's std_lib_facilities.h. Neither get_rand nor seed_randint is marked inline, and since they are defined in a header, their definitions will be embedded in every translation unit that makes use of the header, rather than just once (and not with internal linkage). The version on...
62,986,566
62,986,631
What is the colon in an enum class declaration?
I just found this weird piece of code in the align_val_t definition of Visual Studio 2019's standard library: namespace std { enum class align_val_t : size_t {}; } What does the colon mean? enum class align_val_t : size_t {}; // ^ // this thing
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS. The enum Name : UnderlyingType {} syntax defines an enum that is said to be fixed, with an explicitly specified underlying type. From [dcl.enum]/5: Each enumeration defines a type that is different from all other types. Each ...
62,986,581
62,986,647
what is the point of std::array function?
In the C++ array implementation, an empty method is provided. However as the implementation suggests: constexpr bool empty() const noexcept { return size() == 0; } This only returns true if the size of the array is 0 so what is the point of it? the typical use case for std::array is something like this: std::array<typ...
is there any use case where you would declare a zero length array or get it from somewhere that an empty check would be useful? If you're using a template for the size of the array. for example #include <array> template <std::size_t s> void function(std::array<int, s> const& array) { if (!array.empty()) { ...
62,986,705
62,988,021
How do I select specific characters inside strings?
I'm pretty unfamiliar with string manipulation in C++ and I can't seem to wrap my head around how to select characters in strings. Below is my program so far. Whenever I run it, however, the program crashes and an error showing "Thread 1: EXC_BAD..." shows up (I'm working on Xcode). For some reason, simply using input[...
The reason you are getting the error is: currentChar = input[y]; The problem with this line is that input[y] might be inaccessible, for instance your input is "Hello". With the way you wrote your code, y would eventually equals 5. However, you the last letter 'o' is input[4]. Because of that, when y=5, you get an erro...
62,986,753
62,986,818
Returning make_shared<Base>, inheritence and casting to Derived not working as expected?
Consider this example constructing shared_ptr<T> in various ways and returning: #include <memory> #include <iostream> class Base { public: virtual ~Base() {} Base(int y) : y_(y) {} int y_; }; class Derived : public Base { public: Derived(int y, int z) : Base(y), z_(z) {} int z_; }; std::shared_pt...
I'm not familiar with what make_shared<T> gives It creates a T (on the heap, wrapping it in a shared_ptr). It creates exactly and only T. Your make_shared<Base> calls are equivalent to new Base(Derived(1, 2). This will construct a Base (by copying from the given Derived's Base subobject, commonly called "slicing", si...
62,986,840
62,986,998
c++ lambda can't convert to int
I attempting to use a nested lambda as follows: int main() { auto x=[](int a){ return [a](int b){ return a+b; }; }; int xx = x(1)(2); (void)xx; return 0; } However, the vs2013 compiler yields an error (C++11 language level): [...] can't convert to int. What is wr...
Your code snippet is well-formed, and this is a compiler limitation or bug in the MSVC C++ compiler version used in VS2013. Note that VS2013 only claimed partial C++11 support, as per e.g. What's New for Visual C++ in Visual Studio 2013: Improved ISO C/C++ Standards Support Compiler Supports these ISO C++11 language f...
62,987,087
62,987,334
Template Parameter Array
I'm trying to create a class that uses the value of an array as a value/type template parameter. See below template< std::array<bool, M> arr> class gf { ... }; I believe my rationale for doing this is sane. This class implements operator overloading for addition and multiplication. These operations are only well defin...
Purely from a technical aspect, you can(1) pass the address of a constexpr array with static storage duration as a non-type template parameter: #include <array> template<const auto& arr> struct gf { gf& operator+=(const gf& /* rhs */) { // ... return *this; } }; template<const auto& arr> auto ...
62,987,448
62,987,605
BFD Library not found
I'm trying to use libbfd on Ubuntu and I've installed bin utils: Reading state information... Done binutils-dev is already the newest version (2.26.1-1ubuntu1~16.04.8). 0 upgraded, 0 newly installed, 0 to remove and 147 not upgraded. root@server:~/Documents/Exercicios/BinaryLoader# But when I try to compile my progra...
g++ -D_GLIBCXX_USE_CXX11_ABI=0 loader.cc You didn't tell g++ to 'link with libbfd', so in 'link' phase, it couldn't find the functions provided by libbfd. I guess you need g++ -D_GLIBCXX_USE_CXX11_ABI=0 -lbfd loader.cc.
62,987,647
62,987,755
Easy data storage formats for c++ begginners
I'm making a c++ program and need a way to store data for users and things like that. I've tried JSON, but the libraries are very difficult to use, at least for a beginner like me. I am looking for a key-value pair type format. JSON work, if I could find an easier library for that.
If you are looking for storage formats for data, then options are - XML (3rd party libraries available) JSON (3rd party libraries available) INI file (key value pair in text file) CSV format (text file) Object serialization etc Storage mechanisms are - File store (XML, JSON, CSV as plain text file) Database (RDBMS, ...
62,987,782
62,997,943
No member named 'get_mapping_handle' in 'boost::interprocess::basic_managed_shared_memory
I'm trying to compile some boost code but am getting the following error This is a simplified version of the code #include <boost/interprocess/managed_shared_memory.hpp> using namespace boost::interprocess; int main() { managed_shared_memory shmem(create_only, "MySharedMemory", sizeof(TransferData)); mapped...
That's an excellent minimized example. It shows clearly what you're doing wrong. You're using a mapped region on a managed segment. That's not what they're for, or even supported: Also: Once created or opened, a process just has to map the shared memory object in the process' address space. The user can map the whole...
62,988,146
62,989,961
enable_if-like SFINAE expression for std::apply
I would like the ability to disable a function if a callable template argument is not callable via std::apply. Perhaps it would help to explain the problem starting with what works. I have this for the regular function call case: template <class Fn, class... Args> using enable_if_callable = decltype(std::declval<Fn>()(...
There is no need to reinvent the wheel. Just use what @asmmo said: template <class Fn, class ... Args, std::enable_if_t<std::is_invocable_v<Fn, Args...>, int> = 0> void apply_fn(Fn&& fn, const std::tuple<Args...>& t) { std::apply(std::forward<Fn>(fn), t); } template<class Fn, class Tuple> using enable_if_applicabl...
62,988,173
63,005,390
Get the second line of a Text File in C++ Builder
My text file looks like this Fruit Vegetable And I need the function to return Vegetable This is the code I tried to use and get "Vegetable": String getItem() { ifstream stream("data.txt"); stream.ignore ( 1, '\n' ); std::string line; std::getline(stream,line); std::string word; return word.c_str(); } Then I did...
The 1st parameter of istream::ignore() is expressed in characters, not lines. So, when you call stream.ignore(1, '\n'), you are ignoring only 1 character (ie, the F of Fruit), not 1 line. To ignore a whole line, you need to pass in std::numeric_limits<streamsize>::max() instead of 1. That tells ignore() to ignore all...
62,988,291
62,997,225
which is the full-expression when the rule says the full-expression of initialization
struct S { constexpr S(int i): I(i),D(i) { } // full-expressions are initialization of I and initialization of D private: int I; int D; }; int main(){ constexpr S s1 = 1; //full-expression comprises call of S​::​S(int) } According to the definition of full-expression: A full-expression is an unevalu...
Of course full-expressions can be dynamically nested: consider void f(int i) { ++i; // (useless) full-expression } void g() { f(1); // full-expression } As such, there’s no conflict between initializing s1 being part of the init-declarator full-expression while also containing full-expressions for its mem-initi...
62,988,497
62,988,550
C++ reinterpret_cast core in Linux, but run succsee in MAC
In some case,I want malloc a block memory, example: first part of memory will contains strings, second part memory will contains long type data. so, i try the demo code below. the code below can run success in MAC, but core dump in Linux. valgrind res: valgrind result screenshot where: line 7 is: str[0] = key.data(); ...
Please read a good C++ programming book, then see this C++ reference and the documentation of your C++ compiler (perhaps GCC) and debugger (e.g. GDB). You are right in using valgrind, but of course you should read its documentation (and also consider using address sanitizers, and be aware of ASLR). My recommendation is...
62,988,527
62,988,594
Simple C++ smart buffer that contains `unique_ptr`
I designed this smart buffer. I'd use std::vector but I don't want to copy things, I want to use a ready buffer and I want it to be self deleted when Buffer gets deleted. struct Buffer { public: std::unique_ptr<uint8_t *> data; size_t len = 0; Buffer(CBuffer cBuffer) { ...
Use std::vector as it clears memory by itself upon scope end. Use smart pointers, when standard containers are not possible. Specific to your problem. The smart pointer has to be declared without *: std::unique_ptr<X> (not X*)
62,988,928
62,989,060
Converting pointer of class A to class B in function return, when B has constructor with `A*`
In C++, can we return a pointer of A from a function whose actual return value is a different struct B which indeed has the first object as the pointer of A? Consider the following scenario. struct B { A* ptr; // code... B(A* _ptr) { // code... } }; B foo() { A* tmp; // code... ...
Let's test it! #include <iostream> struct A; struct B { B(A* _ptr) { std::cout << "I've been called!" << std::endl; } }; B foo() { A* tmp; return tmp; } int main() { foo(); return 0; } The output of such simple program is: I've been called! Meaning that constructor has been ca...
62,989,176
62,989,228
How can I store sum of array in this condition
problem is in inner for loop for (int i=0, j=0; i<n; i++, j++){ if (i != j){ cout << sum = sum + arr[j] <<endl; *//error: overloaded function type* } } cout << sum = sum + arr[j] <<endl;
This is a problem with operator precedence. It can be resolved by putting the expression in parentheses: cout << (sum = sum + arr[j]) << endl; However, this is pretty horrible style, and you should split it into two lines instead: sum += arr[j]; cout << sum << endl; Your future self, and anyone else who reads your co...
62,989,619
62,989,699
c++ error: invalid types ‘int[int]’ for array subscript for single dimensional array
I am trying to write a program to find prefix sum. It is showing error: invalid types 'int[int] for array subscript for single dimensional array code1 #include <bits/stdc++.h> using namespace std; long long a[(int)1e5 + 50]; int n; void buildPrefixSum() { // O(n) for(int i = 1; i < n; i++) { a[i] += a[i - 1...
In you first code block, your long long array a is being "shadowed" (hidden) by the a in the line: int t,a,b; You'll find the problem boils down to this: int main() { int a; a[0] = 7; // error: invalid types 'int[int]' for array subscript } In your second code block, the declaration of the non-array a doesn't...
62,989,763
62,989,897
cin is not taking in the last input in a while loop
In the following code segment, the cin inside the while loop, which is nested inside the while loop in the main function, is somehow not working during the last input (i.e, when h == n-1) and reporting a segmentation fault instead. I figured this out by using the print statements (which are commented in the code below)...
The error is here for(auto it : leaf[node]){ if(temp == 0) break; leaf[node].erase(it); auto j = find(adj[node].begin(), adj[node].end(), it); adj[node].erase(j); temp --; } By modifying the unordered_set leaf[node].erase(it); you are invalidating the implicit iterator used by the range based for l...
62,989,989
62,990,733
Change title color of QGroupBox only on parent
I have 2 QGroupBoxes and one of them is a child of the other. I want to change the color of the parent's title without changing the color on the child. I tried the following according to qt documentation: https://doc.qt.io/qt-5/stylesheet-examples.html My code: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #...
The QSS slightly differs from CSS. Qt just do not know what is r1 in your case. To achieve your desired effect you can: setObjectName() on the object you want to customize and then refer via this name. Therefore only that one element will have distinct color. r1 = new QGroupBox("test",this); r1->setGeometry(10,10,100...
62,990,646
62,991,522
C++: How to correctly actualize a file against power loss?
I have a linux embedded environment. Here I have 2 scenarios: A: Open and write a temporary file. Rename temporary file to the original file. Power loss Result: After reboot, what I have is: 0-size original file and there is no temporary file. B: Open and write a temporary file. FSYNC temporary file. Rename temp...
Normaly, if you want to be immune to a power loss, you use journaling. That means that (broadly speaking) you store what you want to write and where, you write it, and when it as successfully be written, you remove it (at least logically) from the journal. In case of major failure (power loss or other system crash), yo...
62,990,833
62,991,087
Is there any regular pattern to figure out where to put ... in templates?
I got confused with the location where the ... should be put when using template parameter packs. For example, in template parameter list, we should use typename ...Ts, while in a parameter list, it becomes Ts...ts. When instantiate a template, it becomes tuple<Ts...> and most confused me is std::forward<Args>(args)......
It follows the thing being repeated. A name that follows is like multiple names. In template<typename... Ts> we are declaring multiple typenames, e.g. template<typename Ts0, typename Ts1, typename Ts2>. In void foo(Ts... ts), we are declaring multiple parameters, using the multiple types, e.g. void foo(Ts0 ts0, Ts1 ts1...
62,991,118
63,116,195
How can I estimate the first derivative of an evaluated univariate function in C++?
I have a two vectors: Coordinates along an axis, x; An evaluation of a function on those coordinates, f(x). and I want to compute an estimate of the first derivative of f at these coordinates. The function is a descriptor of a wavefunction and x is the dihedral angle. Because the result vector must have the same leng...
I'd start with pchip. Example: #include <boost/math/interpolators/pchip.hpp> // ... using boost::math::interpolators::pchip; auto f = pchip(std::move(x), std::move(y)); double t = 3.2; std::cout << "f(" << t << " = " << f(t) << ", f'(" << t << ") = " << f.prime(t) << "\n"; If you don't like the "character" of pchip, t...