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
61,746,322
61,768,432
TCP/IP server code stopped working after including additional library
I'm a beginner with computer-vision and networking. I have made a program to detect and localise small marbles and that gives me the X,Y,Z position of the marble. I have also made a small TCP/IP server application to send this X,Y,Z position to a robot. I now want to combine these two different applications into one ap...
I think you can improve your code and solve the problem by doing these things: Since you are using C++, it is much better to construct the program into several class, which means several modules, and use them to realise complex jobs. It is not wise to use using namespace std, we will use std library only when need, su...
61,747,138
61,750,309
When importing, QtQuick.Controls 1.4 does not apply Material Style
In the QML application I need a Calendar. It is located in QtQuick.Controls 1.4. But as soon as I import QtQuick.Controls 1.4 Material Style ceases to work. How do I use Calendar, but not lose Material Style? #include <QQuickStyle> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQuickStyle:...
QtQuickControls 1.x and 2.x can have Components with the same name which causes them to overlap (depending on what was imported first). When importing QQuick 1.x stuff, I suggest defining a custom name in the import statement. Here is a working example for calendar: import QtQuick 2.12 import QtQuick.Controls 2.12 impo...
61,747,198
61,813,604
How to force Qt repaint QOpenglWidget in paintGL() immediately?
I want to draw in QOpenGLWidget, processing data and call repaint() in mousePressEvent() function: QPoint point[2]; QImage img=QImage(1000,800,QImage::Format_Grayscale8); void Widget::mousePressEvent(QMouseEvent *event) { point[0]=event->pos(); point[1]=point[0]+QPoint(10,10); repaint(); } Now repaint widg...
Finally,I place the Qpainter in mouseMove() function to draw on QImage. Then when I begin to draw on image, mouseMove() will draw on image immediately, every action will be responded, then paint the image on widget ,paint actions will no longer be ignored by qt. The problem get solved. But I still don't get the answer ...
61,747,302
61,747,522
What is explanation for this FOR-IF loop?
I am writing a code for GCD in C++ but I am encountering a mysterious error that I can't seem to think of its probable reason. In the below program if both the numbers are equal to i ... it will break and return the value of i. But it doesn't seems to work because it outputs the result as 1. int gcd2(int a, int b) { ...
The variable hfc is not the cause for the difference you notice. If we keep the difference but introduce a hfc in both versions we have: int hfc = 0; for (i = 1; i <= b; ++i) { if (some_condition(i)) { hfc = i; break; // breaks out of the loop } } return hfc; vs int hfc = 0; f...
61,747,660
61,747,711
How does sizeof() behaves in C++11?
The sizeof() function in c++ is behaving very weird. I am unable to make any sense out of it. I was writing code to implement the binary search algorithm to find an element in an array. To have a lesser number of arguments in the function, I decided to get the length of the array using sizeof() function. Here is the co...
That doesn't work as you're getting the sizeof of a pointer. Refactoring the code to use a template is one solution: #include <iostream> using namespace std; template<std::size_t N> int binarySearch(int (&arr)[N], int target) { int low = 0; int high = sizeof(arr) / sizeof(arr[0]) - 1; cout << "high is: "...
61,748,064
61,748,412
"fpclassify': ambiguous call to overloaded function
I have a very similar problem to this one: How to resolve "fpclassify': ambiguous call to overloaded function I have a large project with about 100 cpp-files and 100 header-files that work fine in Codeblocks using GNU GCC compiler, but I want to migrate the project to VS19. It seems to work fine except for one error: "...
The error message like fpclassify': ambiguous call to overloaded function is always accompanied by notes. For example, for a simple program #include <cmath> int main() { std::isnan(5); } VS complains: corecrt_math.h(415): error C2668: 'fpclassify': ambiguous call to overloaded function corecrt_math.h(300): note: c...
61,748,191
61,749,457
C++: disable implicit conversion warnings
I'm using MSVC, but it would be a plus to mention the right flags for the other major compilers. I need the flags just for experimental purposes. These are some examples of the warnings I'm referring to: warning C4244: '=': conversion from 'T' to 'int', possible loss of data warning C4244: '=': conversion from 'double'...
If you want to silence an error you can do that as shown in the official documention. MSVC has warning levels, and each warning is assigned to a level. So you either change the level what should be reported, assign a certain warning to a different level, or silence a specific waring. /wdnnnn would silence an error nnn...
61,748,256
61,753,118
What happened when constructing a variable of std::chrono::milliseconds from "LLONG_MAX seconds"?
When constructing a variable of std::chrono::milliseconds from "LLONG_MAX seconds", the result t_milli.count() is -1000 auto t_max_seconds = std::chrono::seconds(LLONG_MAX); auto t_milli = std::chrono::milliseconds(t_max_seconds); As far as I can see, somehow "-1" came from "LLONG_MAX", and "1000" was the ratio. (for ...
You are getting signed overflow in the conversion from seconds to milliseconds. On your machine both seconds and milliseconds are represented by signed 64 bit integers. But to convert seconds to milliseconds, the library multiplies by 1000. You are effectively doing this: cout << LLONG_MAX*1000 << '\n'; which on my m...
61,748,415
61,748,487
Using std::accumulate to find sum of array
Here's my array: std::array<int, 4> mark; Here's a function I have: float getAverage() { float sum = 0; sum = std::accumulate(mark, mark + mark.size(), 0); return sum /= mark.size(); } But I get following error: Invalid operands to binary expression ('std::array<int, markAmount>' and 'std:...
Unlike the built-in C-style arrays, std::array does not automatically decay to a pointer to its first element. Use std::begin and std::end to get the iterators (raw pointers in this case): std::accumulate(std::begin(mark), std::end(mark), 0); or member functions .begin() and .end().
61,748,787
61,749,038
Create a vector in C++ with constant values
I want to create a vector by determining the size and the constant value which the vector has, e.g. a vector of the size 5 and only 3 as values. vector = {3, 3, 3, 3, 3} I only know how to create a vector with zero as value with std::vector<int> vec(5);
You can use a constructor that accepts a count and a value. std::vector<int> v (5,3); Will result in having a vector of a size 5 and 3 as a values {3,3,3,3,3}.
61,748,804
61,765,258
how to write double array in a user-defined structure by c and pass to python with ctype
My goal is C writing to the structure members, and pass the structure pointer back to python. The structure consists 2 same size double arrays(which stand for real part and imag part data,) # of row in the array, # of col. Since it is row major in Python, I could pass 2d array by type POINTER(double), and given row&col...
Lots of problems here. First, txData_pointer.from_address(addressof(rec_data)) is wrong. That's basically the C equivalent of *(tx_data **)&rec_data, which is obviously wrong since rec_data isn't a pointer. If you want to be complicated for no reason, then do tx_data.from_address(addressof(rec_data)) instead, but if yo...
61,748,909
61,749,133
Why can't std::variant find operator<() when not in same namespace as compared classes
I was trying to provide a custom operator< for a class from an external library. This class is within that library's namespace, however, the operator I wanted to define is not. Now if I define a std::variant and want to use it in a std::set, the compilation fails as it can't detect the operator<. Here's an example (god...
This is an feature of argument dependent lookup (ADL), which you are relying on when the operator is search for from std::variant. When searching for free functions, including overloaded operators, the compiler will only search in namespaces related to the arguments to the function in question. There are more details i...
61,749,330
61,749,661
How to iterate through a vector that is part of a struct?
I have the following two structs that I use to define a line: struct Point{ double x; double y; }; struct Line { unsigned int n_points; std::vector<Point> points; }; I would like to iterate through the points vector after adding some data. I tried int main(){ Line line; // add some data to poi...
There is syntax error in your code. Assuming you defined the type of iter before or you can use: auto iter = line.points.begin(); Here, iter is a type of an iterator. A . operator won't work & you need to use -> operator just like pointers as follows: auto iter = line.points.begin(); for(; iter != line.points.end(...
61,749,658
61,752,389
what will be the time complexity (in bigO notation)?
I am not able to calculate the time complexity of this program. `const int n=1e6+5; int prime[n]; void pre() { prime[1]=1; for(int i=2;i<n;i++) { if(!prime[i]) { for(int j=2;i*j<n;j++) { prime[i*j]=1; } } } }` can you te...
The inner loop iterates a number of times proportional to n/i for each iteration of the outer loop. So, the total number of iterations is something like n/2 + n/3 + … + n/n. We can factor out the n to get n * (1/2 + 1/3 + … + 1/n). We recognize the thing in parentheses is basically the harmonic series up to term n and ...
61,750,272
61,750,604
How to Lambda thread body
I have a class that currently uses a class method as the thread body: class Something { public: bool isRunning() { return m_run; } private: void threadBody(void); std::unique_ptr<std::thread> m_thread; std::atomic<bool> m_run; }; There is a lot more to the class than j...
You don't need the parameter - you're capturing this and since the lambda is defined in the scope of the class you have the normal accessibility inside a member definition: [this]() { while (m_run) { // ... } }
61,751,052
61,857,771
Properly remove subtree from QAbstractItemModel
It's not clear for me what is the proper way to remove a branch from a custom model class derived from QAbstractItemModel. I have a method that should refresh a tree node (remove all subbranches and insert the new ones). void SessionTreeModel::refresh(const QModelIndex &index, const DbObjectI *object) { auto item =...
First of all, I would like to say thanks to Scheff for his comment. I'm glad I didn't have to go in this direction ;) After hours spent digging into my code, I finally found the issue. A stupid one indeed! In the parent() method the index is created using parentItem->childCount() instead of parentItem->row().
61,751,197
61,751,347
Trying to print out the value of *ptr++, to understand how it works
I am trying to understand the usage of *ptr++. Below is the code I have used (Scenario 1) #include<iostream> int main() { int a[5]; a[0] = 3; a[1] = 2; a[2] = 4; a[3] = 7; a[4] = 9; int* ptr; ptr = &a[0]; std::cout << *ptr << " "; std::cout << *ptr++ ; } I have read that th...
Precedence means that *ptr++ is interpreted as *(ptr++) instead of (*ptr)++. What surprised you is the unusual meaning of (ptr++). That meaning is "increment ptr, but first use the old value". So *(ptr++) dereferences the old value of ptr. The statement *ptr++; ignores the value you got by dereferencing ptr++, but sti...
61,751,509
61,751,811
Ambiguous Call - Templated Function
I've been trying to brush up on my C++ knowledge and found this issue I cannot Google for easily. I've written a function with the following signature: template <typename Iterator> Iterator lower_bound( Iterator left, Iterator right, typename Iterator::value_type const& target ) { //stuff happens here }...
Here, std::lower_bound is causing the ambiguity. Due to Argument-dependent lookup your function as well as the std version are around. If you use your own (non-std) iterator type, then you would not face any problem. See the example below (live demo): #include <vector> #include <iostream> template <class T> struct myI...
61,751,542
61,752,626
C++ - Checking if a word is palindrome in struct data type
I want to know how to check if a word is palindrome in struct data type or object whatever you want to call it. I want to read a data from file then I need to check if that type of word that I have read is a palindrome or not. Also i need to reverse order of the words but I did that so do not need any help about that. ...
As already pointed out in the comments, for (int i = 0; i < j; i++,j--) loops though things and the letters of their names simultaneously. You also have to account for cases where you compare a lower and an upper case letter such as the 'K' and 'k' at the beginning and end of 'Kayak'. You can use std::tolower for this....
61,751,671
61,751,775
(This function is to calculate SMA). Exception thrown at 0x00509159 in FA.exe: 0xC0000005: Access violation reading location 0x0040400C
I'm trying to calculate a list of closing price for SMA. My program was supposed to be calculating like this. And the value of first day of 5-day SMA will be stored in array with index (time_frame-1). Daily Closing Prices: 1.4660, 1.4627, 1.4600, 1.4607, 1.4609, 1.4691, 1.4687 First day of 5-day SMA: (1.4660 + 1.4627 +...
Think about this for (int i = 0; i < i + time_frame; i++) when is that loop ever going to ever stop? I guess you meant this for (int i = 0; i < time_frame; i++)
61,751,978
61,770,341
How to read all the data in socket programming (c++)?
I am learning socket programming in C++. I have initialised by buffer value at 10. I have used select() function to monitor the socket. When the client sends data which is greater than my buffer can accommodate, it will read buffer size worth of data and will again go through the all my clients and read the remaining d...
Just to complete my comment - this code snippet may help to understand not tested code for (i = 0;i < max_clients; i++) { sd = clients_list[i]; if (FD_ISSET(sd,&temp)) { char buf[10]; int n; int flag; do { n = recv(sd, buf, sizeof(buf),0); if (n > 0) { ...
61,752,531
61,753,794
Why don't files open when I add MPI?
When my program works without MPI, then everything is fine with opening files, but when I add MPI, the files do not open. Why is that? My code: void fileEntry(string path, int n) { ofstream fout; fout.open(path); if (!fout.is_open()) { cout << "File open error"; } else { for(int i ...
I didn't have enough reputation to comment, so posting here. According to you comments, errno 13 stands for 'permission denied' and errno 2 - 'No such file or directory' First i would suggest to try use full filepath, and then try to provide right permission to the file or directory.
61,752,636
61,753,435
C++ Memory Allocator
I'm trying to figure out how I could make a linked list which links to a single byte array. So each element I put into the byte array could be enqued() and dequeued(). However, I need to figure out how to do this using pointer offsets and linked lists. My question is: How do I get an offset of a set amount from the st...
It sounds like what you really want is pointer arithmetic. It's simple enough. std::int32_t foo[] = {42, 350}; std::int32_t* intPtr = &foo; // We'll say foo is at address 0x005 ++intPtr; // Or intPtr += 1, either way the value of intPtr is now 0x009 // *intPtr would now give you 350. // Your pr...
61,753,002
61,833,029
Invisible BLE device when Qt scanning
I'm new on Bluetooth Low Energy (BLE) device development and I have to develop an HMI (on Windows 10) which is able to communicate with the BLE device. For this purpose, I choose to develop my SW with Qt v5.14.2 which includes API for Bluetooth communication. I'm in the first step, which is scanning devices around me. ...
Problem resolved! I just change my compiler from minGW to MSVC and it works fine. The precise reason is still unknown for me, but the solution is here.
61,753,247
61,753,548
Data packages access practices
I am working with a file package and to perform different actions with it I would like to read different values from the file header. To access this information, my instructor told me make a array of type char and than access whatever data I need by going to the offset position of my data on the package and type castin...
Yes that is common practice. There are a couple of exceptional rules for char that make such usage possible. For example there is (cppreference): Type aliasing Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefine...
61,753,275
61,753,418
int** a = new int*[n](); What does this function do?
int** a = new int*[n](); I can't find any explanation for this code, all I find is explanations for code like int *array = new int[n];. I understand it but I can't completely figure out the code above. What does it mean?
As you (should) know, int *a = new int[n]; allocates an array of ints with size n. So, in general, T *a = new T[n]; allocates an array of Ts with size n. Now if you substitute T = int *, you'll get int **a = new int*[n];, which allocates an array of int *s (that is, of pointers to int). Adding () on the right zeroes ev...
61,753,426
61,754,144
Is it a good idea to use nested function arrays?
I need a menu. At first I used monstrous if-else cascades, here's what it looked like (don't wonder about weird while(selection > x) loops, it's just a bizarre way to get input): int main() { ... do { std::cout << "\nMENU\n"; std::cout << "The container is " << (list.empty() ? "empty.\n" : "not ...
Add a couple of meaningful names using MenuFunction = std::function<void(std::vector<std::string>)>; template<int Items> using Menu = std::array<MenuFunction, Items>; and you get Menu<2> ChoiceMain = {Edit, Func}; Menu<4> ChoiceEdit1 = {Print, AddFromFile, AddFromConsole, Empty}; Menu<2> ChoicePrint11 = {PrintConsole,...
61,753,871
61,753,984
Partial template specialization using STL
I have a function which has template class object as parameter. Its working fine with user defined template class object as paramerter but its giving arror with std::array object. If I am trying to execute this program #include<iostream> #include<array> template<typename T1, int size> void print(std::array<T1, size> &...
Because the 2nd template parameter's type of std::array is std::size_t, but not int; they don't match and cause template argument deduction on the non-type template parameter fails. (emphasis mine) If a non-type template parameter is used in the parameter list, and the corresponding template argument is deduced, the t...
61,754,269
61,754,496
How to properly link to libraries in CMake (using Boehm GC)?
I've been trying to figure this out for a while, but can't seem to get it working. I've already checked a bunch of posts. I have a static library libRuntime.a, generated like so: cmake_minimum_required(VERSION 3.15) project(Runtime) set(CMAKE_CXX_STANDARD 17) add_library(Runtime library.cpp) find_library(GC gc) messa...
Because you use a separate CMake invocation to create the executable, the properties of the Runtime CMake target from your first project are not known. Specifically, CMake will not know any of the Runtime library's dependencies (i.e. GC), so you have to list them explicitly when linking Runtime to your executable: cmak...
61,754,527
61,755,638
Why Printing "OK" changes output?
Please have a look at this code #include<iostream> #include <string.h> using namespace std; int main() { char ami[100000], tumi[100000]; scanf("%s ", ami); scanf("%s ", tumi); //************ This is the Problem*********** cout << "OK" << endl; //******************************************* int l1 = ...
There were some cases of out of bounds errors. I removed the C strings, C arrays and non-standard features and added some bound checks and moved one bound check. Now your code outputs NO NO and I didn't find any undefined behavior: #include <array> #include <iostream> #include <vector> int main() { std::string ami, ...
61,754,544
61,755,079
Windows std::fstream modify file after open()?
I'm a bit confused about this working on Windows with standard c++ lib. Having this code: std::fstream _fs; _fs.open('file.txt', std::fstream::in | std::fstream::out | std::ios_base::ate); and file.txt: abcdefg SUB Being 'SUB' hex value 0x1A After the open(), without any write() or close(), I found that file.txt is m...
This happens because MS-DOS used that character as an end-of-stream marker, and Windows has some special handling for it in text mode. The Windows documentation for fopen (which using fstream eventually boils down to) says In text mode, CTRL+Z is interpreted as an EOF character on input. In files that are opened for...
61,755,148
61,755,246
how to know which statement got executed while debugging
In my code, sometimes when multiple function calls can be made in a single line. I do not get which function is running right now. for example- int foo(){ if(m==0||n==0) return 0; return std::max(foo(a,b,m-1,n),foo(a,b,m,n-1)); } While debugging, understanding which function was called based on all parameters...
When you are having difficulty debugging code, it usually means you are doing too much in a single line. This means you should split a complex statement into multiple statements. In your case, something like this: int foo(){ if(m==0||n==0) return 0; auto a = foo(a,b,m-1,n); auto b = foo(a,b,m,n-1); retu...
61,755,276
61,761,342
Warning in C++17 when including XPM image
I'm working on a C++ project that compiled with the std=c++17 and -Wall flags. I'm generally required to clear warnings. I've tried including an xpm image produced with an online tool from a png file, and got the following warning: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] The w...
The tool you used to create the XPM file likely only considered the C language (or pre-standard C++) where lack of const is not an error. In C++, however, a string literal is const and the language enforce that. You cannot change the thing, so a char* to it makes no sense and should be a const char*. The easiest solut...
61,755,506
62,005,895
How to dynamically add widget inside a QStackedWidget
In order to replicate the problem I have I prepared a small verifiable example. I have 2 QStackedWidgets inside a QGroupBox with a couple more components as shown below: I created another widget called QBoxForm which carries a QComboBox only. This last widget should appear on the QStackedWidget on the left as soon as...
You should add ui->stackedWidget->setCurrentIndex(0) after ui->stackedWidget->insertWidget(0, mCombo) to make it visible.
61,755,832
61,760,101
How to change a Ackermann function to void return type in C++
Having the following code, int Ack(int m, int n) { if (m==0) return n+1; else if (n==0) return Ack(m-1,1); else return Ack(m-1,Ack(m,n-1)); } int main() { int k = Ack( 2, 2 ); cout << k << endl; return 0; } How can I change the return type of Ack() from int to void so that res...
The posted function works as expected for small values of the parameters, like the Ack( 2, 2 ); in the example, which returns 7. The problem is the very nature of the Ackerman function itself (or the two-argument Ackermann–Péter function, which seems to be the one used here). I won't pretend to know the theory behind, ...
61,756,138
61,777,899
Websocket client in C++ using boost::Beast - throwing error at write operation
Below is a piece of code which I am trying hard to make it successful. I use the reference code available at git hub https://www.boost.org/doc/libs/1_70_0/libs/beast/doc/html/beast/quick_start/websocket_client.html. The problem is when I call the connect method and do write operation in same function it works, however ...
std::make_shared<CWebSocket_Sync>(ioc)->connect(host, port); std::make_shared<CWebSocket_Sync>(ioc)->ServerCommand(loginCmd); std::make_shared<CWebSocket_Sync>(ioc)->CloseConnection(); Each line creates a new client (make_shared<CWebSocket_Sync>) and runs a single step on it. What you probably wanted: auto client = st...
61,756,284
61,756,290
Can't print the right result
I wanted to get the program to calculate the cube of a number by using a pointer. Here's my code, what is wrong with it? the expected out put should be 5 and 125, while i get 5 and a random number using namespace std; int cubeByreference(int *); int main() { int number = 5; cout<<"The original value of number...
You need to return the value from the function: int cubeByreference(int *nPtr) { *nPtr = *nPtr * *nPtr * *nPtr; return *nPtr; } Otherwise, you invoke undefined behavior. (number will have some undetermined value if you don't return, which could be the cause of the random output). Note that this could just be a...
61,756,554
61,756,705
Understanding cout formating in c++
I have been writing in c++ for a while now. When i was working on a project i encountered a solution that might help me but i don't understand how it works. Maybe someone could help me wrap my head around what is going on. for (int i = 1; i < length_of_board - 1; i++) { cout << i; for (int j = 1; j < length_of_boar...
Ternary operator works like query ? if_true : if_false; In your case this expression is expanded like if((i>9)&&(j<2)) cout<<" "; else cout<<" "; if(boardArray[i][j]=='8') cout<<'.'; else cout<<boardArray[i][j]; Or for easier reading; if((i>9)&&(j<2)) { cout<<" "; } else { cout<<" "; } if(boardArray[i][j]==...
61,756,831
61,758,257
External function returning segmentation fault 11 when called on main(). (C++)
I am trying to make a program that uses the <ctime> library to give the option to show the year/month/day/hour/minutes/seconds. The problem is that after entering option on main() the program says Segmentation fault: 11. What a I doing wrong?. time.cpp: int time(int x) { time_t now = time(0); tm *ltm = localt...
int time(int x) { time_t now = time(0); The first thing your time function does is call itself. This will eventually overflow the stack. Also, don't call main and don't put a break after a return.
61,756,861
61,756,963
How do I read a file in C++ and write contents into a string?
I am writing a method which requires reading a file and putting all its contents into a string variable. This is what I have tried: unsigned int ShaderHandler::CompileShader(unsigned int shaderType, const std::string& sourceFilename) { std::string sourceCode; std::string line; std::ifstream shaderFile;...
Don't use << to append something in a string. Rather than: while (getline(shaderFile, line)) { sourceCode << line; } Consider: while (getline(shaderFile, line)) { sourceCode += line; }
61,756,885
61,759,428
C++ load constructor from variable name
I have a school project in which there is a world simulation. Teacher wants me to do save/load system and I've encountered a problem. My data is saved in a format name x y so saving works fine. Problem starts when I want to load data. This is my solution: switch(name) { case "Human": new Human(x,y); break; case...
You can create your own lookup table of creator functions to handle this, for example: class Organism { public: virtual ~Organism() {} }; class Human : public Organism { ... }; class Dog : public Organism { ... }; ... using OrganismPtr = std::unique_ptr<Organism>; using CreateFunc = OrganismPtr(*)(int, int); st...
61,757,123
61,757,227
Why std::move don't change source variable to default value in default move constructor?
I try to understand the move constructor. I allocate memory in the class' constructor and destroy it in the destructor. When I try to move the class, I still have a double free. #include <algorithm> class TestClass { public: TestClass() {a_ = new int[1];} TestClass(TestClass const& other) = delete; TestClass(Te...
std::move just produces an rvalue (xvalue); it won't perform move operation, it won't modify the argument at all. In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type. Given this->a_ = std::move(other.a_);, as bui...
61,757,127
61,758,437
C++ - Changing single lowercase charachter in a word to uppercase and vice versa using struct data type
As you can see from the title I want to change lowercase charachter in word to uppercase and vice versa. Also I need to use struct object (in my case name). I have a problem when I change charachter from lowercase to uppercase it only changes in the first word not in the second,third and so on. I am also reading words...
Tangential, but it will be an issue, is this line for (int i = 0; i < name.length()-1; i++) This will loop from name[0] to name[name.length() - 2]. The std::string::length returns the number of usable characters. It does not include the null terminator, so you don't need to subtract 1. It should be for (int i = 0; i <...
61,757,153
61,757,729
How can I remove all variables defined by `cmake -D` at once?
How can I remove all variables defined by cmake -D at once? For example, I defined FOO and BAR using: cmake -DFOO=foo -DBAR=bar Errors occur when I run cmake -U* ../, CMake Error: File /Modules/CMakeSystem.cmake.in does not exist. CMake Error at /usr/share/cmake-3.10/Modules/CMakeDetermineSystem.cmake:186 (configure_f...
When using the cmake -D command line option to define cache variables, they are placed in the CMakeCache.txt file, along with all of the other CMake-defined cache variables. To list all of the cached variables, you can run cmake -LAH. The variables prefixed with CMAKE_ are set and used internally by CMake. When you run...
61,757,374
61,757,608
How a program in 16 bit system can access integers more than 65535 but not address
A 16 bit system can only access RAM upto 64kbytes (normally). There is a concept of memory addresses that 16 bit system can access 2^16 numbers thus in unsigned integers it can only access 2^16 = 65536 INTEGERS (0 to 65535). Thus 16 bit sytem can only use addresses upto 64kbytes(after conclusion of small calculation). ...
There are a bunch of misconceptions in this post: I came to know in previous days that a 16 bit system can only access RAM upto 64kbytes This is factually wrong, the 8086 has a external address bus of 20 bits, so it can access 1,048,576 bytes (~1MB). You can read more about the 8086 architecture here: https://en.wiki...
61,757,377
61,758,197
Undefined reference to template operator with definition in same header file
I'm getting linker errors from clang++ when trying to use a templated operator I wrote. The errors are: main.cpp:(.text+0xfe): undefined reference to `operator<<(std::ostream&, schematic<130ul, 128ul, 130ul> const&)' main.cpp:(.text+0x28c): undefined reference to `operator<<(std::ostream&, schematic<130ul, 1ul, 130ul> ...
Your example mostly work, can't reproduce the error you have. Still found something that should be changed. First, you can't declare a friendship on a function that isn't declared yet. You need to put the template operator<< declaration before the class definition. However when you try to do so you realize you need the...
61,757,409
61,757,688
Is calculating address difference undefined behaviour?
Let's say I perform the following: void g(int* x) { int y = 0; auto diff = uintptr_t(&y) - uintptr_t(x); } void f() { int x = 0; g(&x); } Does diff merely have undefined value, or does the code invoke undefined behaviour? According to the specification, is the code guaranteed to run nicely and compute...
To quote the C++11 standard draft. On the subject of converting a pointer to an integer [expr.reinterpret.cast] 5 A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the ...
61,757,466
61,757,667
Why does an ostream iomanip not need template parameters when passed to operator<<?
In namespace std, of the gnu stdc++ header ostream, this is the definition of std::endl: template<typename _CharT, typename _Traits> inline basic_ostream<_CharT, _Traits>& endl(basic_ostream<_CharT, _Traits>& __os) { return flush(__os.put(__os.widen('\n'))); } Why is it possible to write std::cout << std::...
std::basic_ostream<CharT,Traits>::operator<< taking manipulators as function pointer. Template argument deduction is performed when being passed template like std::endl, thus template arguments don't need to be specified explicitly. When possible, the compiler will deduce the missing template arguments from the functi...
61,757,658
61,757,927
Why do we need piecewise_construct in map emplace in C++20?
This it theoretical question about potential overload of std::map emplace function that detects that it has been passed 2 tuples, not a question if this functionality exists in C++20. From what I saw in previous question map emplace is "victim" of std::pair's problems. So that got me wondering why is there no concept...
weirdo classes that take std::tuple as argument to constructor Yes, exactly. If you decided that m.emplace(x, y) automatically did piecewise_construct functionality for tuples x and y, then it would be impossible for me to emplace construct this: struct Key { Key(std::tuple<int, int>); bool operator<(Key const&) cons...
61,757,789
61,874,521
Q3DSurface selected point signal
I am using QtDataVisualization (Q3DSurface in particular) to make a simple 3D surface graph. The Q3DSurface supports selection of a point on the graph by showing a highlighted ball on the data point where the user has clicked. The selection pointer shows the coordinates of the point. It looks like this: surface with s...
The desired signal is itemLabelChanged(const QString &label) in QAbstract3DSeries It is emitted when a label, which represents the chosen point's coordinates, is changed. By connecting this signal to the slot, it is possible to retrieve the label's text (const QString &label parameter).
61,757,853
61,759,157
How to check the type of a variable from a file with ifstream?
I have a stream in a file (which is opened by ifstream) with doubles and some string but I don't know their positions. For example: 1 2 3 4 g 3 2 t 1 d So I have to read a stream as the above one, but I don't know how to differentiate the type of the variable before reading. How can I do that with ifstream and with no...
If you are sure your numbers are integers, use the code below. If not, replace int in vec and temp by double #include <fstream> #include <vector> #include <fstream> int main() { std::vector<int> vec; std::ifstream file {"fileLocation"}; while(file.peek() != EOF) { if (isdigit(file.peek())){ ...
61,757,887
61,757,983
Why does const have to be added to constexpr for a string literal declaration?
This declaration: char constexpr *const s = "hello"; Fails with this error: g++ -g -Wall -Werror -std=c++17 test.cc -o test test.cc:8:31: error: ISO C++11 does not allow conversion from string literal to 'char *const' [-Werror,-Wwritable-strings] char constexpr *const s = "hello"; But if I add const to constexpr, the...
Doesn't constexpr imply const? It does, on the object being declared, in your case s. The result of applying constexpr is the object char *const s; It's still declared to point at a non-const object. Only the address has to be a constant expression. Which means it must be to an object with static storage duration. ...
61,758,329
61,759,129
JPG - how to read / extract data from ICC profile section APP2
I have a JPG file from which I have extracted ICC color profile section (APP2). However, I dont know, how to extract relevant data from it, like white point, black point, RGB settings etc. I wasnt even able to find section description. I have found this: https://exiftool.org/ which provides API, but I cannot use this, ...
The overall format of an APP2 segment containing an ICC profile is described in Appendix B.4 of the ICC spec: The JPEG standard (ISO/IEC 10918-1[2]) supports application specific data segments. These segments may be used for tagging images with ICC profiles. The APP2 marker is used to introduce the ICC profile tag. Gi...
61,758,449
61,758,549
Create an object by paasing to the constructor other object reference
I created in an include.hpp two C++ classes: #include <string> #include <map> #include <iostream> #include <sstream> #include<vector> using namespace std; class A { public: vector<char> v; A(){}; A(A &other) { v = other.v; } ...
You are returning a function local object by reference from createstrbyappend. You should return a copy instead: A createstrbyappend() { //... } This requires you to take the argument to Bs constructor by value as well: template<typename T> B(T t): a(std::move(t)) {} Now, you need to take the argument to A's copy co...
61,758,527
61,758,627
sending pointer from unique_ptr::get into function as pointer reference
Ok so i have a unique pointer and use the unique_ptr::get to get the pointer and pass that into say a std::function that has the params of int*& b. It seems to be returning a error. Im just curious as to what i did wrong and how to fix it. I've put a little code snippet bellow thanks. std::function<void(int*& b)> foo; ...
unique_ptr::get() returns a pointer int*, not a reference to a pointer int*&. This is because you should not be able to change the pointer stored in the unique_ptr from the outside. The returned pointer is a temporary (rvalue) and this cannot be bound to a non-const reference, only to a const reference. In your case as...
61,758,745
61,783,697
Dev c++ mingw no longer compiles
I'm using Dev C++ 4.9.9.2 and my programs stopped compiling since yesterday. My compiler error just looks like this: F:\Program\Makefile.win [Build Error] [Program.exe] Error 1 With the compile log messages being: Compiler: Default compiler Building Makefile: "F:\Program\Makefile.win" Executing make... make.exe -f...
Something with the linker refused to work for me. I installed mingw using TDM-GCC and made a new compiler profile for that, which ended up working. I'm still at a loss for why the included mingw suddenly stopped working and didnt work properly even after reinstalling.
61,759,552
61,759,657
Why some top level competitive programmers use #pragma?
why they use this before#include<bits/stdc++.h> mainly I've been using #include ... Now I'm seeing these lines on a cpp program so I became curious. #pragma optimization_level 3 #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") #...
These are indications to the compiler to change its behaviour as if you had passed the equivalent command line flags. For programming competitions, you often submit source code rather than a binary - it's then built and tested using a system you don't control (and can't set the command line on). Putting these settings ...
61,759,824
61,759,887
Reference to a subarray within an array
I was trying to figure out how can I create sub arrays from within a larger array and got a piece of code here and started using it. I created an array of ints int arr[10]; for(int h=0;h<10;h++) { arr[h]=20+h; } Now say I want a sub-array (of 4 ints) within the same larger array int (&arrOnly4Elements)[4]=(int (&)...
cdecl.org translates it for you: int (&arrrOnly4Elements)[4]: declare arrrOnly4Elements as reference to array 4 of int int &arrrOnly4Elements[4]: declare arrrOnly4Elements as array 4 of reference to int As NathanOliver pointed out, C++20 introduces std::span. You should take a look at it (also compare this SO question)...
61,759,982
61,762,190
RAM usage wrong when using pointers to class
I don't understand how the RAM usage is estimated by the compiler. I made the following MCVE. After compiling (Arduino nano ATMEGA328P, new bootloader), the RAM usage shown by the Arduino compiler is wrong. I compared creating instances of the DataContainer struct in two ways, by having an array of pointers and call co...
Do not use dynamic allocation on 16 bit MCUs. Especially not on a nano. There's just not enough RAM. Estimating needed RAM space is simple. Calculate the size of your structure. struct DataContainer { int values[100] = {0}; // init to zeros /* ... */ }; 100 x sizeof(int) = 100 x 2 = 200. Calculate the ...
61,760,072
61,760,621
C++ TypeId to a constructor
I am trying to create a function that checks if type of object equal the type of argument, and if it does, create new object. My class hierarchy: class Copier: public Action class CopierX: public Copier So my function is: void Copier::checkequality(Action b) { if (typeid(*this) == typeid(b)) { Action b ...
One way to solve this would be adding Action* copy() method to the Action class and implementing it within every descendant. The other is using static polymorphism like this template<typename T> class Action { public: template<typename U> void checkequality(Action<U>** b) { if(std::is_same<T, U>::value) { *...
61,760,083
61,761,131
Module dependencies when using template function specializations
Please check out the following code snippet (pseudo code, didn't compile it): A.h template <typename T> void SubTest(T t) = delete; template <> void SubTest(int i) { cout << i; } template <typename T> class MyClass { public: void Test(T t) { SubTest(t); } } B.h class X{}; ...
While it’s true that specializations “need to be declared before they are used”, that doesn’t mean before their caller is defined, but before it is instantiated so as to use the specialization in question. This is critical to any customization scheme: you define the base case, then clients #include that and define spe...
61,760,344
61,798,302
QTextEdit ANSI symbol
Thanks for the code, it helped me solve a lot of problems with displaying text. But there is one symbol that haunts me: [2K but it looks like this: enter image description here as far as I understand this symbol in ANSI means - erase the line and write new information in its place. What can I do with it?
This problem with this sign was solved by replacing the text with an empty value. My function where I applied substitution and formatting, the formatting function is listed by the link void MainWindow::getLine(QByteArray output) { QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QString pStr = codec->toUn...
61,760,382
61,761,763
C++: Single instance of a dialog?
I have a dialog box I want to only exist once, as two different classes (MainFrame, which can open it outright, and Wizard, which can open it with settings brought in from the wizard itself) have to access it at any given time. Ideally, I would like the user to be able to open the dialog with the Wizard, with everythi...
Three (immediate) issues with this code: Your Dialog::Dialog(WxWindow*) constructor is public, which sends mixed signals about the nature of your singleton object. While not directly responsible for crashing or hanging, you're exposing your class to improper use that may violate the singleton contract (and thus indire...
61,760,527
61,760,603
Empty constructor and value passing problem
When I create a class A object with a reference to class C, class B gives the error of: Error C2512 'A': no appropriate default constructor available Class A class A { public: C* cPointer; A(C* arg) { cPointer = arg; } }; Class B class B: public A { public: B() { ...
class B: public A { B() { } } When a child class's constructor is called, it first initializes its parent portion by calling a parent constructor. Since you didn't specify one here, the B constructor is trying to call the default A constructor, but one doesn't exist! To call the constructor you made explicitly, yo...
61,760,666
61,760,862
Dynamic Space separated inputs in C++ program
I am trying to solve a problem which has likeness of the coding questions asked in programming-war sites like HackerEarth. Let me give you a background of problem, though it seems to be unrelevant: I am trying to determine how many of muffins can be created with given units of ingredients. The code I have written so fa...
Use a loop and a vector. If first number tells you number of input: size_t n; std::cin >> n; std::vector<int> quantities(n); for (auto& q : quantities) std::cin >> q; No error checking included! That is: Assuming the user enters n valid numbers.
61,760,834
61,761,153
kill() does always return 0 (sucess), even after child process has already ended?
In C++ (running on Linux), want to do something like this to determine if a process is not running bool isnotrunning(pid_t pidnr) { if(pidnr <= 0) return true; if(kill(pidnr,0) == 0) return false; return true; } and then in my main, I do pid_t myPid = -1; while(1) { if(isnotrunning(myPID) { myPid = fo...
Even after the child process exits, it continues to exist (as a so-called "zombie process") until the parent has "reaped" it by calling waitpid(2) or one of its relatives. When it's a zombie, kill(pid, 0) will still return 0 on many systems (including POSIX-compliant systems). So your parent process needs to use waitp...
61,760,929
61,761,274
decomposition of a number in c++
I don't have a code , I'm only asking how to start. Well the user enters the number (as an example the number will be 437).Decomposition units are (50,10,1) like in a banking system.Lets come back to the example 437 , the output will be 50*8(because the result is 400), then 10*3(... 30) and finally the number 7 will be...
Imagine you are a bank teller, and someone is withdrawing a very specific amount of cash. They request 111111 dollars. What is your brain doing in order to tell you to stop giving them cash? Will you give this person infinite money? Will you give him no money? Literally, ask yourself HOW you would break this persons mo...
61,760,992
61,761,984
Why do different compilers produce different sized files?
I recently installed MinGW on Windows 10 with the packages for C and C++. The other day, I decided to compile some C++ using Visual Studio 1029's compiler and g++ to see if there was a difference. There was a major difference in that the file produced by g++ is over four times larger than the file produced by VS19. Her...
You can assume each compiler as a different software to create machine-runnable code from Files containing code which is programmed according to a specific standard, e.g. C++. Each of these compilers have their specific skills/features. A good compiler optimizes the code. This is also the reason why code compiled in de...
61,761,048
61,766,187
C++ Polymorphic Data Structure
After some searching I've yet to find an existing question which address this issue. My apologies if I missed something. I have a base class with a params structure and setter. I would like to redefine what that params structure looks like in a derived class and set it via a base class pointer. Something like the follo...
You can't redefine a type but what you can do is a have a common base class for the parameters. So you could make A::paramsType a base class and derive B::paramsType and C::paramsType from that. Then store a pointer to A::paramsType in class A. That way you can use a common base class for passing in the parameters. How...
61,761,089
61,769,011
Launching *.msi thanks to Windows API
I've have been trying to launch other programs with admin account in C++ with Windows API. It works well for *.exe files but not with *.msi files. I tried using msiexec.exe which works well in PowerShell, but not from cmd and not from my program. Is there a way to fix this? I'm on Windows 10, compiling with MinGW 64bit...
I can reproduce this with the argument L" /i \"path/my_installer.msi\"". The arguments after "/i" option should not contains /. The following path sample work for me. #include <windows.h> #include <iostream> int main() { wchar_t s[] = L" /i \"C:\\Users\\username\\...\\my_installer.msi\""; STARTUPINFOW su_info...
61,761,133
61,768,034
C++ template to accept both const and non-const objects
How can I get the following code to compile? I would like to support all variations of constness for the c-style array and std::array supplied to the constructor. #include <cstddef> #include <array> template <typename T> class Base { public: explicit Base(T* data) : data_(data) {} private: T* data_; }; tem...
I came up with a solution that works because it can be controlled what type that is used to instantiate the base class: #include <cstddef> #include <array> template <typename T> class Base { public: explicit Base(T* data) : data_(data) {} private: T* data_; }; template <typename U, std::size_t S> class A : ...
61,761,204
61,762,949
Is there a better solving algorithm for this Codeforces problem than merely using brute force?
You are given an array a1,a2,…,an. In one operation you can choose two elements ai and aj (i≠j) and decrease each of them by one. You need to check whether it is possible to make all the elements equal to zero or not. The following link https://codeforces.com/contest/1201/problem/B
I think it's enough to check if the sum is even and no element has more than the half of the sum. Using C++17 with parameter pack expansion and fold expressions it's a short snippet: template<typename ...Ts> bool check(Ts... an) { const auto sum = (an + ...); const auto max = std::max({an...}); return sum %...
61,761,238
61,761,630
what does the NOT operator mean in this case?
i've encountered this thing. I don't understand why you can both use cin and i also dont understand what it means. int val; if (!(cin >> val)); I don't understand what the if(!()) stands for and also able to type a character.
what does the ! mean after ... ! is a unary operator. In this case it is the logical NOT operator. If expression implicitly converted to bool results in true, then !expression is false and if expression implicitly converted to bool results in false, then !expression is true.
61,761,241
61,765,305
Get time to press a key in c++
if (a == 1) { cout << "Press a" << endl; Sleep(500); // I tried to do it this way but it didn't work if(GetKeyState('A') & 0x80000){ cout << "Nice" << endl; }} I don't have enough time to press a key, maybe you have any solutions.
@JonathanPotter has pointed out a solution. The following is an example code working for me. You can have a try to see if it helps. GetAsyncKeyState and GetKeyState return SHORT, so compare the return value with 0x8000 instead of 0x80000. DWORD WINAPI MyThreadFunc(LPVOID lpParam) { while (TRUE) { if (G...
61,761,347
61,763,081
Is this backtracking approach for N Queen problem incorrect?
The N Queen problem is behaving inappropriately i.e. it is giving some output (although incorrect) when using long long int but in case of int it is giving the board array with all the elements -1. The code is: #include<iostream> #include<iomanip> #include<cstring> using namespace std; const int d=4; //fil...
Well, first of all, your algorithm can be still much better. If you want to improve your algorithm, look at "Constraint Satisfaction Problems". Also there are places to optimize your code. #include<iostream> #include<iomanip> #include<cstring> using namespace std; const int d=4; //fills 0 to all the positi...
61,761,453
61,761,659
error: use of deleted function ‘std::unique_ptr<...>
I'm new to C++ programming. I was trying to use an external library where i have access to header files an .so libraries. here is my library code class Employee { private: std::unique_ptr<Address> address; ................ ................ ................ public: virtual void updateAddres...
found a solution thanks for taking time to answer my question Solution marked Employee mEmployee; as a reference Employee& mEmployee;
61,761,673
61,762,172
C++ - How can we call a class without calling its attributes?
I need to implement the class Multiplier for a school exercise, but I do not understand how the teacher was able to call prod() without calling its inputs. The goal of the code is to read a sequence of integers until the product of their absolute values is greater than 200. Can somebody help me understanding please? He...
Multiplier prod(100); - Multiplier must have defined a constructor that takes an integer as input, eg: class Multiplier { ... public: Multiplier(int value); ... }; cin >> prod - Multiplier must have overloaded operator>> for input, eg: class Multiplier { ... }; istream& operator>>(istream&, Multiplier&); prod.li...
61,762,309
61,769,629
QProcess fails to execute a terminal line command via QPushButton
I am trying to execute a command line using QProcess as soon as I push a QPushButton on my gui. The problem I have is that the .sh executable file is never executed. The script I am trying to execute is very simple and reported below: #!/bin/bash echo "try one two three" rostopic echo -b LaserScan_PointCloud2_test.bag ...
Try this: header: #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QProcess> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: ...
61,762,436
61,762,516
C++ program speeds up when re-executed
I am currently doing a performance testing of a C++ program. I need to bulk insert to a std::unordered_map or some other similar open source structure. I am inserting 30-40 char strings as key-value pairs and noticed an interesting behaviour. When code is first executed (Clion), it took 20 seconds to complete, I repeat...
The first time you run the code it has to: Wake up the disk if it's spun down or idle Read the data off disk Read the executable off disk Possibly load in some shared libraries as well The second time you run the code it can: Read the data from the OS read-cache in memory Read the executable from the OS read-cache i...
61,762,809
61,762,938
Why restarting program with exec() doesn't work as it should?
My task was to create simple program to restarting itself via command exec(). After each call program should assign string from keyboard to global array(max 20 char) and print content of array before assignment and after it in a hex form. The problem is that in each call my output is ending after scanf(as if program ...
Standard output is buffered, by default. All that printf does is write data into the buffer associated with stdout. Nothing else happens until the buffer is full or a newline character is written into the buffer (if stdout is line-buffered, which it will normally be if it is directed at a terminal. You can use setvbuf ...
61,762,868
61,763,065
Why it's possible to access std::unique_ptr<A>* u1 as u1[1000] and it still works
Sorry for silly title, couldn't think how it should be. I'm playing with unique_ptr, created pointer to unique_ptr (I know I shouldn't create pointer to a unique_ptr, I'm just playing to see what happened) class A { public: A() {std::cout<<"A const\n";} ~A() {std::cout<<"~A dest\n";} void fun() {std::cou...
Technically, u1[1000]->fun(); exhibits undefined behaviour, and as such, "anything can happen". In practical terms, you execute A::fun() with an invalid this pointer, and since A::fun() references no member variables or virtual functions, you get away with it. Which is probably bad news, rather than good, since you ha...
61,763,319
61,763,847
Easy way to create multiple-dimension arrays in C++ with new operator
I need to create a lot of small 2-dimension arrays in C++ code. The problem is that it's a lot of work to create even a simple array: new int* [2]{ new int[2]{9, 9}, new int[2]{25, 19} }; Is there any better way how to do that? I wanted to avoid writing "new int[]..." every time.
If the dimensions are not decided at runtime, and all the inner arrays have the same dimensions, you do not need dynamic allocation here. Just declare an array: int myArray[2][2] = { {9, 9}, {25, 19} }; That's it!
61,763,357
61,763,552
Opposite of std::bind, pass in different functions for given parameters
I have several functions with almost identical signatures (made much shorter than actual code): int hello(A a, B b, C c, int n); int there(A a, B b, C c, int n); int how(A a, B b, C c, int n); int are(A a, B b, C c, int n); ... And so on. Then during invocation, the code creates the parameters once and then passes the...
You can use a Lambda, which made std::bind mostly obsolete, as it is easier to use: auto uber_func = [&](std::function<int(A, B, C, int)> f, int n) { return f(a, b, c, n); }; uber_func(hello, 240); uber_func(there, 33); uber_func(how, 54); uber_func(are, 67); The first solution enforces that all funct...
61,763,545
61,763,726
Adding 1 to an address result in adding 0xE0 to that address
I encountered a really weird behavior while trying to add an offset to an address which I got with the use of & operator. So when I try to add any number to that address, the result is that adddress plus my number times 0xE0 (224). These are screenshots of the watch list in Visual Studio. The first row of each scree...
To understand this, start by compiling and running the following code (C++, though I've included the C lines as comments if you want to use that language): #include <iostream> // #include <stdio.h> int main() { // int main(void) { int xyzzy[2]; int *pXyzzy = &xyzzy[0]; ...
61,764,195
61,764,491
cppyy inherit class that contains a smart pointer
Here is a simple example of inheriting from a class that contains a smart pointer. We don't do anything with it, just declare it. import cppyy cppyy.cppdef(""" class Example { private: std::unique_ptr<double> x; public: Example() {} virtual ~Example() = default; double y = 66.; }; """) c...
As hinted by S.M., if we must use unique_ptr, the trick appears to be to make sure to define a copy constructor, e.g., this example gives the expected results with no error messages, import cppyy cppyy.cppdef(""" class Example { std::unique_ptr<double> x; public: Example() { x = std::unique_ptr<double>(n...
61,764,719
61,764,750
C++ compiler complaining about no default constructor
Given this struct with a private stateful variable: struct Calibrate { private: Stitcher stitcher_obj_; } This is the stitcher object (with empty constructor): Stitcher::Stitcher(const std::vector<cv::Mat> &src_images){} When calling Calibrate, I am getting this error: default constructor of 'Calibrate' is impl...
As soon as you provide a custom constructor for a class, the default constructor (the 0 argument constructor) is no longer synthesized. You need to reinstate it manually, like this: class Stitcher { Stitcher() = default; // ... };
61,764,983
61,764,993
how do I declare a 2d std::array
I want to use a 2d std::array as I've to use bound check at certain point in my program. For 1d array, I would do this: #include <iostream> #include <array> int main (){ std::array<int,4> myarray; for (int i=0; i<10; i++){ myarray.at(i) = i+1; } } How do I do it for a 2d array. Can I make use of auto in...
std::array is 1-dimensional, there is no such thing as a 2-dimensional std::array. You would simply have to use an inner std::array as the element type of an outer std::array, eg: #include <iostream> #include <array> int main(){ std::array<std::array<int,5>,4> myarray; for (int i=0; i<5; i++){ for (int j=0; j...
61,765,410
61,765,561
how do I print a vector of vector of bools
Here's what I tried #include <iostream> #include <vector> using std::vector; using std::cin; using std::cout; using std::endl; const int n{5},s{9},arr[]{2,3,7,8,11}; vector<vector<bool>>dp; void print(){ for(auto &x :dp){ for(bool y:x){ cout<<y<<' '; } cout<<endl; } } int mai...
What is the correct way to do it. Your example program is a correct way. The program crashes It shouldn't. Either you are mistaken, or there is something wrong with your system. ... with nothing being printed. This makes sense. You are printing a vector of vector of bool that is empty. There is nothing to print.
61,765,559
61,807,681
Size of an executable at runtime in C/C++ on Linux without /proc/self/exe?
I need to get the size of a C/C++ executable at runtime in code. Unfortunately I cannot use /proc/self/exe as it's restricted on the target system.
dl_iterate_phdr https://linux.die.net/man/3/dl_iterate_phdr This solved it! Thanks @o11c!
61,765,697
61,765,874
double free or corruption (fasttop) when using erase in vector. How can you erase several items of a vector knowing their indexes?
I am working on a "big" project and I am stuck with a segmentation fault which I finally narrowed to a simpler and reproducible example: I am going to put two pieces of code. First: #include <iostream> #include <string> #include <vector> using namespace std; int main() { std::vector<int> someVector; printf("1...
You are missing the assignment operator for your class. The std::vector requires that your class has correct copy semantics, and your ActionType does not have correct copy semantics. It is simple to add an assignment operator for the class you've written: #include <algorithm> //... class ActionType { //... Actio...
61,765,908
61,765,993
How to initialize a class with a primitive in C++(like std::string initialized from const char*)
What I've been wondering for a while, across many different languages, now in c++, is how do you initialize an object with a primitive? I'm curious about how std::string initializes with a const char* and I want to know if there's a simple way of doing that. Apologies if this question is badly formatted, I've just not ...
If you can write something like that: std::string s = "hello world!"; It's because the constructor of the string class takes a const char * std::string is a std::basic_string<char> For example, if you want to instantiate an object of your custom class with a primitive data type, you have just to define a constructor...
61,765,930
61,766,896
I am trying to count the number of elements currently in a linked list
int OOLList::getListSize() { int count = 0; OOLNode* iterator = NULL; // If the stack is empty return 0 if (this->start != NULL) { count = 0; } // If the Stack isn't empty else { while (iterator->next != NULL) { iterator = iterator->next; count++; ...
The error is because you initialize iterator to NULL and don't set it to anything else before accessing iterator->next. Presumably start is the first node in your list. When start is not NULL (the list is not empty), you return 0. And when start is NULL (the list is empty), you try to iterate. Your logic is backwards...
61,766,092
61,766,229
How should non-member functions be declared and defined in the .h file and cpp file?
I don't really understand the concept of "non member function" in C++. How should non-member functions be declared and defined in the .h file and cpp file. and how to call the non member function in main.cpp since the non member function does not declared inside a class?
non-member function or "free function" is a function that lives outside of a class. To create a function like that you can just declare it outside of the class. .h Class C { int func1(){}; //member function declared and defined in header int func2(); //member function declared in header ... } int func...
61,766,279
61,766,346
How to populate objects of derived class with data members into a pointer array of base class
When i try to output a material of type string of class 'Brakes' using polymorphism, it doesn't print correctly. I believe the problem has to do with me instantiating a new derived object. How do I populate a derived object with data members into an array of pointers of the base class in C++? Sorry if the format for th...
partsList in main is a pointer to an array of Parts. populateArrayBrakes populates an array of Parts * (pointers to parts). Your use of &parts will results in Undefined Behavior because any access in populateArrayBrakes of parts[element] where element is not 0 will be out of bounds. What you want is to declare partsLis...
61,766,367
61,769,678
Is FlatBuffers C++ reinterpret_cast access actually undefined behavior? Is it practically OK to do that?
Recently I try to use FlatBuffers in C++. I found FlatBuffers seems to use a lot of type punning with things like reinterpret_cast in C++. This make me a little uncomfortable because I've learned it's undefined behavior in many cases. e.g. Rect in fbs file: struct Rect { left:int; top:int; right:int; bo...
I didn't analyze the whole FlatBuffers' source code, but I didn't see where these objects are created: I see no new expression, which would create P objects here: template<typename P> P GetStruct(voffset_t field) const { auto field_offset = GetOptionalFieldOffset(field); auto p = const_cast<uint8_t *>(data_ + f...
61,766,422
61,766,493
does negative index necessarily mean undefined behavior
int main(){ vector<vector<int>> a; a.resize(2,vector<int>(2)); int arr[2][2]; cout<<&arr[1][1]<<endl; cout<<&arr[2][-1]<<endl; cout<<&a[1][1]<<endl; cout<<&a[2][-1]; } The output to this program shows that arr[2][-1] and arr[1][1] both correspond to the same address. It is not true for the...
You have Undefined Behavior in two places. When you reference a[2], this is UB because a only has two elements, and a[2] is past the end. (Don't think of a as a 2D vector; think of it as a vector of vectors.) Even if you try to access a[1][-1], this is also UB because indexing is unsigned, the -1 will be converted to a...
61,766,570
61,766,692
About using range based for loop over a vector of vectors
I am working on some graph problem. I have: vector<vector<int>> e that I populate as: for(vector<int> edge: edges) { e[edge[0]].push_back(edge[1]); e[edge[1]].push_back(edge[0]); } Now when I try to access e using a range based for loop like: for(vector<int> v: e[node]) I get an error: no viable conversion...
each element of e is a vector, each element of e[node] is int.
61,766,649
61,766,867
Why does the compiler not perform inlining, if the function contains static variables?
I read from the following website, that the compiler may not perform inlining when the function has static variables. What is the reason? Reference: Inline Functions in C++ Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining. Compiler may not perform inlini...
Compilers can totally inline functions with loops static variables, switch statements, and even recursive functions. Here's an example: #include <iostream> inline int foo(int* a, int n) { int r = 0; static int b; for (int i = 0; i < n; i++) { r += a[i]; } switch (n) { case 42: ...
61,766,800
61,767,247
why wild pointer holds zero address rather than garabge address?
I have been trying to find the size of an particular datatype like "int" without using sizeof() and found this : #include<stdio.h> int main() { int *ptr; /*Declare a pointer*/ printf("Size of ptr = %d\n",ptr); ptr++; printf("Size of ptr = %d\n",ptr); return 0; } This returns correct size for ...
Since ptr is uninitialised, its value is indeterminate and accessing its value gives undefined behaviour. The meaning of "undefined", somewhat ironically, is defined by C and C++ standards to mean something like "this standard doesn't constrain what happens". Beginners often incorrectly assume this means it must conta...
61,766,999
61,767,135
Is there a way to repeat a loop cycle?
Is there a way to repeat a loop cycle like in code example below, without i incrementing by 1? bool twice = true; bool* repeated = new bool[64]; int counter = 0; for (int i = 0; i < 64; i++) { counter++; if (twice && !repeated[i]) { repeated[i] = true; repeat; } } delete[] repeated; cout <...
You could use a lambda function to wrap the interior of your loop and then simply call it twice. bool twice = true; int counter = 0; auto execute_interior = [](const int i){/*Do something with i*/}; for (int i = 0; i < 64; i++) { ++counter; execute_interior(i); if (twice) execute_interior(i); } s...