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
70,170,287
70,170,465
Bug in templated conversion operator in GCC: Workaround?
I want to have a class representing a unit with some kind of dimension. This should express something like 1.5m^2. A scalar multiplication with some type shall be allowed and a dimensionless unit should behave exactly like the underlying type. Here is my solution: #include <type_traits> template<typename T, int Dim> c...
You can use specialization instead of SFINAE. To avoid too much duplication you can move the common parts (anything that does not depend on Dim) to a base class: #include <type_traits> template <typename T> class base_unit { public: explicit base_unit(T t): _value(t) {} T _value; }; template<typename T, ...
70,170,411
70,170,468
c++ klocwork scan std::vector uninitialized
> -Severity (Error) > -ID(local): 7 > -Code: UNINIT.CTOR.MUST --> IpuCCAInterfaceBase() > -Message: 'this->_remaining_run_kernels_uuids' is not initialized > in this constructor. > -Details: > > 'this->_remaining_run_kernels_uuids' is not initialized in this > constructor. > > * IpuCCAInterfaceBase.cpp:47:...
Perhaps Klockwork requires you to explicitly initialize the vector, for example in a constructor initializer list: IpuCCAInterfaceBase::IpuCCAInterfaceBase() : _remaining_run_kernels_uuids{ } { } With that said, I would consider the message a false positive, as the vector should be implicitly default-constructed (...
70,170,507
70,171,035
How to iterate through a collection of maps of different kinds using range based 'for' loops?
I can iterate through a map as follows: std::map<int, std::string> intMap = { {1, "one"}, {2, "two"}, {3, "three"} }; for (const auto &[k, v]: intMap) { doSomething(k, v); } I have another map (of different type and size) defined as follows: std::map<float, std::string> floatMap = { {1.0, "one"}, {2.0, "two"}}; ...
You can use fold expression to expand immediately invoked lambda to do this: [](const auto&... maps) { ([&] { for (const auto& [k, v] : maps) doSomething(k, v); }(), ...); }(intMap, floatMap); Demo.
70,172,168
70,172,721
One less data is deleted when using hash table delete function
I have created a project using a hash table with separate chaining. Now for my delete function, there is a slight problem, sometimes when a try to delete a node it always deletes 1 less node than it's supposed to. To simplify what I mean is, for example, if I am trying to delete all "people" objects that are in Columbi...
Since deleteByString iterates over all content without using a hash function on its argument, we can assume that countries are not the hash key and thus there can be arbitrarily many items with the same country in a bucket. You can't just drop out of your inner loop when you find one of them in this case. Something lik...
70,172,239
70,176,608
Menubar does not change colour
I have following simple piece of code: m_menuBar = new wxMenuBar(); m_menuBar->SetForegroundColour(*wxRED); m_menuBar->SetBackgroundColour(*wxGREEN); m_menuBar->SetOwnBackgroundColour(*wxYELLOW); But no matter where I set these colours, my menu bar does not show any of them. So what am I doing wrong or what ha...
Unfortunately a menu bar is not really a window even if wxMenuBar does derive from wxWindow. This is confusing, but the relationship between the classes is preserved for compatibility even if it's impossible to implement -- in particular, because there is no way to change the colours of a menu under macOS (or under Lin...
70,172,710
70,172,901
Memory corruption when removing elements from a vector of shared pointers
I was dealing with a bothersome error yesterday involving a function meant to delete elements from a vector of shared pointers. Here's the problematic code: template <typename T> void flush( std::vector<std::shared_ptr<T>>& offers ) { std::vector<unsigned int> idxs; for (unsigned int i = 0; i < offers.size(...
Just posting a quick answer so this can be marked as resolved. The issue is the second loop: in order for the algorithm to work, the indices need to be sorted in descending order; otherwise we'll access out-of-bounds data. I believe the following should behave correctly: template <typename T> void flush( std::vecto...
70,172,806
70,173,019
Iterate over columns in C++ matrix
I want to iterate over single row and column in std::vector<std::vector<int>> matrix and get their sum. I know that I can do this in nested loop, but here is my question. Can I use int val_sum = 0; std::for_each(matrix_[row].begin(),matrix_[row].end(),[&](int x) { val_sum += x;}); for columns and how to do that?
The analogous way of your proposal is to iterate the matrix rows and accumulate the elements in the given column. int val_sum = 0; std::for_each(matrix.begin(),matrix.end(),[&](std::vector<int> &row) { val_sum += row[column];}); But I would still prefer to use the c++11 range-loop version int val_sum = 0; for ( const...
70,172,898
70,173,312
How to use gmock SaveArgPointee with with std::shared_ptr of derived class
I have a BaseMessage class from which I derive several different DerivedMessage subclasses and want to send them like this: class BaseMessage { public: virtual std::vector<uint8_t> data() const noexcept = 0; virtual ~BaseMessage() = default; [...] } class DerivedMessage : public BaseMessage { public: [...]...
In your case you actually want to just save and inspect the considered shared_ptr, so it is enough to use SaveArg: MockTcp mockTcp; SomeClass sc(mockTcp); std::shared_ptr<BaseMessage> bm; EXPECT_CALL(mockTcp, sendMessage(_)).Times(1).WillOnce(::testing::SaveArg<0>(&bm)); // it will effectively do bm = ...
70,172,941
70,173,056
C99 designator member outside of aggregate initializer
struct Foo { char a[10]; int b; }; static Foo foo = {.a="bla"}; Compiling the above code gives the following gcc error: $ gcc -std=gnu++2a test.cpp C99 designator ‘a’ outside aggregate initializer I thought that c-string designators in initializer list like these are ok in C++20? What am I missing? I am us...
This is a known bug with GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55227 Unfortunately, you will have to either not use designated initializers or use a different initializer for the array: static Foo foo = {"bla"}; static Foo foo = {.a={'b', 'l', 'a', 0}};
70,173,395
70,173,987
C++ Win socket sleep bug?
I've got a little problem with sending file with TCP to downloaded server. I spend couple of hours to find what is the problem but still I can't find the reason why it doesn't work. The main problem is when i'm trying to send a file. Program got number of bytes of my file also read the file and passes through the condi...
Your code is broken. send returns the number of bytes sent, and it can be less than bytes_read. But the loop while (test != bytes_read) throws away the buffer contents and fills it with a new fread. You could change it to call send in a nested loop until the entire buffer is sent but that will be inefficient with regar...
70,173,952
70,182,830
<Package>Config.cmake for a library package
We equipped a library package with a *Config.cmake file, following step 11 of the CMake tutorial. Yet our downstream software fails to find the library. Our package is called "formfactor" [https://jugit.fz-juelich.de/mlz/libformfactor]. It provides a shared library (libformfactor) and some header files. Our downstrea...
The script formfactorTargets.cmake, generated by CMake via install(EXPORT formfactorTargets FILE formfactorTargets.cmake DESTINATION cmake ) defines only targets, which has been added to the export set with that name (formfactorTargets). Since you have added only a single library to it set(lib formfactor) ... inst...
70,174,078
70,243,408
Klockwork scan c++ Template value
> -Severity (Error) > -ID(local): 1 > -Code: UNINIT.CTOR.MUST --> IPCAtomic() > -Message: 'this->value' is not initialized in this constructor. > -Details: > > 'this->value' is not initialized in this constructor. > > * CommunicationTypes.h:198: 'this->value' is used, but is > uninitialized. > > * Commun...
To initialize templated member values, use list initialization instead of initializing from a default constructed object. Like this : IPCAtomic() : value{} { } // when initializing with a value use const T& this avoids // unecessary copies. Also make constructors with one parameter // explicit so they can't acci...
70,174,189
70,174,368
Iterate values of a map using range-based for loop
Recently I started using range-based for loop. I had a problem where I needed to sort a map by value and then check if value is smaller/larger then some other element/number. Can I do that with this loop? for (auto& it : M){ // assign only a value to vector } This question would be the same if I had a vector of pa...
From C++20, you can use views::values to get at the values of a std::map, or a vector<pair> for that matter: for (auto v : m | std::views::values) // m is some map // ... demo You can similarly get at the keys with views::keys.
70,174,971
70,180,806
Merge Sort Code Not Giving Desired Output
I have just started to learn recursion. The problem is of merge sort, I was trying to solve it without breaking in two arrays so i am passing the start index (si) and end index (end). #include <iostream> using namespace std; void inputArray(int a[], int n) { for (int i = 0; i < n; i++) { cin >>...
Fixed It, Thank You Everyone! #include <iostream> using namespace std; void inputArray(int a[], int n) { for (int i = 0; i < n; i++) { cin >> a[i]; } } void printArray(int a[], int n) { for (int i = 0; i < n; i++) { ...
70,175,131
70,176,157
Qt: how to implement a hash function for QColor?
I have a need to use std::pair<QColor, char> as a key of unordered_map. As for the pair, I know that there is boost functionality that can be used, but what about the color? Is it enough to just provide the hash template in the std namespace? If so, what would be the best attribute of the color to base the hash on to m...
What you propose will probably work (although you would have to convert the color name from QString to std::string), I would use the RGBA value of the color directly. It is a bit cheaper than having to go through the QString to std::string construction and hash calculation: template<> struct std::hash<QColor> { std::...
70,175,136
70,175,902
Changing internal format causes texture to have incorrect parameters
I set up framebuffer texture on which to draw a scene on as follows: glGenFramebuffers(1, &renderFBO); glGenTextures(1, &renderTexture); glBindTexture(GL_TEXTURE_2D, renderTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, W_WIDTH, W_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN...
You get a GL_INVALID_OPERATION error, because the texture format argument doesn't correspond with the internal format of the texture. For an unsigned integral format you have to use GL_RED_INTEGER instead of GL_RED (see glTexImage2D): glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, 256, 3, 0, GL_RED, GL_UNSIGNED_INT, hist_dat...
70,175,614
70,175,875
Does always int i{0} be faster then int i = 0?
int i{0}; //(1) int i = 0; //(2) Do I have correct understanding that in first case (1) the variable i will be created already with 0 as it's value, and in (2) it will be created without a value and then assigned a value 0, so (1) will always faster then (2)? But seems like most(all?) modern compilers will still optim...
initializing variables with Brace Initialization performs additional checks at compile time (no effect on runtime). . Such as if you enter a float literal inside the curly braces it will throw an error. Initialization with the equal sign will be optimized by the compiler. Prefer brace initialization whenever possible. ...
70,175,635
70,175,879
C++: Member function call forwarding using variadic data structure
I am trying to create a class (similar to std::tuple) which can hold a variable number of references to objects of different type and which can forward a call to a specific member function to all of its constituents. Here is an example: // g++ Test7.C -std=c++17 -o Test7 #include <iostream> struct P1 { void operator(...
It looks like you're trying to do partial specialization, and you're close. Rather than this template <class... EmitterList> struct Emitters { inline void operator()(void) const { std::cout<<std::endl; } }; Consider template <class... Ts> struct Emitters; template <> struct Emitters<> { void operator()(void) cons...
70,175,652
70,175,769
How to write else if as logical statement?
I want to write an if-else statement as a logical statement. I know that: if (statement1){ b=c } else{ b=d } can be written as: b=(statement1 && c)||(!statement1 && d) But how do I write the following if-else statements as logical?: if (statement1){ b=c } else if (statement2){ b=d } else{ b=e } I have...
As with all logical statement building, it'll be easiest to create a truth table here. You'll end up with: +--+--+--------+ |s2|s1| result | +--+--+--------+ | 0| 0| e | +--+--+--------+ | 0| 1| c | +--+--+--------+ | 1| 0| d | +--+--+--------+ | 1| 1| c | +--+--+--------+ So un-simplified, that'll...
70,175,970
70,176,116
What is the type of a lambda expression for the compiler?
So, if we run the gdb on the following source code : //... auto myLambda1 = [&](int x){ printf("Hi, I got x=%d here\n",x);}; auto myLambda2 = [&](double y){ printf("Hi, I got y=%f here\n",y);}; //... I will get : (gdb) ptype myLambda1 type = struct <lambda(int)> { } (gdb) ptype myLambda2 type = struct <lambda(double)>...
The type of a lambda expression is a class type, but it has no name. The most important feature of the class is that it has a public operator() so that it can be used in a function-call expression syntax. Tons of technical details are in the Standard section [expr.prim.lambda.closure], which begins with The type of a ...
70,176,159
70,176,518
Overload function/method with template argument
I want to overload a method, based only on template argument (which is a type), without passing any method arguments. For that, I use code like this (simplified, of course) in C++17: template<typename T> class C { public: auto f() const { return f((T*) nullptr); } private: in...
(The comments on the question raise some valid questions about why you would have this. But just focusing on the question as asked.) It is a bit hacky, but sometimes having an API function call an implementation function for technical reasons is a reasonable approach. One gotcha you might get into with that pattern is ...
70,176,567
70,177,536
Why connect `QThread::finished` signal to `QObject::deleteLater`?
I read this in the Qt 5.15 documentation for QThread::finished: When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to QObject::deleteLater(), to free objects in that thread. However,...
QObject::deleteLater in this case is essentially just erring on the side of caution. There's no reason you couldn't simply delete the objects if you're absolutely certain there's no chance the object will be accessed. In practice though you'll save way more time simply using QObject::deleteLater and letting Qt take car...
70,176,591
70,176,650
Determine the longest word in a text input
How do I create a program where it reads in text from the user and then outputs the shortest and longest words and how many characters these words contain? So far, I can only create a program that counts the number of words in the text. int count_words {}; string word; cout << "Type a text:" << endl; while (cin >> wo...
Simply declare a couple of string variables, and then inside the while loop you can assign word to those variables when word.size() is larger/smaller than the size() of those variable, eg: size_t count_words = 0; string word, longest_word, shortest_word; cout << "Type a text:" << endl; while (cin >> word) { ++cou...
70,176,780
70,177,121
C++ Template specialization of member function with a generic type eg. std::vector<T> do not compile
I have a problem with specialization of a member function of a generic struct. My goal is to specialize the member function Run of Bar with all kinds of std::vector. #include <iostream> #include <vector> // (1) compile template <typename T> struct Foo { T Run() { std::cout << "Foo not specialized" << std::endl...
Template functions cannot be a partially specialized. You can do it with a trampoline and overloading. Like Run(){ DoRun(*this) then write DoRun overloads.
70,176,846
70,177,008
How do I specify the size of a class in C++?
My task is to create a class that implements Floating point number. The size of the class must be exactly 3 bytes: 1 bit for the sign 6 bits for exponent 17 bits for mantissa I tried to implement the class using bit fields, but the size is 4 bytes : class FloatingPointNumber { private: unsigned int sign : 1; u...
C++ (and C for that matter) compilers are permitted to insert and append any amount of padding into a struct as they see fit. So if your task specifies that it must be exactly 3 bytes, then this task can not be done with struct (or class) using just standard language elements. Using compiler specific attributes or prag...
70,177,177
70,177,380
Catch c++ Access Violation exception
A c++ access violation error gets thrown at some part of my code. I would like to "catch" it and log the faulting line so I can investigate further. I tried the first answer in this thread: Catching access violation exceptions? Unfortunately no luck so far. I am using debug mode in Visual Studio 2019. Anyone knows a wa...
On Windows, you can do it with __try ... __except, as in the following simplified example: __try { * (int *) 0 = 0; } __except (EXCEPTION_EXECUTE_HANDLER) { std::cout << "Exception caught\n"; } Microsoft call this mechanism 'structured exception handling' and it is much more powerful (and, indeed, usable) than...
70,177,472
70,177,502
Why is #undef not working for my function?
I defined something at the beginning: #define noprint Then I returned in my functions if it's defined: void print() { #ifdef noprint return; #else //do stuff #endif } Then in the main function: main() { #undef noprint print(); } And it still doesn't work. How come?
Macros are not variables. They are a simple text replacement tool. If you define, or undefine a macro, then that (un)definition has no effect on the source that precedes the macro. The function definition doesn't change after it has been defined. Example: #define noprint // noprint is defined after the line above void...
70,177,526
70,177,553
C++ UNIX Help - simple TCP server socket connection
I am a student writing a C++ code using UNIX system calls to perform simple server <-> client requests from the Terminal. The user (me) input in the port for both programs (Server and Client) in the Terminal to establish a connection, the goal is for the Server to send back to the Client the contents of what the Client...
You problem is here: else if(s.st_mode & S_IFREG) { int fd = open(path, O_RDONLY); if(fd < 0) { perror("open"); exit(EXIT_FAILURE); } read(fd, buffer, strlen(buffer)); << Change strlen(buffer) strcat(buffer, "\n"); if(write(connSock, buffer, strlen(buffer)) < 0) { perror("write"); exit(EXIT_FAIL...
70,177,686
70,181,913
How to set text origin to be the center of sf::text in SFML?
I need to center a text object in SFML to the middle of the string rather than the top left corner. Thus far, I have tried this: topTextObj.setOrigin( (float)topTextObj.getCharacterSize() / 2, (float)topTextObj.getCharacterSize() / 2); However, this does not fix my issue, as the text is still top-left aligned.
origin should be set to the center of text bounding rect: sf::FloatRect rc = text.getLocalBounds(); text.setOrigin(rc.width/2, rc.height/2);
70,177,691
70,177,782
Storing timepoints or durations
I want to make a simple editor to shift subtitle times around. A Subtitle of WebVTT is made of chunks like this: 1 00:02:15.000 --> 00:02:20.000 - Hello World! So as you can see there is a time that the subtitle will apear and a time that it dissapears. This time is also can be clicked to jump to that specific point o...
Since these are time points relative to the beginning of the video, not to some clock, I suggest keeping it simple and using std::chrono::milliseconds. They support all operations you require, except im not sure there is an existing implementation for parsing them from a string. But that should be very easy to build.
70,177,987
70,178,656
Point Cloud Library Octree lib generating error
I get this error just by including the header file to my code. I'm using visual studio 2019 and c++17, I've included the linker files and all but it doesn't want to work. What could it be? Error C4996 'std::iterator<std::forward_iterator_tag,const pcl::octree::OctreeNode,void,const pcl::octree::OctreeNode *,const pc...
It is a warning for using deprecated code and Visual Studio treat it as error by default. Go to project properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> set to No. And it should be good.
70,178,194
70,178,221
Error: initializer must be brace-enclosed
What does this error mean and why can't I initialise this struct with a braced initialiser list? Unfortunately the structs are auto-generated. // Contains no functionality, purely documentative. struct NativeTable {}; ... struct TableKeyT : public flatbuffers::NativeTable { typedef TableKey TableType; std::string...
Since TableKeyT inherits NativeTable, you also need to initialize the base class, but since it is an empty class, using {} should be fine. TableKeyT key { {}, std::string(sym), std::string(ex), std::string("") }; //^^^
70,178,398
70,178,432
Obtaining start position of istringstream token
Is there a way to find the start position of tokens extracted by istringstream::operator >>? For example, my current failed attempt at checking tellg() (run online): string test = " first \" in \\\"quotes \" last"; istringstream strm(test); while (!strm.eof()) { string token; auto startpos = strm.tell...
First, see Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong? Second, you can use the std::ws stream manipulator to swallow whitespace before reading the next token value, then tellg() will report the start positions you are looking for, eg: #include <string> #include <sstream...
70,178,437
70,178,467
Segmentation Fault while getting input from 2D vector
I get a segmentation fault when I run the code below. int main() { int R, C, val; cin>>R>>C; vector<vector<int>> a; for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { cin>>val; a[i].push_back(val); } } But when I change it to this, it s...
You have never told what is the size of vector<vector<int>>, and you try to access a[i]. You have to resize the vector. int main() { int R, C; std::cin >> R >> C; std::vector<std::vector<int>> a(R, std::vector<int>(C)); for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { ...
70,178,477
70,178,506
Cannot initialize a lambda member variable with a default argument
I would like to compile the code below with c++17, so that I can pass any function (lambda) that has a specific signature, int(int), while also allowing the default argument: template <class F = int(int)> // for deduction struct A{ A(F f = [] (int x){return x;}) : f_{f} {} F f_; }; int main() { ...
As the error message said, you can't declare a data member with a function type like int(int). When passing a lambda to the constructor, the template parameter F would be deduced as the lambda closure type by CTAD (since C++17); when passing nothing F will use the default argument int(int) and the data member f_'s type...
70,178,554
70,178,649
Qt: how can one close a window upon another window closed by the user
The following code snippet opens two windows, w1 and w2. How can one force w2 to close when w1 is closed by the user? As in the comment, the connect function is not working that way. #include <QApplication> #include <QtGui> #include <QtCore> #include <QtWidgets> int main(int argc, char *argv[]) { QApplication a(ar...
This modified version of your program shows how you could do it by overriding the closeEvent(QCloseEvent *) method on your w1 widget: #include <QApplication> #include <QtGui> #include <QtCore> #include <QtWidgets> class MyWidget : public QWidget { public: MyWidget(QWidget * closeHim) : _closeHim(closeHim) { ...
70,178,758
70,180,682
Dynamically create a SphereComponent in UnrealEngine
I'm trying to create a SphereComponent dynamically 2 seconds after the level is started. For that I have this following code: void ACollidingPawnSpawnPawns::DelayedFunction() { // The first parameter 'SphereComponent' is the main component in the level and it has been created using the CreateDefaultSubobject m...
First, only NewObject can be used to create components outside of constructor: void ACollidingPawnSpawnPawns::DelayedFunction() { // you should specify outer as current actor (because this component is part of it) USphereComponent* DynamicallyCreatedSphere = NewObject<USphereComponent>(this, USphereComponent::...
70,179,190
70,179,392
enum class with scoping but without having to cast to underlying type
I have this: enum class Categories : uint32_t { C6 = 0x00000020, C7 = 0x00000040, C8 = 0x00000080, ... }; I chose an enum class because it is great for scoping. But the downside is that when I need to use the categories as mask bits for bitwise operations I need to cast them to uint32_t first. Example:...
Split the enum class into an enum and a class (or struct for convenience). struct Categories { enum : uint32_t { C6 = 0x00000020, C7 = 0x00000040, C8 = 0x00000080, }; }; Since the enum is an embedded type, you need to specify Categories to access it, as in Categories::C6. If this is ins...
70,179,351
70,181,124
How to write this floating point code in a portable way?
I am working on a cryptocurrency and there is a calculation that nodes must make: average /= total; double ratio = average/DESIRED_BLOCK_TIME_SEC; int delta = -round(log2(ratio)); It is required that every node has the exact same result no matter what architecture or stdlib being used by the system. My understanding i...
For this kind of calculation to be exact, one must either calculate all the divisions and logarithms exactly -- or one can work backwards. -round(log2(x)) == round(log2(1/x)), meaning that one of the divisions can be turned around to get (1/x) >= 1. round(log2(x)) == floor(log2(x * sqrt(2))) == binary_log((int)(x*sqrt(...
70,179,422
70,179,671
OpenGL texture function always return 0 on integer data
I'm working on a deferred shading pipeline, and i stored some information into a texture, and this is the texture attached to my gbuffer // objectID, drawID, primitiveID glGenTextures(1, &_gPixelIDsTex); glBindTexture(GL_TEXTURE_2D, _gPixelIDsTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32UI, _width, _height, 0, GL_RGB_I...
uniform sampler2D gPixelIDsTex; Your texture is not a floating-point texture. It's an unsigned integer texture. So your sampler declaration needs to express that. Just as you write to a uvec3, so too must you read from a usampler2D.
70,179,604
70,187,736
Extracting the edges of odd degree vertices in a graph
I have a graph as follows, represented by an adjacency matrix MyCustomVector<MyCustomVector<int>> graph: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 0 1 1 INF INF INF INF INF INF INF INF...
Simply extract the rows and columns corresponding to the subset of indices: using std::vector; /* ** input: ** adjacency list adj ** subset of node indices v ** output: ** adj list of induced subgraph subadj */ vector<vector<int>> get_subgraph(vector<vector<int>> const &adj, vector<int> co...
70,179,854
70,182,042
longest increasing subsequence wrong answer
I wrote a recursive solution for the longest increasing subsequence and it worked perfectly fine. But when I applied dp on the same code it gives different answers. Problem Link: https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence-1587115620/1 Recursive code: int LISrecursive(int arr[], int n, in...
When I think of dynamic programming, I usually break it down into two steps: Solve the recursion with "including the current element before recursing again" compared to "not including the current element before recursing again". This is exactly what you did with your recursive solution. Take the recursive solution ...
70,179,958
70,180,096
No matches converting function in C++ error
When I run the code snippet I get the following error. error: no matches converting function ‘exp’ to type ‘struct std::complex (*)(struct std::complex)’. However when I call exp() inside main() passing a complex argument to it,it runs fine. Can somebody please help? using namespace std; complex<long double> testExp(c...
In the documentation, the prototype is complex<T> exp( const complex<T>& z ). You should declare your function pointer as complex<double>(*test_func)(const complex<double>&). Then, at the call site, use exp<double>. The result of the function is complex<long double> but result is complex<double>, you should change its ...
70,180,414
70,180,623
My binary search function in c++ in Array is not working and I am not getting why
My code isn't working. The problem may be in the loop.I was trying to write c++ code for Binary Search and it just doesn't execute.In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted a...
You do not adjust mid in the loop so it stays at the same index that you initialized it with. Suggested change: int BinarySearch(const Array& arr, int key) { // const&, no copy int low = 0; int high = arr.length - 1; int mid; while (low <= high) { mid = (low + high) / 2; // assign mid inside...
70,180,470
70,180,523
Using static results in an undefined reference in this piece of code
This is a MSVP of a problem I am facing. What is wrong with m_eventQueue being static in the code below ? When it is not static, it compiles fine. I want it to be static because I am planning to use it in another class as well and it is a common queue between them. This is the error I get badri@badri-All-Series:~/prog...
When you declare a static member in a class, C++ requires you to define the member outside of the class explicitly. Put this outside of your class in the .cpp file: /*static*/ EventQueuePtr commonQueue::m_eventQueue;
70,180,495
70,181,240
How can I fix c6385?
// Take last element from deck and add to dealer's hand // Update current elements after //Ensure the deck still has cards if (deck.currentElements == 0) { getNewDeck(deck); shuffleDeck(deck); } deck.currentElements -= 1; dealerCards.currentElements += 1; dealerCards.Card...
dealerCards.Cards[dealerCards.currentElements] will not be assigned for dealerCards.Cards[0]; there will be a hole. --deck.currentElements; dealerCards.Cards[dealerCards.currentElements] = deck.Cards[deck.currentElements]; ++dealerCards.currentElements; This assumes that a valid index is in 0 .. (currentElements-1). T...
70,180,548
70,180,635
How to detect C-style multidimensional arrays in templates specialization?
I have the following code: enum type_kind{unkown=-1,carray, multi_carray}; template<class T> struct detect_carray{ constexpr static int kind=unkown; }; template<class T, std::size_t N> struct detect_carray<T[N]>{ constexpr static int kind=carray; }; Now, I want to add another specialization for detecting multid...
Just add a specialization for multidimensional arrays: template<class T, std::size_t N1, std::size_t N2> struct detect_carray<T[N1][N2]>{ constexpr static int kind=multi_carray; }; then std::cout<<detect_carray<std::vector<int>>::kind;//-1 std::cout<<detect_carray<int[3]>::kind;//0 std::cout<<detect_carray<double[3...
70,180,555
70,181,077
Yet another how to create a C wrapper of a C++ class?
I'd like to create a C wrapper for a C++ library I wrote. All the examples and SO's answers I found: Using void, typedef void myhdl_t How can I call a C++ function from C? Trojan horse structure: struct mather{ void *obj; }; https://nachtimwald.com/2017/08/18/wrapping-c-objects-in-c/ # .h struct mather; typedef str...
My case: I'd like to have an allocation C function like that: int alloc_function(struct Foo** foo){ Foo is already a C++ type. Use a different one. Use a void * pointer. struct CFoo { void *pnt; }; extern "C" int alloc_function(struct CFoo* foo) { if (!foo) return -EINVAL; // That is no EFAULT, it's EINVA...
70,181,531
70,181,578
How to instantiated this ListNode struct in C++?
I am confused about the struct in Leetcode (Algorithm #2). struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; The first problem is I dont know how to instantiated an...
The statement list_input->next; fetches the value of list_input->next and then does nothing with it. You probably want: list_input = list_input->next; That will make list_input point to the next element in the list. Also, how you create the list, the call ListNode_output(&p1_1) should be ListNode_output(&p1_3) to pr...
70,181,611
70,261,388
C1047 The object or library file '' was created by a different version of the compiler
I am migrating VC++ project from VisualStudio2015 to VisualStudio2019. One of the project reporting below error, Error C1047 The object or library file 'Library Path' was created by a different version of the compiler than other objects like 'Object file path'; rebuild all objects and libraries with the same compil...
I followed below step , issue got resolved. Error C1047 The object or library file 'Library Path' was created by a different version of the compiler than other objects like 'Object file path'; rebuild all objects and libraries with the same compiler. compile the reported Library Path project in same compiler [VS2019:T...
70,181,668
70,181,921
Overloading operator[] only for members of a specific class
Edit: MyClass has been renamed to ReverseStringAccess for disambiguation. I have a class which encapsulates a vector<string>. The class has an overloaded operator[] which can be used to read and modify the contents of the vector. This is how it looks (minimally): class ReverseStringAccess { public: ReverseS...
If you want my_object[i][k] to not invoke std::string::operator[] then don't return a std::string& from MyClass::operator[], but a proxy that implements the desired []: class MyClass { public: MyClass() {} MyClass(vector<string> _arr) arr(_arr) {} struct MyProxy { std::string& ...
70,181,681
70,406,854
Connect 4: Drop function only works for two row
const int N = 200; const string usr1 = "o", usr2 = "x"; void updateBoard(string a[N][N], int c, int n, string xo) { int col = c - 1; int row = n - 1; for (int i = row; i >= 0; i--) { if ((a[i][col] == usr1) || (a[i][col] == usr2)) { a[i - 1][col] = xo; } if ((a[i][col] == " ")) { a[i][col]...
I found the answer... Here's the fixed function: bool updateBoard(string board[N][N], int col, int n, string xo) { for (int i = n - 1; i >= 0; i--) { if (board[i][col - 1] == "-") { board[i][col - 1] = xo; return true; } } return false; }
70,181,738
70,181,780
Should I delete heap objects that will last for the life of the process?
If I created some objects in the heap during the execution of my program; And I know that all these objects will continue to be accessed until the very final lines of codes of main(); Then is it malpractice to not delete the objects in the heap? and is there any actual harm from that behavior?
It is a good general rule to delete the objects when they are not used anymore. However, when a process exits, all its heap memory is released.
70,182,217
70,182,333
How to access a Protected Variable Correctly?
I am trying to access one of the protected variable from items.h class using components.cpp class but I got the error confusing me: :D Item::Quantity': cannot access forbidden protected member declared in class 'Item' item.h protected: int32 Quantity; component.h #include "Items/Item.h" Item* AddItem(class...
You can solve this by making the class Component a friend of class Item by adding a friend declaration inside class Item as shown below: item.h class Item{ friend class Component; protected: int32 Quantity; //other members here }
70,182,228
70,183,725
Using the keyword 'new' in file scope?
Given this class in the header file: class ClassA { public: ClassA(){}; } Then in file.cpp #include file.h ClassA* GlobalPointerToClassAType = new ClassA(); a. Is it allowed, and is it good practice to use the keyword 'new' to allocate memory for an object in the heap(?) in lines of file-scope? b. If it is allowed, t...
a. Is it allowed, and is it good practice to use the keyword 'new' to allocate memory for an object in the heap(?) in lines of file-scope? It is allowed. Whether is it good practice to use new here is opinion based. And i predict that most people will answer no. b. If it is allowed, then when exactly does the const...
70,182,512
70,183,276
Debugging into MFC header code does not work with Visual Studio 2019
TL;DR: Debuigging into MFC (CString) header code does not work on both my machines and as far as I can tell this is due to the peculiar way these headers are compiled. Stepping through MFC header code when entered via disassembly works, but setting brealpoints does not work. I'm looking for a workaround or at least ack...
Analysis went sideways at some point, but we finally found one part of the problem here: The Require source files to exactly match the original version option: was the problem, but in a very peculiar way: When you do NOT require source files to match (that is, disable this default option), then the erroneous behavior ...
70,182,726
70,182,926
Error: Use of deleted function std::unique_ptr
I am trying to pass a unique_ptr into a custom vector class but I am receiving the error in the subject title. I understand that you cannot copy a unique_ptr and so I am trying to use std::move() when passing it, however that doesn't seem to solve my problem... Where am I going wrong? Thanks in advance template<typenam...
If you want to allow both copy-via-const-ref and move-via-rvalue-ref, you can either template your Add method and use the universal forwarding reference technique, or write two overloads explicitly: void Add(const T& v) { m_Items.push_back(v); } void Add(T&& v) { m_Items.push_back(std::mo...
70,182,761
70,184,973
Boost: how to use `boost::hash` with `std::pair`, when pair contains a custom type?
I'm trying to use the following custom unordered_map using pair = std::pair<char, QColor>; using cache = std::unordered_map<pair, QPixmap, boost::hash<pair>>; cache _cache; I defined the hash function for QColor as follows template<> struct std::hash<QColor> { std::size_t operator()(const QColor &color) const noex...
boost::hash<> probably uses boost::hash_combine which uses hash_value overloads and it doesn't have one for QColor which could be a problem so I suggest that you create a specialization for std::hash<Pair> by moving the alias out of the class definition and then use boost::hash_combine directly in your operator(): usin...
70,183,511
70,183,588
Trying to access private class variables in header function
I need several functions in a header file that use std::cout to say the date, but I don't know how to access them from the header file. If I were within the class, I could just say something like: void DisplayStandard() { cout << month << "/" << day << "/" << year << endl; } However, since I'm access...
You can solve this by changing void DisplayStandard() to void dateclass::DisplayStandard() as shown below void dateclass::DisplayStandard()//note the dateclass:: added infront of DisplayStandard { cout << "Date: " << month << "/" << day << "/" << year << endl; }
70,183,672
70,198,448
Add non-included header file to up-to-date check in Visual Studio project
I am using Microsoft Visual Studio 2017 and I write code in C++. There always was one problem with the #define settings in header files. The first approach is to place settings in multiple header files corresponding to specific source files. This approach is OK for minimal rebuild but the main disadvantage is that sett...
Solved. Just changed Item Type to C/C++ compiler instead of the C/C++ header in the config.h properties.
70,183,943
70,185,179
Jsoncpp - How do I read an array?
I'm stuck at trying to read an array from a Json file. Here is the People.json file: { "ID": [ { "1": { "name": "Fred", "favouriteFood": "Cheese", "gender": "Male" } }, { "2": { "name": "Bob", "favouriteFood": "Cake", "gender": "Male" ...
Problem is your JSon which is badly designed. It is bad since objects have keys of unexpected values. Those "1" and "2" make things complicated. I do not see in documentation how to get list of keys of a JSon object. Ok I've found getMemberNames(), but you try use it yourself. IMO it would be better to fix this JSon. S...
70,183,974
70,184,638
How to convert this vector code into a class?
I was trying to put this code into a class but I couldn't manage to do it. The job of the function is pulling team names from a .txt file and putting them in a vector. I think the main problem is I couldn't select the right function return type. This is the teams.txt: (The names before the "-" symbol are teams. Other n...
I did a little different research based on the Botje's comment. And I manage to create an answer based on here. Thanks. #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; std::string process(std::string const& s){ string::size_type pos = s.find('-'); if (pos != str...
70,184,010
70,184,161
Exception thrown: Write access violation C++
I want to fill (obj * m) with numbers 2 4 6 8 10 12 14 16 18 20. In Microsoft Visual Studio Professional 2019 I am getting this error: "Exception thrown: Write access violation" at the line "n-> val = data;" or line 15. But then I went into the DEV C ++ application and there I realized what the error was, for some reas...
In your code, next is not initialized, so n becomes to point wrong address during iteration in func int main() { /* ... snipped ... */ /* Initialize `next` */ for (int i = 1; i < 100; i++) { m[i - 1].next = &m[i]; } m[99].next = nullptr; /* snipped */ }
70,184,436
70,184,534
How to stop fold expression function calls in the middle when a condition is met and return that value?
I have functions foo, bar, baz defined as follows: template <typename ...T> int foo(T... t) { return (bar(t), ...); } template <typename T> int bar(T t) { // do something and return an int } bool baz(int i) { // do something and return a bool } I want my function foo to stop folding when baz(bar(t)) == tr...
Use short circuit operator && (or operator ||): template <typename ...Ts> int foo(Ts... t) { int res = 0; ((res = bar(t), !baz(res)) && ...); // ((res = bar(t), baz(res)) || ...); return res; } Demo Note: (baz(res = bar(t)) || ...); would even be shorter, but less clear IMO.
70,184,472
70,184,624
what's the advantage of defining a class instead of a function in some c++ standard library?
Recently I noticed that C++ std::less is a class,although it simply compares the values of two objects.Here is a sample code: template <class T> struct less { bool operator() (const T& x, const T& y) const {return x<y;} typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; }; ...
Primarily to use it as a template parameter, like std::set<int, std::less<int>>. Class template parameter in interfaces like std::set is used instead of pointer to function to be able to pass other function-like objects that do have some data members. In addition, making it a template parameter aids compiler optimizati...
70,185,148
70,185,327
Unpacking first parameter from template parameter pack c++
I'm new with templates, specially with parameter pack and I wonder if I can get the first value from the pack. For example the following code: template <typename T, typename... Args> bool register(Args... args) { if (!Foo<T>(args..) { assert(std::is_same_v<std::string, args...[0]>); std::cerr << "Fa...
You can use lambda to extract the first parameter: template<typename T, typename... Args> bool register(Args... args) { if (!Foo<T>(args...)) { auto& first = [](auto& first, auto&...) -> auto& { return first; }(args...); static_assert(std::is_same_v<std::string, std::remove_re...
70,185,398
70,185,561
What has changed in C++17 in terms of MOVE elision
Is the "move elision" guaranteed in C++17? Let me explain what I mean by that. In almost every article on what C++17 has introduced, one can find the term: "guaranteed copy elision for RVO" which is kinda self-explanatory. But what about move construction? Let's look at the code below, it's simple there is a non-copyab...
Since C++17 mandatory elision of copy/move operations was introduced: Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the s...
70,185,461
70,185,576
How to make a type T that `std::is_empty_v<T> && sizeof(T) > 1` is true?
I came across an interesting quiz question at here: Write a translation unit containing a class type T, such that std::is_empty_v<T> is true, and yet sizeof(T) is greater than 1. I'v thought about it for some time, but no solution. How to make a type T that std::is_empty_v<T> && sizeof(T) > 1 is true?
std::is_empty checks if there are no members. You can use alignment to force a size greater than 1: struct alignas(2) T {}; static_assert(std::is_empty_v<T>); static_assert(sizeof(T) > 1);
70,185,484
70,186,252
Problem with reading a binary file in cpp?
I have a binary file called "input.bin" where every character is of 4 bits. The file contains this kind of data: 0f00 0004 0018 0000 a040 420f 0016 030b 0000 8000 0000 0000 0000 0004 0018 0000 where 0f is the first byte. I want to read this data and to do that, I am using the following code: #include <string> #include...
The problem is here myFile.read (buffer, 100); if (!myFile.read (buffer, 100)) { where you read twice, and thus ignore the first 100 bytes (if there are more than 100 of them). Remove the first read, or change the condition to if (!myFile)
70,185,610
70,185,832
Transform uppercase letters to lowercase and vice-versa using single parameter function (C++)
I have the trans function which uses a single parameter, has to be void, and returns through c the opposite case of a letter from a word input in main. Example: input: dOgdoG output: DoGDOg The function does change the case, but i cant figure out a way to build the new word / replace the old one because i keep getting...
Don't reinvent the wheel. The standard library has functions to identify uppercase and lowercase letter, and to change case. Use them. char trans(char ch) { unsigned char uch = ch; // unfortunately, character classification function require unsigned char if (std::isupper(uch)) return std::tolower(uch); ...
70,185,771
70,185,809
Template value before typename
I have following simplified example code where I attempt to figure out whether given value is the maximum value of enum of it's type. enum class MyEnum : unsigned char { VALUE, OTHER_VALUE, _LAST }; template<typename T, T _L> bool is_not_last(T value) { return value < _L; } int main() { is_not_las...
Since C++17, you might do template <auto L> bool is_not_last(decltype(L) value) { return value < L; } Demo
70,185,931
70,188,915
How to know if shared_ptr was already serialized to boost archive
In my program I have c++ class objects that keep SmartPointers members (SmartPointer is my own custom class derived from boost::shared_ptr). By design, some of my class objects must keep SmartPtr that are unique i.e no shared ownership is allowed. I want to implement check module for debug reasons that will test whethe...
The code smell is using a shared_ptr where unique ownership must be guaranteed. What are you going to do when you find a violation? Assert? std::terminate? You could make a serialization wrapper that adds the check on de-serialization. You will depend on library implementation details, because - apparently - while load...
70,185,973
70,186,799
Box2D weird behavior with std::vector
lately I started playing with box2d and tried abstracting it to class RigidBody::RigidBody() { } RigidBody::RigidBody(const RigidBody& other) { m_fixture = other.m_fixture; b2BodyDef bodyDef; bodyDef.position = other.m_body->GetPosition(); bodyDef.type = other.m_body->GetType(); m_body = Runtime...
The problem was I didn't define operator = resolved it by RigidBody* RigidBody::operator=(const RigidBody& other) { if(m_body) Runtime::PhysicsWorld.DestroyBody(m_body); m_fixture = other.m_fixture; b2BodyDef bodyDef; bodyDef.position = other.m_body->GetPosition(); bodyDef.type = other.m_b...
70,186,254
70,207,179
How to formulate the position of each number in a magic square?
How did this code formulate the position of each numbers? I'm kinda dumb at math and I can't contact the one who made this code. so can anyone enlighten me with this? especially on the test positions part. #include <iostream> using namespace std; int main () { int magicsq[3][3]; int i, j, x; int row = 0; ...
This program is about creating a magic square according to the "de la Loubère" method. There is a very good explanation on Wikipedia here. You should read that. It has even animated graphics. Very nice. The code that you found, is not nice. It is imply ugly and you should not waste your time in understanding it. The me...
70,186,333
70,187,028
Advice on converting timestamp string in "HH:MM:SS.microseconds" format
I'm given a list of timestamps (suppose we have a ready-made std::vector<std::string>) in a string format of a kind std::vector<std::string> = {"12:27:37.740002", "19:37:17.314002", "20:00:07.140902",...}. No dates, no timezones. What would be a preferable way to parse these strings to some kind of C++ type (std::chron...
You can build this functionality completly with C++ standard library functionality. For parsing the string use std::regex. For time related datatypes use std::chrono Example : #include <stdexcept> #include <regex> #include <chrono> #include <iostream> auto parse_to_timepoint(const std::string& input) { // setup a ...
70,186,672
70,189,478
Eigen3 (cpp) select column given mask and sum where true
I have a Eigen::Matrix2Xf where row are X and Y positions and cols act as list index I would like to have the sum of the columns (rowwise) where some column condition is true, here some example code: Eigen::Vector2f computeStuff(Eigen::Matrix2Xf & values, const float max_norm){ const auto mask = values.colwise().n...
The main problem with your code is that .select( ... ) needs at least one of its arguments to have the same shape as the mask. The arguments can be two matrices or a matrix and a scalar or vice-versa, but in all cases the matrices have to be shaped like the mask. In your code mask is a row vector but values is a 2 by x...
70,186,757
70,187,301
g++ cannot find library although it's there
I'm compiling some cpp files with: $ ​g++ -c --std=c++17 -I/antlr4/runtime/Cpp/runtime/src/ *.cpp And everything goes fine: $ ls -l *.cpp *.o -rw-r--r-- 1 root root 76637 Dec 1 14:33 Java8Lexer.cpp -rw-r--r-- 1 root root 370768 Dec 1 15:13 Java8Lexer.o -rw-r--r-- 1 root root 925012 Dec 1 14:33 Java8Parser.cpp -...
You can specify the directory with option -L and the library file with its abbreviated form (no lib prefix, no .so.xxx suffix): g++ *.o -L /antlr4/runtime/Cpp/dist -lantlr4-runtime
70,187,432
70,187,577
Is it implementation-defined that how to deal with [[no_unique_address]]?
Below is excerpted from cppref but reduced to demo: #include <iostream> struct Empty {}; // empty class struct W { char c[2]; [[no_unique_address]] Empty e1, e2; }; int main() { std::cout << std::boolalpha; // e1 and e2 cannot have the same address, but one of them can share with // c[0] and ...
See [intro.object]/8: An object has nonzero size if ... Otherwise, if the object is a base class subobject of a standard-layout class type with no non-static data members, it has zero size. Otherwise, the circumstances under which the object has zero size are implementation-defined. Empty base class optimization bec...
70,187,552
70,192,005
can we define 'operator<' as member function of a class to work with std::less?
I am trying to write member function which can be used when we call std::less. I defined a 'pqueue' class which stores contents in dequeue internally and uses std::less to compare. Defined one more class 'myClass' and I am using pqueue to store objects of the class. Code is as below. #include <iostream> #include <deque...
This answer is from the comment 'Jarod42' posted. Missing const (at the end) -> bool operator < (const myClass &obj) const else it is like if friend function would be friend bool operator < (myClass&, const myClass&).
70,187,754
70,188,484
Find position of min element of a "masked vector"
I have a vector of some values and a mask vector of 0's and 1's. For example: std::vector<int> mask{0, 0, 1, 0, 1, 1, 0}; std::vector<double> vec{7.1, 1.0, 3.2, 2.0, 1.8, 5.0, 0.0}; and I need to find the min element (its index) in vec but only where mask is 1. In this example it is 1.8 at index 4. Here'...
You can transform into a combined vector, using max double as a replacement for masked values, and use that with std::min_element #include <algorithm> #include <iostream> #include <limits> #include <vector> int main() { std::vector<bool> mask{0, 0, 1, 0, 1, 1, 0}; std::vector<double> vec{7.1, 1.0, ...
70,188,097
70,188,138
Detecting memory leaks
Consider the following code: int main(){ A c; A array[5]; A *ptr; } Assuming that class A has no memory leaks. Does the above code have any memory leaks? My thoughts: The variables c and array of these six objects of type A will get allocated/instantiated. The ptr variable is not assigned anything, so that...
There are no memory leaks as there are no mismatched malloc / free new / delete new[] / delete[] The array array[5] has automatic storage duration. That's the formal term for being "on the stack". Conceptually it goes out of scope at the closing brace } of main(), after ptr has gone out of scope.
70,188,661
70,219,784
Why would a program crash in DllMain() when linking Xinput.lib
I have created an input library and I link with xinput.lib. The program that uses my input library crashes on start up before any user code is executed so it makes it pretty hard to debug. The program crashes during xinput dll loading which appears to happen in the generated dllmain function of my library. The error ...
I can confirm that this must be a bug in the latest clang-cl tool-chain (it worked about 2 years ago when i was heavily working on this project). After using the msvc tool-chain, everything works as expected. I will file a bug report with Microsoft Visual Studio.
70,188,797
70,220,729
Reserving memory for an object in heap without calling its constructor on Arduino
I'm working on an arduino project, this is relevant since there's no support for STL nor dynamic allocation on arduino natively. I've noticed that a lot of classes I'm writing do nothing on construction, but have an .init() method that actually initializes any resources. This is because that way the class can be initia...
This is the solution I ended up with. .init emulates the pattern that most classes in the arduino libraries use, without actually splitting the init logic in two methods. There's definitely room for improvement, but this works for global variables. #pragma once #include <new> template<typename T> union MemoryOf { uin...
70,189,132
70,189,222
C++ call function from class without instantiating it
In dice.h, I have class dice { public: dice(int sides); int roll() const; static int globalRoll(int sides); private: int sides; And in dice.cpp dice::dice(int sides) { this->sides = sides; } int dice::roll() const { return rand() % sides + 1; //Here sides refers to member field } int dice...
Ok I just needed to change dice. to dice::. I feel silly. I don't really understand the difference but I'll look into it. Also, since overhead is irrelevant and it's bad practice to have different paths to accomplish the same thing (and most importantly it can still be all on one line), I have just deleted the static f...
70,189,596
70,192,178
Optimal access of NUMBER(14) column via ODBC instant client 32-bit driver
I am working on an application written in C++ that uses the 32-bit Instant Client drivers to access an Oracle database. The application uses the Record Field Exchange (RFX) methods to update the columns in the database tables. The database schema cannot be modified. The C++ code was originally written to handle OID val...
We actually went with the "Convert all the OIDs to Strings in the C++ code" option. It turns out the database was still able to run an indexed search after converting the OIDs from Strings to integers. It would have been better if we switched ODBC driver to one that could handle BigInt, but that wasn't really an option...
70,189,675
70,189,877
Problem with union containing a glm::vec2 (non-trivial default constructor)
I have a the following struct: struct Foo { union { glm::vec2 size; struct { float width, height; }; }; Foo() = default; }; If I create an instance of Foo with new, I get the following error: call to implicitly-deleted default constructor of 'Foo' Note that I've read a few answers on ...
At most one non-static data member of a union may have a brace-or-equal-initializer. [Note: if any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), th...
70,189,912
70,190,279
C++ how to display text in child window at real time
This application creates a child window (which is the white box) when I right click anywhere, and destroys the child window after another right click. I have implemented the mechanics to expand and shrink the red rectangle through Direct 2D. I would like the child window to display the width and height of the rectangl...
Since you are using a Win32 LISTBOX control as the child window, then you have a couple of options for displaying the rectangle's dimensions in it: give the ListBox the LBS_HASSTRINGS style, and add 1-2 items to it. Then, any time you change the rectangle, send LB_DELETESTRING and LB_ADDSTRING messages to the ListBox'...
70,189,974
70,190,032
Beginner quesiton memory allocation c++
I'am currently learning c++. During some heap allocation exercises I tried to generate a bad allocation. My physical memory is about 38GB. Why is it possible to allocate such a high amount of memory? Is my basic calculation of bytes wrong? I don't get it. Can anyone give me a hint please? Thx. #include <iostream> int...
Many (but not all) virtual-memory-capable operating systems use a concept known as demand-paging - when you allocate memory, you perform bookkeeping allowing you to use that memory. However, you do not reserve actual pages of physical memory at that time.1 When you actually attempt to read or write to any byte within a...
70,190,066
70,192,893
How to run Redis sadd commands with hiredis
My code contains a head file redis.h and a c++ source file redis.cpp. This is a demo of sadd opeaion in redis. All the operations fail, becase of WRONGTYPE Operation against a key holding the wrong kind of value. I don't know what happened. Please give me some suggestions. //redis.h #ifndef _REDIS_H_ #define _REDIS_H_ ...
WRONGTYPE Operation against a key holding the wrong kind of value This means the key, i.e. names, has already been set, and its type is NOT a SET. You can run TYPE names with redis-cli to see the type of the key. Also, your code has several problems: redisConnect might return null pointer you did not call redisFree ...
70,190,329
70,205,412
Adding a toolbar to wxWidgets is generating a strange result
I'm trying to accomplish a very simple task, add a toolbar to an app. I tried the most simple thing I could come up with, but the result is kind of strange, and I was wondering if this is suppose to behave this way or if I'm missing something. The code is below, note that I even tried to use a native image(commented), ...
This is how toolbars work in recent macOS versions and wxWidgets is all about using the native UI, so this is most definitely a feature and not a bug, as this is how the native apps look too -- just look at Finder, for example.
70,190,368
70,190,581
Find element in a vector with previous and next element equal to 0
I want to go through a given vector of integers and find an integer which the value of the next and previous integer are 0. #include <iostream> #include <vector> using namespace std; int main() { vector<int> sample = { 0,3,0 }; for (int i : sample) { if (sample[i - 1] == sample[i + 1] == 0) ...
In a range-for loop, i is set to the value of each element in the array. It is NOT set to the index of each element, as you are currently assuming it does. You need to use an indexed-based loop instead: #include <iostream> #include <vector> using namespace std; int main() { vector<int> sample = ...; if (sampl...
70,190,651
70,190,778
saving a lambda expression as parameter/variable inside a class to another class
I made a class and a struct. The class is named Learning and the struct is named Action. My Action constructor takes one parameter: object's function, and the function is a std::function<int(int)>. This is my Action struct: typedef std::function<int(int)> func; struct Action { // constructor Action(func); ...
You define Learning::addAction(Action&) with an action reference as argument. This means that you have to ensure the lifetime of the referenced object, and not let it get destroyed by going out of scope. But then you call it on an rvalue // Action(...) immediately goes out of scope robot.addAction(Action("Up", [](int...
70,191,042
70,191,520
Call a member function with the same name as macro
Consider the following: struct S { void f() {} }; #define f 42 int main() { S s; s.f(); // error: expected unqualified-id } How to call a member function S::f without undefining the macro f or changing member function name? Is it even possible? If the macro was defined as #define f() 42 (with parentheses...
How to call a member function S::f without undefining the macro f or changing member function name? Is it even possible? It isn't possible in standard C++. Problems such as this are the reasons why everyone recommends avoiding macros, and to separate the naming conventions between macro and non-macro identifiers. In ...
70,191,320
70,191,558
Call the destructor of a template class, expected class-name before ‘(’ token
I have an exceptional situation where I need to call the destructor of a class to clear union memory. We can not use an std::variant yet. The class in the union is template based and defined similar to: template<class TYPE> class BaseTemplate { public: BaseTemplate() = default; ~BaseTemplate() = default; ...
variableX's destructor is called ~BaseTemplate(). However, if X is in scope and resolves to BaseTemplate<int>, it will also work as an alias for the destructor. If X was not in scope: some::random_namespace::X variableX; // variableX.~X(); X not in scope, will not work variableX.some::random_namespace::X::~X(); // ...
70,191,692
70,191,791
Using '|' (pipe) operator with std::views does not compile
After a career diversion, I am trying to get up to speed with std::views (and functional programming in general). I am using the '|' (pipe) operator with std::views::filter on a vector, and I am puzzled why some code structures compile and others don't. This code creates a vector of vectors of int, then filters them by...
This is passing an lvalue vector into filter: vecs | views::filter(sumFilter) whereas this is passing an rvalue vector into filter: buildMultiples(nums) | views::filter(sumFilter) The current rule, which compilers implement, is that range adaptor pipelines cannot take rvalue non-view ranges (like vector, string, etc....
70,191,997
70,192,120
Is there a solution to override an argument in C++?
I just found something that I cant understand. I have a function that I want not only run in main(), but to use it in another function (for edit file) and I dont want to create an extra global variables. int fileOut(bool = 1, char filename[] = 0); //... int fileOut(bool output, char filename[15]){ cin >> filename...
In a function parameter, char filename[15] is actually treated by the compiler as simply char *filename, which you are defaulting to 0, aka NULL/nullptr. So, if the caller doesn't provide a buffer for filename, it won't point anywhere useful, so you can't write data to it, hence the crash. In that situation, you can u...
70,192,113
70,192,237
How to call macro that uses token pasting?
I am trying to print ffmpeg version in a C++ program. I see that in the /libavutil/version.h there is AV_VERSION which should tell the version number in the format x.x.x. As a test I used some random numbers as function parameters like this: std::string version = AV_VERSION(3,4,2);. The same error I get if I use LIBAVU...
You need to use a stringize expansion. Because of how the preprocessor works, this involves two macros: #define STR(x) #x #define XSTR(x) STR(x) The macro STR will take whatever parameter you give it and make that a string literal. The macro XSTR will first expand its parameter x and the result will be the parameter ...
70,192,151
70,192,204
How to call overridden child methods in a vector
I am trying to loop over multiple different child classes of a parent. Ideally I would like to save the child objects in a vector of smart pointers. The following outputs "Update idle" for every call to the method Update. I would like for the call to be the overridden variants of the method. What is the best way of sol...
std::make_shared<T>(args) creates an new instance of T, passing args to T's constructor, and then returns that instance in a std::shared_ptr<T>. As such, your code is not dynamically creating any Foo1 or Foo2 object for the vector at all. It is creating 3 dynamic Foo objects, all of which are copy-constructed from tem...
70,192,381
70,192,498
Can I run a python script from C plus plus?
I made a basic C++ script that looks like this. #include <iostream> int main() { std::cout << "Hello World!" << std:endl; } I complied this and named that complied file pcpp. Next, I made a python script named runcpp. This looks like this. import os com = 'sudo stdbuf -oL ./pcpp' os.system(com) Then, when I run ...
If you just intend to run a Python script from C/C++ you could simply use system() to execute the Python script like system("./myscript.py"), which will use the interpreter specified in the shebang. This means say you have the script: #!/usr/bin/python3 print("Hello!") It will run the script using /usr/bin/python3 as...
70,192,457
70,192,528
Initialize 2D array in constructor of CPP class
I was wondering what the best way to initialize a 2D array in a cpp class would be. I do not know its size until the constructor is called, ie, Header file contains: private: int size; bool* visited; int edges; int** matrix; Default constructor (right now): Digraph::Digraph(int n) { int rows = (n * (...
matrix = new int[rows][2]; is not valid syntax. Allocating a 2D sparse array requires multiple new[] calls, eg: private: int size; bool* visited; int edges; int** matrix; int rows; int columns; ... Digraph::Digraph(int n) { size = n; edges = 0; rows = (n * (n-1)/2); columns = 2; m...