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
67,928,979
67,929,393
Does a detached thread keep its captured shared_ptr alive?
If I have a shared_ptr that I copy into a std::thread, detach the thread, and then I destroy all other copies of the shared_ptr, can I expect the detached thread to continue to have a live copy of the shared_ptr? For example if I have: { std::shared_ptr<Foo> my_foo = std::make_shared<Foo>(); std::thread soon_de...
Does a detached thread keep its captured shared_ptr alive? Yes. The lambda - and thus also the captures of the lambda - will stay alive as long as the thread is executing. Same would also apply to args passed into std::thread. we're deleting our own handle to the std::thread at the end of the scope The std::thread ...
67,929,121
67,929,429
thread_local static variables in a dynamic loaded library – when are they created?
cppreference states the following on thread_local variables The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. I think of using a thread_local static member ...
What cppreference says is paraphrased. What's actually in the standard is All variables declared with the thread_local keyword have thread storage duration. The storage for these entities lasts for the duration of the thread in which they are created. There is a distinct object or reference per thread, and use of the ...
67,929,402
67,929,648
Find the island from left, right, top and bottom in c++ in a matrix
I have been trying for some time now, but i can't figure it out. I have to make a program where in a matrix, it finds the top, bottom, left and right numbers and prints them out. I made it where it prints the bottom, left and right numbers but can't figure out how to print the top one. #include <iostream> using namesp...
The for-loop is extremely unnecessary. If you already now the numbers of column and row, the midpoint can easily be calculated: #include <iostream> const unsigned int maxn = 10; int a[maxn][maxn]; int main() { int row,col; std::cin>>row>>col; for(int i = 0; i < row; i++) { for(int j = 0; j < ...
67,929,680
67,929,846
how to remove duplicates of a vector of structures c++
I have the vector movements vector<posToMove> movements; posToMove is a structure: struct posToMove { int fromX; int fromY; int toX; int toY; }; I want to remove the duplicates that are in movements, how do I do that?
The simplest way is to use : movements.erase(std::unique(movements.begin(), movements.end()), movements.end()); But std::unique only removes consecutive duplicated elements, so you need to sort the std::vector first, by overloading < and == operator: struct posToMove { int fromX; int fromY; int toX; in...
67,930,515
67,932,157
How to address Gmock with Symbol not found error?
I was trying to make a minimal gmock test case from donsoft.io's example The file structure is simple: my_workspace/ ├── BUILD ├── WORKSPACE ├── coinflipper.cc ├── coinflipper.h ├── mockrng.cc ├── mockrng.h └── rng.h I got this error while trying to compile by $ bazel test --test_output=all //:mockrng $ bazel test --...
The definition part for Rng::~Rng() is missing, a slightly fix will work: #ifndef RNG_H #define RNG_H class Rng { public: virtual ~Rng() {}; virtual double generate(double min, double max) = 0; }; #endif By the way, what version of the compiler are you using? A modern compiler will give us explicit error message:...
67,930,683
67,931,088
memcpy in C++ doesn't copy u_int32_t to unsigned char*
I'm with a problem when using memcpy function. I need to create an array of unsigned char with three parts: id, size of data array, data array. But I couldn't do nor the first part yet. #include <cstdlib> #include <cstdio> #include <cstring> #include <iostream> #include <vector> #include <string> int main() { ...
5 in ASCII is not printable since it's a control character. ASCII Table You can try below and it will print a as expected. OID = (u_int32_t)'a';
67,930,947
67,945,547
Is there an event mask I can set in Xlib to receive an event whenever a window title is changes
I'm writing a window manager in C++ (mostly c stuff but i need unordered_map) with Xlib and my current approach to updating window titles is to get window titles whenever it receives any unrelated event. The problem with this is that if I open XTerm, for example, the titlebar says "xterm" until I do something that send...
The client should set _NET_WM_NAME application window property. If you want to get events when application updates this property you can set PropertyChangeMask on the application window. Mask value is 0x400000.
67,931,082
67,931,310
A better understanding of named constructors idiom
I want to make a angle class to be initialized in radians or degrees and I want to return the value and not the Angle object. I found out that named constructors would probably the most efficient way to do this but I am not a 100% sure how I would modify for my case. #pragma once #define _USE_MATH_DEFINES #include <cma...
Your Angle class lacks an invariant. That is to say, there is nothing that can be said to be true about an arbitrary object of the Angle class beyond "it contains a double". Consider this: If I write the following function: void do_something(Angle delta) { // do something } How am I supposed to work with delta if it...
67,931,458
67,941,469
Emacs company mode doesn't support auto completion for c++ STL functions
I want emacs to autocomplete std functions such as push_back of vector #include <vector> using namespace std; int main() { std::vector v; v.push_back(3); } However, company mode seems don't support this, when I type v. and hit , push_back and other vector functions not show up in the popup. My company mode confi...
Assuming you've installed the irony-mode-server, try M-xirony-cdb-menu. If that shows no compilation database, there are a few options to tell irony where to look for includes (discussed in the documentation). Irony will provide completion based on sources found in the compilation database. Of those options, I use a ...
67,931,628
67,931,937
Access inner class private variable in outer class
//In file1.hpp class A { protected: class B { public: B () {}; }; }; // In file2.hpp class C { public: void getValue() { D obj; ---- error: no matching function for call to D printf("%d\n",obj.c); } class D : public A::B { friend cl...
Let take the following example: #include <iostream> //In file1.hpp class A { protected: class B { public: B () = default; }; friend class C; // <-- bad idea }; // In file2.hpp class C { public: void getValue() { // Creating an object E? E objE; // Acc...
67,931,764
67,931,818
output is not as expected it should print 12 not 102
output should be 12 not 102 why is it not deleting all the zeros #include<bits/stdc++.h> using namespace std; int main() { string s="10002"; for(int i=0;i<s.size();i++) if(s[i]=='0') s.erase(s.begin()+i); cout<<s; }
It’s skipping a value because the loop counter gets incremented even when you erase characters. You need to decrement i when you erase a 0 if (s[i] == 0) { s.erase(s.begin() + i); i--; }
67,931,825
67,936,773
Cannot convert from initializer_list to my type, which has templated variadic constructor
So, this isn't really something I have to do, I was just playing around. I wrote a Vector class for vectors of any numeric type and any number of coordinates. It is used as Vector<NumericType, [num of coords]>. Here is the code: #include <array> #include <functional> namespace World { template <typename NumType, unsi...
In Convert, you have the parameter pack Is which you'd like to use in conjunction with callback and values. Parameter pack expansion "expands to comma-separated list of zero or more patterns", so this is what you'll get when used with the values in your question: Is... 0, 1, 2 values[Is]... => values[0], values[1], va...
67,932,084
67,932,175
Check if sum possible in array
Given an array of N nonnegative integers and a target sum, check if it is possible to obtain target by choosing some elements of the array and adding them up. (An element can be chosen multiple times). I tried to come up with a brute force recursive solution. My idea is that for each element, we have 3 choices Include...
If the array has a non-positive number (such as zero) in it, your solution will never stop iterating.
67,932,147
67,932,385
Removing a specific element from a string in C++
I was trying to remove X from a given string, the code compiles and runs but there is no output shown. I guess the problem is where I have to use the 'cout' operator. Here is my Code: #include<iostream> #include<bits/stdc++.h> #include<string.h> using namespace std; void removeX(char str[]) { if(str[0]='\0') ...
You have a few issues in your code, the ones I can spot right away are: if(str[0]='\0') - this is an assignment, not a comparison. Your entire string will be replaced with \0-characters - no characters will be skipped because this: if(str[0]!='x'||str[0]!='X') is always true. Ask yourself if x is different from x (fals...
67,932,393
67,932,753
Error: cannot convert argument 1 from 'Packaged_Task::<class_name>' to 'std::nullptr_t'
The following program seems to be an error associated with an explicit constructor. However, I'm unable to find that out. Using Visual Stduio 2017, the following error comes up on build: C:/data/msvc/14.28.29333/include\future(475): error C2664: 'std::function<_Ret (int,int)>::function(std::nullptr_t) noexcept': cannot...
packaged_task needs to be able to call SumUp::operator() so that needs to be public not private: class SumUp { public: int operator()(int begin, int end) { cout << "SumUp(" << begin << ", " << end << ") ..." << endl; long long int sum{ 0 }; for (int i{ begin }; i < end; i++) { ...
67,932,665
67,937,773
Does `std::any_cast<T>` require `T` to be constructible even when asked for a pointer?
I want to std::any to contain std::vector<std::unique_ptr<T>>. class Foo { public: Foo() = default; ~Foo() = default; Foo(const Foo&) = default; Foo(Foo&&) = default; Foo& operator=(const Foo&) = default; Foo& operator=(Foo&&) = default; virtual void bar() = 0; }; void f() { using std::any; using st...
std::any uses type-erasure techniques. And that means that whatever requirements are imposed on the erased type must be detected at the time when you erase the type. This is different from a template type, where it can assess the requirements when you invoke a function that actually uses those requirements. So even if ...
67,933,360
67,934,343
Linux Debian 10 how to use c++ 20
Well unluky as I am i had to a hard drive crash and had to reinstall my Linux. I tried to use vs studio code with C++20 but he does not recognize it. Below is my config. { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++-10 build active file", ...
Blockquote If you're compiling C++ you need to invoke the compiler as g++ not gcc. Otherwise it links with the C runtime libraries resulting in the undefined symbol errors you're seeing. – G.M. 17 mins ago Thats it! Thanks! What a mess, the moment you do it the right way it suddenly works.
67,933,544
67,933,678
How to insert class objects to map correctly without pointers?
this is my code: LoggedUser.h #pragma once #include <string> using std::string; class LoggedUser { private: string m_username; public: LoggedUser(string username); string getUsername() const; bool operator==(LoggedUser loggedUser) const; }; Room.h #pragma once #include <LoggedUser.h> #include <string...
In the m_rooms[roomData.id] = Room(roomData, loggedUser); statement you use the std::map::operator[], which... ...returns a reference to the value that is mapped to a key equivalent to (requested) key, performing an insertion if such key does not already exist. Thus, we may use the operator only if the mapped_type ha...
67,934,345
67,934,685
how to return a dictionary from a function in cpp
I have this code #include <map> #include <tuple> int test(int x, int y){ std::map<std::tuple<int, int>, std::string> test_1; std::tuple<int, int> test2; test2 = make_tuple(x,y); test_1.insert<std::pair<std::tuple<int, int>, std::string>(test2, "string"); return test_1; } Error: 'return': cannot conver...
You want to return std::map<std::tuple<int, int>, std::string> but you have written the return type as int. #include <map> #include <tuple> std::map<std::tuple<int, int>, std::string> test(int x, int y){ std::map<std::tuple<int, int>, std::string> test_1; std::tuple<int, int> test2; test2 = make_tuple(x,y); ...
67,934,623
68,124,637
call c/c++ DLL from Java in Eclipse IDE
I want to call this minimal dummy C program (named "TEST.c"): extern "C" void Java_TEST_run() {} from this Java code (named "Example.java"): public class Example { public static void main(String args[]) { System.out.println("START"); TEST test = new TEST(); test.dll_call(); Sys...
I was able to resolve the issue with Eclipse. The C/C++ code needs to include the name of the Eclipse project, e.g. "Example", in the function name. In above code, this means: extern "C" void Java_TEST_run() {} needs to be changed to: extern "C" void Java_Example_TEST_run() {}
67,934,678
67,935,128
Array of class holding an array memory layout
If we have a class which holds an array, let's call it vector and hold the values in a simple array called data: class vector { public: double data[3]; <...etc..> }; Note: called as vector is for clearer explanation, it is not std::vector!!! So my question is that, if I store only typedefs near this array inside...
Mostly, yes. The standard doesn't promise that there never is anything after data in the representation of a vector, but all the implementations that I know of won't add any padding in this case. What is promised is that there is no padding before data in the representation of vector, because it is a StandardLayout typ...
67,934,693
67,935,100
How can I use struct efficiently in my quiz?
I'm trying to create a simple quiz with struct. But my program here is very repetitive. How can I modify it and make it more efficient? Especially to check if the answers are correct I do not want to declare a separate variable and store it as int correct. Thank You. #include <iostream> using namespace std; struct Qui...
That's as much as non-repetitive as I can imagine after a few minutes of thinking. Maybe it can become smaller, but for my taste this looks alright. You basically rely on std::vector class, instead of a typical array, because vectors can be of dynamic size. This allows us to use only one struct, but make as many answer...
67,934,711
67,934,895
Is the assignment operator inherited or not?
I know that the assignment operator is not inherited by derived classes, instead the compiler will create a default one if it is not redeclared. But I do not understand why the output of the following code snippet is Base operator=: #include <iostream> using namespace std; class B { protected: int h; public: ...
The generated assignment is "all the base assignments, in order of inheritance declaration", so your generated assignment is essentially D& operator=(const D& d) { B::operator=(d); return *this; } If you were to derive from both B and C - in that order; class D: B, C - it would be equivalent to D& operator=(co...
67,934,757
67,938,852
Qt. signal linked to slot of latest object
I am creating multiple object of type QWidget_WindowContact at runtime. When I click the Increment or decrement buttons the value in the last generated object gets updated and not the value in the same object. I am struggling to properly link the signals and slots, so that when multiple objects of the same type are gen...
You have QSpinBox* counter; as a global variable, which changes its value every time new QWidget_WindowContact is created. This piece of code: void QWidget_WindowContact::on_btnInc_clicked() { counter->setValue(counter->value() + 1); } is using this global variable, which is always the pointer to the most recentl...
67,934,821
67,946,712
Converting enum into String using QMetaEnum
I have searched a lot for this topic and already found some approach but I get some errors I can't find the reason of it. Idea is to read the keys from the enum with QMetaEnum to fill the strings in a combobox later. I have already the enum and also setup Q_Object and Q_Enum Macro in the class where the enum is. But I ...
I found the answer of my Question. As i was researching about this vtable issue i've found this post. C++ - Undefined reference to `vtable and i have given it a shot and removed Q_Object macro from the class. Then both errors disappear Edit: This does not solve it! But you can find the solution here: QMetaEnum does not...
67,935,081
67,943,064
how to allocate memory foe generic class without having a T()
I have a class and I want to write a generic sorted list that we can use it with that class: class A { int n; public: A(int n):n(n){} }; and this how I thought to do my sorted list class template <class T> class SortedList { T* data; int size; int max_size; void expand(); static const int EXPAND_RATE=2;...
does anyone have any Idea how can I write the sortedlist class without needing the A()?? Option 1: Allocate memory for each element separately. In other words, use a node based data stucture such as a linked list. Option 2: Separate allocation of memory from creation of the object. This can be achieved by using std...
67,935,597
67,938,568
Mouse in Maze - Stacks (but count steps also)
I am reading Adam Drozdek's book on DSA, and in solving the mouse in maze problem, he is using stacks. But how would I (if i wanted) count the number of steps the rat takes ? Because according to his stack solution , false positive neighbors (ie. the neigbors that failed to reach destination) also get marked, and there...
With a little change to the algorithm, you're left at the end with the path on the stack: exitMaze () push start cell on the stack while stack is not empty let currentCell = top cell on the stack mark currentCell as visited; //it might already be marked, but that's OK if currentCell is e...
67,935,865
67,936,235
How to overload operator "<<" to output integer values in one case and char values in another case?
std::ostream& operator<<(std::ostream& ostr, const Vector& right_hand_side) { for (int i = 0; i < right_hand_side.size; ++i) { // Printing array integers ostr << right_hand_side.array[i] << " "; } ostr << std::endl; return ostr; } I have a custom vector class. It works well, but on...
If Vector only stores ints, then you only have ints to output. I think your instructor is asking for you to have a Vector_int class that holds ints and a Vector_char class that holds chars, and basically identical implementations. Aside: I'd recommend going through your existing implementation, and changing all uses of...
67,935,905
67,936,144
Define type of variable with its own constant values
I want to create a new type of variable which has his own constant values. So I want to do something likes this: (This is a not working example to explain the idea) class Variabletype { public: static const uint8_t Option1 = 0; static const uint8_t Option2 = 1; }; typedef const uint8_t Variabletype; int main() { ...
What you are looking for is an enumeration type – designed specifically for the purpose you outline. Although you can use a plain, 'C-style' enum, a more modern, C++ approach is to use a so-called "scoped enum"; see: Why is enum class preferred over plain enum? Here's a possible implementation of your code using such a...
67,936,351
67,936,504
C++ - Overriding Virtual Templated Member Functions
In this example: class MyClass { public: MyClass(int i); }; template<typename T> class Base { public: virtual std::unique_ptr<T> createObj() { return std::make_unique<T>(); } }; class Derived : public Base<MyClass> { public: std::unique_ptr<MyClass> createObj() override { retu...
You misinterpreted the error. The error message is: In file included from <source>:1: In file included from /opt/compiler-explorer/gcc-10.3.0/lib/gcc/x86_64-linux-gnu/10.3.0/../../../../include/c++/10.3.0/memory:83: /opt/compiler-explorer/gcc-10.3.0/lib/gcc/x86_64-linux-gnu/10.3.0/../../../../include/c++/10.3.0/bits/un...
67,936,620
67,936,686
Dynamic Array implementation in C++
I am trying to implement Dynamic Array using C++. However, my resize() function seem to not work properly. There are no errors or warnings. I did some research and tried to look at other implementations found on the internet but was unable to fix the issue. I put my code below. #include <iostream> class Array { privat...
In your resize method you copied over the existing elements from arr for (int i = 0; i < size; i++) { temp[i] = arr[i]; } But then later you 0 all of the elements out, effectively clearing the previous data for (int i = 0; i < capacity; i++) { arr[i] = 0; } Instead you likely just want to 0 the trailing new elements ...
67,936,870
67,936,974
Is std::string str(array.begin(), array.end()) adding the null character on its own?
I am very new to C++ and i was wondering if std::string str(array.begin(), array.end()) is adding a null character on its own at the end of the string? I looked up this reference but i could not figure it out. I appreciate your answers! Edit: I am using C++11 and I have an boost::array<u_int8_t> of uknown size. My goal...
Since C++11 std::string must contain a terminating null character. However, a null character in a std::string does not necessarily terminate the std::string. I hope it gets more clear with the following example: #include <string> #include <iostream> int main() { std::string x{"Hello World"}; std::cout << x.c_...
67,937,097
67,937,311
Ball to Ball Collision resolution Stick together
If have the following code which simulates a ball to Ball collision. My problem is, that the balls bounce against each other. I want to have the balls stick together like snow particles. Does anyone know how to do that? /** * Rotates coordinate system for velocities * * Takes velocities and alters them as if the coo...
void resolveCollision(Particle& particle, Particle& otherParticle) { float xVelocityDiff = particle.speed.x - otherParticle.speed.x; float yVelocityDiff = particle.speed.y - otherParticle.speed.y; float xDist = otherParticle.pos.x - particle.pos.x; float yDist = otherParticle.pos.y - particle.pos.y; ...
67,937,388
67,937,467
Not printing single word after whitespace
Hi I am solving a question of book C++ Primer by Stanley. The question is :- Write a program to read standard input a line at a time. Modify your program to read a word at a time. I have used select variable through which user can switch to desired output i.e whether to print a line or a word. The Line output is coming...
It's because of the while-loop. Remove it and the program work as expected. #include<iostream> using namespace std; int main() { char select; string line,word; cout<<"please enter w(word) or l(line)"; cin>>select; if(select=='l') { while(getline(cin,line)) { cout<<line; } } else ...
67,937,587
69,911,714
Cmake error at find packages to finish the build
I want to build easyhttp - https://github.com/sony/easyhttpcpp/wiki/Installing-EasyHttp#build-easyhttp and after Cmakeing , it doesn't find packages to finish the build CMake Error at /usr/local/lib/cmake/Poco/PocoConfig.cmake:29 (find_package): Could not find a package configuration file provided by "PocoNetSSL" wit...
The POCO Core library doesn't include the PocoNetSSL components. So they need to be installed additionally. With vcpkg run to list the different poco components available: ./vcpgk search poco You should get an output similar to this: poco 1.11.0 Modern, powerful open source C++ class libr...
67,937,703
67,938,271
Which implementation is better for code readability?
I have this code, which intention is just to initialize all zones to false: Zone per_zone; std::fill_n(per_zone.begin(), per_zone.capacity(), false); System per_system; std::fill_n(per_system.begin(), per_system.capacity(), per_zone); std::fill_n(m_pMemory->TrackingZonesShowingLogicalParcels.begin(), m_pMemory->Trackin...
I don't know if OP can make use of C++20 or not, but the general idea of being able to iterate over a deeply nested hierarchy like this is precisely what std::ranges::join_view is for. Using it, you can separate the aggregation of the the target elements and the operation on the aggregated references as two distinct op...
67,937,747
67,937,903
Why does g++-11 '-O2' contain a bug while '-O0' is ok?
#include <limits> #include <cstdint> #include <iostream> template<typename T> T f(T const a = std::numeric_limits<T>::min(), T const b = std::numeric_limits<T>::max()) { if (a >= b) { throw 1; } auto n = static_cast<std::uint64_t>(b - a + 1); if (0 == n) { n = 1; } ...
b - a + 1 is clearly UB when the type of a and b are int and a is INT_MIN and b is INT_MAX as signed overflow is undefined behavior. From cppreference: When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined You are not converting to int64_t until aft...
67,937,796
67,937,990
No output produced in the c++ program
I want to write a program in c++ where consecutive elements in an array where each element in that subarray has value a[i] >= 100 are deleted and replaced by their length(of that subarray). This code does not produce any output. Can you help me find the error? Test case :- input - 2 100 120 3 output - 2 2 3 here consec...
This function is wrong: void removeElements(vector<int>& array, int start, int end) { array.erase(array.begin() + start, array.begin() + start + end); } The second argument of array.erase should be array.begin() + end. Adding start there is redundant compared with the usage of the function: removeElements(array, t...
67,938,170
67,939,025
Explicit conversion of templated functors to specific functors
I have a callable struct Foo defined as struct Foo { template <typename T> void operator()(T i) const { /* ... */ } }; and for reasons that are out of scope I would like to statically select which type to call it with avoiding the following cumbersome notation: Foo foo; foo.operator()<int>(0); foo.operator()<c...
Your assumption that there is extra overhead involved is not necessarily correct. Compilers are really good at optimizing things, and it's always worth confirming whether that's the case or not before spending time refactoring the code for what will amount to no benefit whatsoever. Case in point: struct Foo { templ...
67,938,196
67,938,253
Defining the amount of elements in an array
I was wondering if I do this: int TOPE , vector[TOPE] ; cin >> TOPE ; Does vector get the amount of elements I input or does it have a number that I can't control?
The variable vector is a Variable-Length Array (VLA). Standard C++ doesn't support that, but some compiler supports that as extension. The variable TOPE is not initialized at the point where the variable vector is declared, so its size is indeterminate. To set the size of VLA to the number entered, you should write lik...
67,940,935
67,941,159
Is it possible to convert Base& to Derived& without object copying or undefined behavior?
Problem: I have a class (PortableFoo) designed to be very portable. It contains a scoped class PortableBar. The surrounding codebase (call it Client A) requires both Foo and Bar to have a function that cannot be implemented portably, and Foo's implementation must call Bar's implementation. The following is a solution t...
You ran into one of the main reason why public member variables are a bad idea. If all access to the class goes through functions, overloading the accessors to return adapters that wrap a reference to the underlying member would be a transparent refactor, and would give you Mostly what you want. Like so: class Portable...
67,941,365
67,941,558
Is this overloading?
If I have two functions like this: int f ( int a ) {} void f ( signed a ) {} are they overloaded? When in main() I call f(5), I get an error: old declaration ‘void f(int)’
Type specifiers signed and int (used alone without other type specifiers) define the same signed integer type. That is you may equivalently write for example int a; signed a; signed int a; int signed a; So the functions in the question have the same parameter declaration. However they have different return types int f...
67,941,368
67,941,509
Retrieving information from a Base Class and overriding its own function returns error
class Package{ private: float weight; float cost; public: Package(float weight, float cost){ setNumber(weight, cost); } void setNumber(float weight, float cost){ this->weight = weight; this->cost = cost; } float ...
You have created a type Package that can only be constructed if a weight and cost is provided. Package(float weight, float cost){ setNumber(weight, cost); } You also create a type TwoDayPackage that is-a type of Package and has this constructor: TwoDayPackage(float fee){ setFee(fee); } This constructor is inv...
67,941,431
67,941,479
Can someone explain to me briefly what is std::streampos?
Can you show me some examples with std::streampos? I am not sure what it is used for and I don't know how to work with it. I saw in a project in github: std::streampos pos = ss.tellg(); where ss is std::stringstream. Why don't we use int pos = ss.tellg(), for example in this case?
Why don't we use int pos = ss.tellg(), for example in this case? Because std::streampos happens to be the type returned by std::basic_stringstream<char, std::char_traits<char>, std::allocator<char>>::tellg(). Maybe on one computer it's something that converts cleanly to an int, but not on another. By using the correc...
67,941,920
67,941,963
Circular reference of templates in C++
Consider something like this in C#: class C<T> {} class D : C<E> {} class E : C<D> {} Is an equivalent construction possible in C++ using templates?
Yes, you can forward declare E: template <typename T> class C {}; class E; class D : public C<E> {}; class E : public C<D> {}; or, as per Franks suggestion: template <typename T> class C {}; class D : public C<class E> {}; class E : public C<D> {}; Whether this works in your real case depends on whether C requires ...
67,942,072
67,942,130
`std::make_shared` fails for empty parameter pack
Background I have a variadic class template. template<typename... Ts> class Foo { public: Foo(Ts... values) { } }; Using this class, I can create objects with/without parameters. Foo<int> f1{1}; Foo<int, double> f2{1, 2.0}; Foo f3{}; I can even create a shared pointer. auto f4 = std::make_shared<...
The correct syntax is std::make_shared<Foo<>>() Foo<int,double> is a type, which is why std::make_shared<Foo<int,double>> works. The problem is that Foo, without the <> is a template, and is not a type, and results in a compilation error. Edit: The code Foo f3{}; is sort of a special case. In this case, your are usin...
67,942,354
67,942,892
Lambda vs. manually inlined code changes GCC's optimizer behavior
The following code: #include <vector> extern std::vector<int> rng; int main() { auto is_even=[](int x){return x%2==0;}; int res=0; for(int x:rng){ if(is_even(x))res+=x; } return res; } is optimized by GCC 11.1 (link to Godbolt) in a very different way than: #include <vector> extern std::vector<int> r...
It's a quirk of the code generation. There is no reason why the lambda version shouldn't be vectorized. In fact, clang vectorizes it as-is. If you specify return type as int, GCC vectorizes it too: auto is_even = [](int x) -> int { return x % 2 == 0; }; If you use std::accumulate, it's also vectorized. You can report ...
67,942,528
67,942,606
Circular reference of templates in C++, when complete types are required
Consider this example in C#: class C<T> { void greetMe() { print("Hello you"); } } class D : C<E> { void useE(E e) { e.greetMe(); } } class E : C<D> { void useD(D d) { d.greetMe(); } } Is an equivalent construction possible in C++ using templates? I don't have any useful C++ code to sh...
Extending from Not A Number's answer to the related question and embedding comments where I felt it was necessary: template <class T> class C { public: void greetMe() { } }; class E; // forward declare E same as answer to related question class D : public C<E> { void useE(E & e); // Passing by reference should...
67,942,624
67,942,829
my production code stopped compiling after moving to visual studio 2019
The following simple application demonstrates the compile error: My class declaration: MyClass.h #pragma once class MyClass { friend int MyCalc(); public: }; class definition: MyClass.cpp #include "stdafx.h" #include "MyClass.h" int MyCalc() { return 1 + 2; } The main function: ConsoleApplication1.cpp #include...
This is the clause, found in [namespace.memdef], that is causing the name MyCalc() not to be found inside main(), and it has been part of standard C++ for as long as there has been a C++ Standard. Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first...
67,943,040
67,953,814
LAPACKE C++ linking error. Unable to find function
I'm looking to use the LAPACKE library to make C/C++ calls to the LAPACK library. On multiple devices, I have tried to compile a simple program, but it appears LAPACKE is not linking correctly. Here is my code, slightly modified from this example: #include <cstdio> extern "C" { #include "lapacke.h" } // extern "C" { ...
I am compiling with: g++ -lblas -llapack -llapacke -I /usr/include main.cpp That command line is wrong. Do this instead: g++ main.cpp -llapacke -llapack -lblas To understand why the order of sources and libraries matters, read this.
67,943,453
67,943,493
MSVC Warning Number for -Wunused-label
What is the msvc warning number equivalent to -Wunused-label in gcc and clang?
-Wunused-label is C4102 in visual studio
67,943,471
67,943,588
std::copy for vector doesn't work properly
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> a{ 1, 2, 3 }; copy(a.begin(), a.end(), back_inserter(a)); for (const int& x : a) cout << x << ' '; } Output: 1 2 3 1 -572662307 -572662307 Expected output: 1 2 3 1 2 3 I have no idea why is t...
The problem is that as the vector grows, iterators you provided are potentially invalidated. You can fix that by using reserve. It is, in general, a good idea to use reserve if you know the size in advance so there are fewer allocations going on: #include <algorithm> #include <vector> int main() { std::vector<int> a...
67,943,716
67,947,127
How to clear label caption?
I am using label with OnCtrlcolor event: I have set the background color of the label to be the same as the form, if (iD == IDCmylabel) { pDC->SetTextColor(blue); COLORREF normal = RGB(245, 245, 245); pDC->SetBkColor(normal); return (HBRUSH)GetStockObject(NULL_BRUSH); } So...
NULL_BRUSH is a brush that instructs the system to turn any painting operations that use that brush into no-ops. Using it doesn't actually make the control transparent. It just appears to be transparent until (part of it) has been painted. If you want a control that has a particular background color, irrespective of th...
67,943,916
67,944,345
How can I create a vector with a maximum length?
I want to create a container that provides all of the same functionality as a std::vector but with the caveat that you cannot add anymore elements once the vector reaches a specified size. My first thought was to inherit from std::vector and do something like template <typename T, unsigned int max> class MyVector : pub...
How can I create a vector with a maximum length? You cannot do that with std::vector. You can however refrain from inserting any elements after you reach some limit. For example: if (v.size() < 10) { // OK, we can insert } I want to create a container that provides all of the same functionality as a std::vector...
67,944,163
67,944,297
C++ handle class abstraction
I am trying to abstract the explicit creation and destruction of raw handles with the usage of classes. The actual handle is stored as a private class member (so that the user doesn't interact with the lower-level details), which is created on construction and destroyed on destruction. Is there a design pattern of some...
Is there a design pattern of some sorts that could help achieve what the code below is trying to accomplish? Yes. It is called Resource Acquisition Is Initialization, or RAII for short. Your first attempt is in the right direction, but it is likely incomplete. A thing to potentially be concerned about is that typical...
67,944,631
67,944,723
How is a type that's forward declared in a function parameter list visible outside the function scope?
The following program compiles, which I find strange. void f(class s); using u = s; // ok, but why? s is a forward declaration of a class inside a function parameter list, and it seems to me it should not be visible outside the function scope. basic.scope.param seems the obvious place I would find this rule, but ...
To start with, this rule is not particularly new. It existed since C++'s inception, pretty much. As for C++20, it is written as follows: [basic.scope.pdecl] 7 The point of declaration of a class first declared in an elaborated-type-specifier is as follows: ... for an elaborated-type-specifier of the form class-key id...
67,945,174
67,945,208
Call function with argument Object& in c++
I want to hand over to a function a pointer to an object and then work with this in the function. However this somehow does not work. Please excuse if my nomenclature is not correct. I haven't worked with c++ for a while. Here is my code: #include <iostream> #include <array> #include <fstream> class Grid { public: s...
Try to use: // Create object. Grid g; Instead of: Grid g();// create object Or even something like: Grid *g = new Grid(); // Heap allocation. set_initial_conditions(*g); delete g; // Later manual memory release. Edit -- also replace your constructor's line: std::array<std::array<std::array<double,10>, 10>, 10> ch...
67,945,192
67,946,630
shared_ptr and unique_ptr constructor
When I use smart pointers, I always need to construct it with the factory functions, e.g. std::make_shared<T> and std::make_unique<T>, I don't use the constructor which takes a pointer because I try to avoid any usage/appearances of new. But my question is why C++ standard didn't include a constructor that takes argume...
It is basically to avoid ambiguities and confusion. Ambiguities arise because std::shared_ptr has over 10 constructor overloads and std::unique_ptr has also half dozen and lot of those are templates. So adding one that is meant to forward the arguments to managed object will either result with inability for compiler to...
67,945,508
68,330,523
Making a simple message box using C++/WinRT
I'm having trouble making a simple message dialog in C++/WinRT. Something as simple as "You clicked this: press ok to continue" nothing fancy. In the standard Windows API you can simply write MessageBox() and new popup will show up where you can click ok, and you can do somthing similiar in C++/CX with auto messageDial...
I was able to form a simple message dialog using this: winrt::hstring Title = L"Hello"; winrt::hstring Content = L"Some cool content!"; winrt::Windows::UI::Popups::MessageDialog dialog(Content, Title); dialog.ShowAsync(); Make sure to also include <winrt/Windows.UI.Core.h> so you can get access to the UI library. And ...
67,945,619
67,945,641
oredered_set not compiling in c++
I coded this statement and receiving compilation error. Code : #include<bits/stdc++.h> #define ll long long #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds ; template <typename PB> using ordered_set = tree<PB,null_type,less_equal<PB>,rb_tree_...
I suspect you have a file named c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\ext\pb_ds\detail\resize_policy\hash_standard_resize_policy_imp.hpp0000644. Rename that file to remove the 0000644 from the end of it.
67,945,806
67,945,860
Getting exception when calling std::call_once
I am trying a simple example to check the behavior of std::call_once(). I have tried the following code which doesn't do any useful work. class Test { private: std::string obj_name; std::once_flag init_flag; public: Test(std::string name) : obj_name(name) {} void Init() { std::cout << "Ini...
This is a really strange bug. I saw it both on GCC and Clang. Compile your code with -pthread and everything works. I don't know why come compiles and runs, but it does not works correctly. I was expecting that code does not link. If you add pthread, it works as expected.
67,946,562
67,947,340
Writing a function that detects a generic member
With C++20 it is now possible to write a template function detect_foo, which will return whether a template argument is a structure with a member called foo. Example: consteval bool detect_foo(auto&& arg) { if constexpr(requires { arg.foo; }) { // arg has a "foo" member return true; } else { // arg does...
You don't need a detect function, because you can just use requires. have M optional fields ... want to perform the same logic ... and only write that logic once The only way of passing around a "name of a member" that comes to mind is using a lambda (or a function) that returns said member: auto get_foo = [](auto &&...
67,946,835
67,946,855
About operator + overloading
I have the following code snippet: #include <iostream> using namespace std; struct Integer{ int x; Integer(const int val) : x(val){} friend Integer operator+(Integer& i, Integer& j){ return Integer(j.x + i.x); } friend std::ostream& operator<<(std::ostream& o, Integer i){ o << i.x;...
operator+ returns by-value, what it returns is an rvalue, which can't be bound to lvalue-reference to non-const, i.e. can't be passed to operator+ as argument for the next cacluation. Change the parameter type of operator+ to lvalue-reference to const, which could bind to rvalues. friend Integer operator+(const Integer...
67,947,031
67,949,302
Dijkstra's Algorithm in String-type Graph
I am making an inter-city route planning program where the graph that is formed has string-type nodes (e.g. LHR, ISB, DXB). It's undirected but weighted, and is initialized as: map<pair<string, string>, int> city; and then I can add edges by for example: Graph g; g.addEdge("DXB", "LHR", 305); g.addEdge("HTR", "LHR", 2...
The data structure used by a graph application has a big impact on the efficiency and ease of coding. Many designs start off with the nodes. I guess the nodes, in the problems that are being modelled, often have a physical reality while the links can be abstract relationships. So it is more natural to start writing a...
67,947,131
67,947,589
buffer cleaning in getline function
I understood that cin.getline() function doesn't clean the buffer and for example in the code below the program skip the line 4: char name[10]; char id[10]; std::cin >> name; std::cin.getline(id,10); std::cout << name << std::endl; std::cout << id << std::endl; the output (if I enter "Meysam" as name variable): Meysam...
In the first case, cin>>name does not consume the newline character and it is still there in the buffer. The fourth line is not skipped, instead cin.getline() reads the \n in the buffer and stops reading further as the default delimiter of getline in \n. As such the id only contains the newline character. In the second...
67,947,250
67,947,348
Goto label not defined c++
Why doesn't this goto work? After the player writes a number, it should boot them back to the main menu, instead, the compiler gives label MainMenu not defined c++ int main() { while (alive){ MainMenu: } } void InfoPanel(){ int choice; cout<<"1. Go back"<<endl; cin>>choice; if(choice==...
Your goto doesn't work because your label MainMenu: is not visible for Infopanel function as it`s defined in main and has scope visibility so it can be used just in main block.
67,947,276
67,948,030
QMetaEnum does not read keys from enum
why my code does not read my specified keys from my enum. The code itself compiles fine and the program runs without any runtime errors. Header file with the enum: #include <QMetaEnum> class Planet: public QObject { public: enum PlanetTypes { Barren,Gas,Ice,Lava,Oceanic,Pla...
You're missing an important thing: class Planet: public QObject { Q_OBJECT and should have non-empty vtable for class, e.g. at least ~Planet(); // can be empty but should not be inlined } Without Q_OBJECT or Q_GADGET macro the meta-object compiler (MOC) utility won't scan your class at all. So code generate...
67,947,699
67,947,759
Binary Operator Overloading in C++
The given problem: Use friend function for getting the private variable and operator overloading for calculating the total number of goals by each side of the team. I'm completely new to C++ and unable to figure out how to fix this error. What I've tried: Player operator-(Player &P1, Player &P2) { Player P; P.g...
Not passing Player as a reference in the operator solves the issue: Player operator-(Player P1, Player P2) { Player P; P.goal=P1.goal+P2.goal; return P; } As well as passing them as a reference to const: Player operator-(const Player &P1, const Player &P2) { Player P; P.goal=P1.goal+P2.goal;...
67,947,814
67,947,990
What does `decay_copy` in the constructor in a `std::thread` object do?
I am trying to understand the constructor of a std::thread but fail to understand how parameter types are represented/handled. Judging from cppreference, a simplified constructor could be sketched as follows: class thread { public: template <class Function, class Arg> thread(Function&& f, Arg&& arg) { ...
Std thread makes a copy (or move) into a decayed version of the arguments type. The decayed version is not a reference nor const nor volatile nor an array (arrays and functions become pointers). If you want an lvalue reference argument, use a reference wrapper. The called function in the thread ctor gets an rvalue ot...
67,948,757
68,241,940
Loading or building cuda engine crashes occassionaly after upgrading to TensorRT 7
I'm trying to run TensorRT inference in C++. Sometimes the code crashes when trying to build a new engine or load the engine from the file. It happens occasionally (sometimes it runs without any problem). I follow the below steps to prepare network: initLibNvInferPlugins(&gLogger.getTRTLogger(), ""); if (mParams.loadE...
Finally got it! I rewrote the CMake.txt and add all required libs and paths and removed duplicate ones. That might be a lib conflict in cuBLAS.
67,948,759
67,948,934
Unable to access static member from static function
I am using the below code snippet. #include <iostream> struct Entity { static int x,y; static void print() { std::cout << x << " Yoo -- ooY " << y << std::endl; } }; // int Entity::x; // int Entity::y; int main() { Entity::print(); return 0; } I get a compilation error on trying to...
You need to define storage for the static variables: #include <iostream> struct Entity { static int x,y; // <-- declares that variables exist somewhere static void print() { std::cout << x << " Yoo -- ooY " << y << std::endl; } }; int Entity::x = 0; // <-- defines storage int Entity::y = ...
67,948,799
67,949,925
Pi estimation using sphere volume
My task is to calculate the approximate value of pi with an accuracy of at least 10^-6. The Monte Carlo algorithm does not provide the required accuracy. I need to use the calculation only through the volume of the sphere. What do you advise? I would be glad to see examples of code in CUDA or pure C++. Thank you.
To be completely literal about it, you could use a Darboux integral to measure the volume of one octant of the sphere. This code sample measures the area of one quadrant of a circle of radius 2. #include <iomanip> #include <iostream> #include <queue> #include <vector> enum class Relationship { kContained, kDisjoint, k...
67,949,203
67,949,239
Cannot use initialization list on two overlapping structs
I want to use initialization list to initial the variable p1 to simplify things for me. But it's not happening please help. Code is almost self explainatory. struct word_t { int in; string word; int out; word_t(int i, string w, int o): in(i),word(w),out(o) {} }; struct para_t { std::vector<word_t>...
You need one more {}, i.e. para_t p1{ { { 0, "We", 10 }, { 11, "are", 14 } , { 15, "the", 18 } , { 19, "World", 22 } } }; // ^ ^ <- for para_t // ^ ...
67,949,591
67,949,623
Trouble to find size of an Array & Output issue
I'm implementing Binary search. But I don't want to pass the size of an array as an argument in the binarySearch function. I'm trying to find array size in function. I use sizeof operator, but the output of the binary search is wrong. when I try to pass the size of array as an argument then the output is fine. My que...
My question is why & what is the problem for calculating array size in function The problem is that arr is a pointer to an element of the array. The size of the pointer has nothing to do with the size of the array, which is why your attempted sizeof(arr) cannot work. The warning message also explains this quite well....
67,949,724
67,949,817
GLUT: How to Make Sphere with radius greater than 1?
I am trying to make a solar system using OpenGL for project. As I have other planets and moons too, I want to make my sun larger than radius=1, and my earth=1 since a little less than 0.18, the sphere is barely visible, and moons cannot be drawn with proper size difference. Below is my code, if I try to make a sphere w...
The sphere is clipped by the near and far plane of the viewing volume (Orthographic projection). Use glOrtho instead of gluOrtho2D and increase the distance to the near and far plane: gluOrtho2D(-5.0, 5.0, -5.0, 5.0); glOrtho(-5.0, 5.0, -5.0, 5.0, -5.0, 5.0); When using Orthographic Projection, the view space coordina...
67,949,905
67,950,105
overloaded << operator function : unresolved external symbol error
I've overloaded << operator to print the address in pointer member of a class. However, it throws the following error (using Visual Studio 2017). Using a normal class method does the job. Any leads? Error: error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl...
Your friend declares non-template operator. In this case, you can define a friend function inside of the class body, or try the following: template<typename T> class AutoPtr { // ... template<typename U> friend ostream& operator<<(ostream& out, const AutoPtr<U>& ptr); }; template<class T> ostream& operator<<(o...
67,950,436
67,950,636
Should I make a class polymorphic if only one of its methods should behave differently depending on the object's data type?
I have a class Group containing a vector of objects of another class Entry. Inside the Group I need to frequently access the elements of this vector(either consequently and in random order). The Entry class can represent a data of two different types with the same properties(size, content, creation time etc.). So all o...
is it worth it to make a class polymorphic just because of one only among many other of its method is needed to behave differently depending on the data type? Runtime polymorphism starts to provide undeniable net value when the class hierarchy is deep, or may grow arbitrarily in future. So, if this code is just used...
67,950,633
67,953,615
How to fix minimax algorithm
Required to write a minimax algorithm that returns a value from a array of random numbers, the length of which is 2 ^ depth(the algorithm works on a binary tree). my code: int minimax(int* scores, unsigned int left, unsigned int right, int depth, bool search_max_score, bool& move) { if (search_max_score) { ...
You have at least 2 bugs: Inside if (search_max_score) block you call minmax with false as the 5th argument, which is equivalent to making the search for max element becoming a search for min element, and then max again, etc. If you have an interval [left, right] and you want to halve it, the midpoint is NOT right/2 ...
67,950,671
67,950,731
lambda vs function object
The following code snippet doesn't compile because of the absence of copy ctor. template <typename Func> void print(Func f) { f(); } struct abc { abc() = default; abc(const abc&) = delete; abc& operator=(const abc&) = delete; void operator()() { std::cout << "f" << std::endl; } }; int...
Why does the following compile? Beacuse the lambda is copy-constructible. I thought lambda doesn't have copy ctor either. You thought wrong. Lambda closures are copy-constructible as long as they have no non-copyable value-captures.
67,950,930
67,951,006
C++ Blackjack code only going to first if statement
I'm trying to code a blackjack game and everything is going smoothly so far but for this bit. No matter what I input into hitStand it always goes to the first if statement and "hits". I would like for if "h" is inputted it "Hits" and if "s" is inputted it "Stands" and, if there is an invalid input, it will tell the use...
There are (at least) three errors in the single if (hitStand = "H" || "h") line! First, the = operator is an assignment, not a comparison; to test for the equality of two operands, you need the == operator. Second, the "H" and "h" constants are string literals - that is, multi-character, null-terminated strings of char...
67,950,978
67,951,107
How do I fix this calculator error in c++?
I'm new to programming and I came across this problem im not sure why the output is negative can someone explain? Edit: Thanks for the help! #include <iostream> using namespace std; int main() { cout << "Enter your first number " << endl; int num1; cin >> num1; cout << "Enter your second number" << endl; int...
Your issue is coming from this check if (yes == 1) { What you want to be checking for is a std::string instead. Since the inputted type is a string you need to take it as a string instead of a integer. Something like this should work for you: int main() { int num1 = 0, num2 = 0, sum = 0; std::string yes; std::cout <...
67,950,990
67,951,104
Calculate CRC for File(content)
I tried to create a program to create a crc sum for a file, based on its content. My intention is to compare this with a older value to see if content changed. I work on Linux (Debian). I tried this code below and it seems to work: FileInfo fi; fi.strPath=strPath_; std::ifstream input(fi.strPath, std::ios::binary); s...
The thing is, the value does not change. It's not supposed to. The filesystem::hash_value is a hash of the path to the file, not the contents of the file. If you want to compute a CRC of the contents of a file, you're going to have to read those contents and apply a CRC algorithm to them.
67,951,238
67,962,052
64 bits DLL c/c++ interface to Delphi
I have a .h file that I need to translate into Delphi, to call a DLL interface that is written in C/C++. In 32bit, everything goes well, I can use the DLL with a Delphi app with no issue. In 64bit, it does not work very well. I did not write this DLL interface, it comes from a third party that does hardware. namespace ...
Something like the following should work fine in both 32bit and 64bit: unit gXusb; interface type // prefixing types that Delphi already declares... _INTEGER = Int32; _INT16 = Int16; _CARDINAL = UInt32; CARD8 = UInt8; _REAL = Single; LONGREAL = Double; _CHAR = AnsiChar; _BOOLEAN = ByteBool; ADDRES...
67,951,291
67,951,777
cmake: how to pass a list of variables (from set) to code
I have been experimenting a bit with cmake recently and came across the project definition, where you can specify the name, version, description and languages. I then learned that you can pass this information to the code, to print for example when the program starts, with the following lines: add_compile_definitions( ...
I think a simple way would be to use a configure_file. Create a file: # authors.h.in #cmakedefine PROJECT_AUTHORS "@PROJECT_AUTHORS@" Then: $ cat CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(test) set(PROJECT_AUTHORS "fname1 lname1" "fname2 lname2") configure_file(authors.h.in ${CMAKE_CURRENT_BINARY_DI...
67,952,585
67,953,302
how is INT returned as INT& in c++?
am a c++ beginner and this code really confused me: int global = 100; int& setGlobal() { return global; } int &a=setGlobal() ; int main(void){ a=a+5; std::cout<<global<<std::endl; } The return type of setGlobal is int& , but global is an int. Please explain to me how does that work? Shouldn't it be r...
A return type of T& gets you the reference of the returned object of type T. In your case int& setGlobal() { return global; } returns a reference (int&) to global. Basically an alias, another way to access the same variable. This means that int &a=setGlobal() ; Sets a as a reference to global and any operatio...
67,952,602
68,103,650
SWIG LUA C++ wrapper
I am new to SWIG and I am trying some tutorials but running into compilation issues. The functions I am trying to wrap (ex.cxx) : #include <time.h> double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char ...
luaopen_example is defined in an extern "C" {} block in ex_wrap.cxx, but compiling ex.c with g++ declares luaopen_example as a C++ function, so the linker looks for a C++ mangled name to resolve luaopen_example(lua_State*) and not simply luaopen_example Change your declaration in ex.c to extern "C" { extern int luaope...
67,952,651
67,952,906
In-place modification of a vector member variable through a vector of user-defined class elements
Using Visual Studio C++ 2019 Why does this fail... std::vector<Cell> cells{ 9 }; std::vector<Cell*> cells_copy; for (Cell& cell : cells) cells_copy.push_back(cell); ...while this works? std::vector<Cell> cells{ 9 }; std::vector<Cell*> cells_copy; for (Cell& cell : cells) cells_copy.push_back(&cell); What I ...
Seems like you are confused with: for (Cell& cell : cells) ^^^^^^^^^^ vs cells_copy.push_back(&cell); ^^^^^ In the first one, Cell& cell, you are declaring cell as a reference. What that mean is anything that you do with the cell, will be applied to the original cell in your vector. However,...
67,953,091
67,959,919
How can I apply a custom theme?
I am using QtCreator to create a Qt Application in C++. I know CSS and making themes for elements in my applications isn't too hard, but is there a way to make a file and apply it? I've looked through the Qt Docs but I can't seem to find anything about such a thing. Currently, I am styling each individual button and st...
easy: you just create a file, e.g. style.myStyle there you place the styles for all the widgets including events, attributes etc then you load the file when the app starts and apply that to the app here is an example how: #include <QApplication> #include <QFile> int main(int argc, char *argv[]) { QApplication a(ar...
67,953,171
67,953,418
Use of std::forward with Eigen::Ref objects
I have a functor Foo defined as follows: struct Foo { template <typename _Vector> void operator()(const Eigen::Ref<const _Vector>&, const Eigen::Ref<const _Vector>&) { /* ... */ } }; I'd like to call it with either Eigen vectors, blocks, or Eigen::Ref, and _Vector can be any of Eigen vector types. ...
error: ‘Eigen::Ref<Eigen::Matrix<double, -1, 1> >&’ is not a class, struct, or union type ^ You need to std::remove_reference to make the version with perfect forwarding valid: #include <type_traits> template <typename T, typename U> void operator()(T&& x, U&& y) { ...
67,953,197
67,953,270
Safe way to construct a vector inside a loop and return it outside that scope?
I have a code sample, and I'd like to ask you to review this and tell me if my understanding is correct. I am learning C++, and so I apologize if these questions are rudimentary. I have read about how C++ handles memory management, but I haven't found practical examples. I am trying to write some myself. Code Sample: s...
The move semantics creates new objects. It is not a copy or assignment, it is a move-constructor that is invoked. Thus, if you call move(innerVector) you actually create a new vector object as entry in containerOfVectors. This automatically contains the content/data of the original innerVector at the moment you make th...
67,953,345
67,953,479
endl, '\t' and '\n' dont work after 15 tabs
If you compile and run this code, the endl doesn't get executed. You will get 0hello when you pop the terminal into full screen. #include <iostream> int main() { using namespace std; for (int i = 0; i < 15; i++) { cout << '\t'; } cout << "0" << endl << "hello"; return 0; } However, i...
I am assuming you are running this from visual studio where the default terminal width is 120 characters. A tab is 8 characters. 8x15 = 120. If you look at the output, there is a blank line before the 0. It is printing the tabs: just that you've reached the end of line so it has moved to the next line. If you change t...
67,953,494
67,953,817
Flex Bison Reentrant C++ Parser: yyscanner undeclared identifier
I'm attempting to create a reentrant parser using C++ with flex and bison. I'm also using a driver class Driver. I'm getting the error 'yyscanner' : undeclared identifier on the lex side of things. I think it has something to do with the reentrant option in flex, which is strange since I would have assumed that driver ...
If you generate a reentrant scanner, you must define its prototype to include a parameter named yyscanner of type yyscan_t. And you need to call the scanner with that argument. You cannot substitute some type you have defined for the yyscan_t argument, because your type does not include the data members which the flex-...
67,953,514
67,953,606
Two classes friending a member function from the other class
I've been trying to find a way to have two classes, where each class has a member function, and each member function is a friend of the other class. To illustrate: #include <iostream> class A; class B { friend void A::func_A(); // compiler error: invalid use of incomplete type 'class A' public: void func_B() ...
You can do something like this, though it's probably not worth the trouble. class B { friend class AccessorForAFuncA; }; class A { void func_A(); }; class AccessorForAFuncA { private: static void DoThingsWithPrivatePartsOf(B*); friend void A::func_A(); }; AccessorForAFuncA is a helper class that accesses pri...
67,953,800
68,051,662
Linking a MinGW library to a MSVC app with a C interface
I'm trying to link to the OpenAL soft library as compiled with the Media Autobuild Suite, and I'm getting the following error from Visual Studio: libopenal.a(source.cpp.o) : fatal error LNK1143: invalid or corrupt file: no symbol for COMDAT section 0xA My application is in C++ and compiled directly in Visual Studio 20...
I figured out what works for me, so I'll share. I was not able to link a static library between compilers as I originally attempted. My understanding is that the extra info kept in the lib to allow link-time code generation is compiler-specific. Brecht Sanders's answer outlines a few possible reasons why the code would...
67,953,956
67,954,121
Wifi from my esp32 M5 StickC plus does not work
I am trying to connect to my wifi using my M5StickCPlus. I use the platformIO framework. I am getting this error : error: invalid conversion from 'const char*' to 'char*' at compilation. Here is the code: #include "M5StickCPlus.h" #include <WiFi.h> const char* WIFI_SSID = "router"; const char* WIFI_PASS = "pass"; vo...
The WiFi.begin() function overload that takes two arguments (an SSID and a password) requires the first argument to be a non-const char* pointer (i.e. a pointer to a potentially modifiable char array, even if the function doesn't actually change it). A simple way around this (similar to the example given in the documen...
67,954,296
67,964,316
How to pass a variable to a template metafunction?
im currently trying to learn how to use template metaprogramming to write functional code in c++ Heres my attempt at a recursive fibonacci sequence generator template<int i, int x = 0, int y = 1> struct Fib : Fib<i-1, y, x+y> {}; template<int x, int y> struct Fib<0, x, y> { enum { value = x }; }; This seems to wo...
how to use template metaprogramming to write functional code in c++ You might be approaching the subject from a wrong angle. Metaprogramming involves writing instructions for how to write programs, reaching a level of abstraction beyond normal programming. (For more information, I recommend A: What is metaprogramming...
67,954,400
67,954,448
Call to deleted function 'addressof' in ctor/dtor
I don't know there is std::addressof available in c++ standard library until today I read some blog. In my understanding, if opeartor & is overloaded, then std::addressof should be used, otherwise it's not necessary to use std::addressof, it should be equivalent with &. However, just trying to use std::addressof, to va...
C++ standard: §9.3.2 The this pointer the keyword this is a prvalue expression std::addressof template <class T> const T* addressof(const T&&) = delete; So addressof overload for rvalues is deleted. The reason is because you cannot take the address of a prvalue so addressof is modeled to respect that. That's why y...
67,954,567
68,146,986
Converting an unruly dependency injection model with a service locator
I've been using DI for a game engine project for a while and I just hit a wall; given the below order of creation: The job system does not depend on anything and everything depends on the file logger. It makes sense to create the job system, then the file logger, then pass the created references for each dependency dow...
I ultimately went with the ServiceLocator pattern, deriving every subsystem that was a dependency as a Service: App::App(const std::string& cmdString) : EngineSubsystem() , _theConfig{std::make_unique<Config>(KeyValueParser{cmdString})} { SetupEngineSystemPointers(); SetupEngineSystemChainOfResponsibili...
67,954,621
67,954,966
How to write this macro in cpp that can return from the function
I'm using cpp variants to indicate error in my program, for example, I have a function like this: std::variant<Result, Error> do_foo(); std::variant<string, Error> do_bar() { auto v = do_foo(); if (std::holds_alternative<Error>(v)) { return std::get<Error>(v); } auto r = std::get<Result>(v); // do some m...
What you want isn't possible in portable C++. If you are using gcc or clang, you can use statement exprs. I really recommend you don't do this, but here is the answer to the question you asked: // Non-portable--you probably shouldn't do this #define bail(v) ({ \ auto _v = v; \ if (_v.i...
67,955,225
68,039,808
Gtkmm3: Handling command line options and Gtk::Plug properly
I'm trying to interface with the xfce4-settings-manager which I was successfully able to do in the standard c gtk+-3.0 libraries, but I've been struggling to replicate it in gtkmm3. xfce4-settings-manager passes a --socked-id option to the client, and the client is meant to use a GtkPlug to connect to the socket via th...
Here is an example similar to yours, in C++ with Gtkmm 3: #include <string> #include <gtkmm.h> #include <gtkmm/plug.h> // Simple command line argument parser. // // Documented here: // // https://gitlab.gnome.org/GNOME/glibmm/-/blob/master/examples/options/main.cc // class CmdArgParser : public Glib::OptionGroup {...