question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
66,572,969
66,573,217
How to access a function from a derived class from a base object
I have a vector array with an object and I have it filled with some of the same objects but also I have it filled with some objects that are derived from the base object. But I cannot get access to the functions on the derived object in the array. Is there away to get access to it? vector<BaseObject*> objects; if (type...
The following example demonstrates, how to use basic polymorphism: #include <iostream> #include <vector> class BaseObject { public: int var1; int var2; BaseObject(int var1, int var2) : var1{var1}, var2{var2} {} virtual void print() const { std::cout << "BaseObject{var1=" << var1 << ",var2=" <...
66,573,170
66,573,436
How to get system time in UTC format using chrono
I am trying to find the system time in UTC format using the chrono. I think the following program only gives me local time , please can some one help me out ? #include <iostream> #include <chrono> #include <ctime> auto GetSystemTime() -> uint8_t * { auto now = std::chrono::system_clock::now(); std::time_t currentTim...
If you're stuck with C++11 - C++17, you could use std::gmtime which "converts given time since epoch as std::time_t value into calendar time, expressed in Coordinated Universal Time (UTC)" and then std::put_time to format it the way you want. #include <chrono> #include <ctime> #include <iomanip> #include <sstream> std...
66,573,512
66,574,428
Boost convex hull with longitude and latitude
I am trying to use boost's convex_hull algorithm with longitude/latitude coordinates. From here: https://archive.fosdem.org/2017/schedule/event/geo_boost_geography/attachments/slides/1748/export/events/attachments/geo_boost_geography/slides/1748/FOSDEM17_vissarion.pdf I can see that we can calculate the distance betwee...
Yeah, though you may be right that a strategy /can/ be made, that is not implemented. A little side-by-side tester clearly shows that the strategy is not implemented for the geographical coordinate system: template <typename cs> void test() { using point = bg::model::point<double, 2, cs>; using polygon = bg::...
66,574,354
66,575,317
OpenGL Texture DSA not showing texture
I'm attempting to use the newer DSA functions to show textures but it's not working at all. Here is the code for using the older approach. unsigned int containerTexture = 0; glGenTextures(1, &containerTexture); glBindTexture(GL_TEXTURE_2D, containerTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);...
The 2nd parameter to glTextureSubImage2D is the level to be set. Mipmap levels are zero-based, therefore the base level is 0 and not 1 as in your code: glTextureSubImage2D(containerTexture, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
66,574,407
66,574,637
How do you create a POINT object in Win32?
I am trying to use the PtInRect function in Win32, which takes a POINT object. I have x and y coordinates, but I don't know how I create a POINT from those. I tried looking it up, but could only find this documentation, which does not contain the information I want. Thank you for your help.
Problem: You're creating trouble for yourself because of attempting to dynamically allocate the POINT object with malloc. BTW you do not always need dynamic allocation and to initialize any struct you do not need to use malloc as you pointed in the comments, you can just create the object directly. Solution: As tkausl ...
66,574,668
66,574,782
Shift position from the first to the last
I am trying to make a simple program that shift the position of the first to the last until a: 1 2 3 4 5 6 Looks like: 6 5 4 3 2 1 IDK why the second for doesn´t work. using namespace std; int main() { int x[6], a = 6, safe = 0; cout<<"Value"<<endl; for (int i = 0; i < 6; ++i) { cin>>x[i];...
Problems: x[a] access an element out of bonds during the first iteration, what itself is Undefined Behaviour. for (int i = 0; i != 2; ++i) does not make sense at all. Why the condition would be i != 2. Solution: Instead of making yourself a lot of trouble you can just reverse the array with std::reverse (Documentatio...
66,574,803
66,580,049
How can I change the color of a cylinder in opengl?
I want to draw one cylinder using OpenGL in Visual C++. I want to make the color of the cylinder red, so I add the following code in the renderCylinder function, but it doesn't change. glColor3f(1.0, 0.0, 0.0); Could you help me to solve this problem? The following codes are the full codes to make a cylinder for a tes...
You have lighting ON so glColor is ignored and material & light properties are used instead... To remedy that add this to your code near place where you enable light: glEnable(GL_COLOR_MATERIAL);
66,574,828
66,575,160
How to swap the first and last elements of a linked list
I am trying to swap the first and last elements of a linked list, but I have not been able to find a solution. My logic, or pseudo code, is to: set the second-to-last node's next to the first node. set the first node's next to a nullptr. set the last node's next to the first node. My current code is: void SingleList:...
Your logic has a flaw in its third point. set the last node next to the first node It should be. set the old last node as the new first node. Lets walk through your pseudo code. I assume first is a global pointer that points to the first node of your list. |200|50|300|25| ^ first after the while run the current p...
66,574,956
66,574,957
How can I use typeid with a template
I am trying to provide more type safety by checking what kind of type is passed into a template. Further, this affects the constants used in a computation (in this example machine-epsilon) My issue is typeid seems to emit some strange type in this case. // compile with g++ -Wall -g -std=c++14 #include <typeinfo> #inclu...
You are calling typeid on a type_info&, which is an object you already called typeid on. The solution is to replace your conditionals with the following. if (float_t == typeid(double)) { eps = mach_eps<double>; } else if (float_t == typeid(float)) { eps = mach_eps<float>; } else { std::cerr << "gamma: unsup...
66,575,860
66,575,976
definition of static variable inside a class member function
I am learning singleton design pattern and came across this piece of code class Singleton { private: static Singleton * pinstance_; static std::mutex mutex_; protected: static Singleton *GetInstance(const std::string& value); }; Singleton* Singleton::pinstance_{nullptr}; //can this lin...
No, they can't be removed but they can be moved to local static variables of the method. class Singleton { protected: static Singleton *GetInstance(const std::string& value); }; Singleton *Singleton::GetInstance(const std::string& value) { static Singleton* pinstance_{nullptr}; static std::mutex mu...
66,576,116
66,577,118
Alphabetically sorting the text file with mixed case in c++
I was trying to sort a file of 1000 unsorted mixed case words into alphabetical order. Example: Ancient absent Bow bar Cow cat ... Give the code below: #include <iostream> #include <string> #include <fstream> #include <cctype> using namespace std; void bubbleSort(string[],int); int main() { const int size = 1000; ...
if only first letter is uppercase, you can use this function: bool gt(string a, string b){ if(a[0] < 97) a[0] += 32; if(b[0] < 97) b[0] += 32; return a>b; } then. instead of this if (arr[index] > arr[index +1]) you put this if (gt(arr[index] , arr[index +1])) and this should work for you...
66,576,242
66,576,291
Are dynamic arrays actually dynamic?
I'm reading about dynamic arrays (specifically at https://www.learncpp.com/cpp-tutorial/dynamically-allocating-arrays/), and it seems to me that dynamic arrays are not actually dynamic, in that the size allocated for them cannot be changed. If I am understanding correctly, the main use or point of dynamic arrays vs fix...
"Dynamic" refers not to size, but to allocation method. In most C++ implementations there's several methods of storing data, but the two relevant here are local, as in on the stack, and dynamic, as in on the heap. Dynamic tends to mean "allocated with new" or a similar mechanism, while stack allocations happen implicit...
66,576,660
66,576,750
Why is my code giving me a memory error? c++
I am trying to create a mock item buy menu. I would really appreciate if anyone can tell me why my vector is returning -858993460 instead of the int value that I am trying to read into it through an array. I am trying to read it like an array and it is saying I have a memory issue. I am stuck. Here are the related vari...
Choice >> iLimit[i]; This doesn't do what you think it does, I think you mean iLimit[i] = Choice; the >> operator has been overloaded for string types (and cin, cout etc) to copy the value from one to the other. But this is not the case for ints, where >> is the bitshift operator. it doesn't modify any of the operand...
66,577,104
66,578,127
Error spotted in C++ Primer 5th Edition (copy intialization vs direct initialization)
Hi i am trying to understand how copy constructor works and looking at an example. The example is as follows: {//new scope Sales_data *p = new Sales_data; auto p2 = make_shared<Saled_data>(); Sales_data item(*p); // copy constructor copies *p into item vector<Sales_data> vec; vec.push_back(*p2);// copies the object to ...
Despite the poor choice of name, copy initialization is orthogonal to copy constructors. A copy constructor is any constructor whose first parameter is a lvalue reference to its class type, and can be called with just one argument. It's just a constructor that can initialize new objects from existing objects. That's pr...
66,577,188
66,577,599
create vector with new elements
so I have the following vector<vector< tuple<string, double>*>*>* graph; a 2d vector, with a tuple of string and double. I want to initialize the graph(2d vector) with a certain size and a new vector< tuple<string, double>*>, in each of the element of the big (outside)vector and I used the following line graph = new ...
Problem summary: In the line graph = new vector<vector<tuple<string, double>*>*>(67, new vector< tuple<string,double>*>()); constructor 3 of std::vector is used (reference) This will evaluate new vector<tuple<string,double>*>() once, then create a vector with 67 copies of this pointer. Solution: Don't use pointers unl...
66,577,323
66,577,550
How to name a memory location (C++)?
This is a question regarding pointers in C++. The diagrams that follow use the following representation: Let's say we have int* k = 1778. This is represented in the left diagram below. How do I name the memory location in k? This is marked by the question mark in the diagram on the right. I understand that if I write...
Variable names are not a property of the memory location. Those names are used by the program for accessing relevant memory locations. So that you cannot name a memory location in the physical memory (RAM). If you need to access the dereference(*) of the pointer k through a new name, please create a reference variable ...
66,577,615
66,578,849
Using MPI_Send and MPI_Recv instead of MPI_Gather
I want to compare the performance difference of MPI_Send and MPI_recv with MPI_Gather; so I'm trying to get the answer from this code without MPI_Gather, but the thing is it seems that the buffer of root is not updating. The code is: #include <fstream> #include <iostream> #include <vector> #include <string> #include "m...
The problem is that in: if (rank != root) { MPI_Send(x.data(), N, MPI_INT, 0, 0, MPI_COMM_WORLD); } every process will send N element of the x array to the process = 0, Then process 0 : if (rank == root) { for (int i = 1; i < size; i++) { MPI_Recv(single_arr.data(), N, MPI_INT, rank + i, 0, MPI_COMM_WO...
66,577,824
66,578,918
Smart Pointers compatibility with raw pointers
I am using a library that uses raw pointers. In my code, I use smart pointers. How do I make them compatible. For example, I have an object std::unique_ptr<Canvas> m_canvas; But a function call in library is f(..., Canvas* c,...); How do I pass m_canvas to f ?
If the function doesn't take ownership, you might use get(): f(m_canvas.get()); If the function takes ownership, you might use release(): consume(m_canvas.release());
66,578,050
66,578,442
I was attempting a problem online need assist as I am unable pass hidden test cases. Please point out fault in my code
Problem Finally, progress reached the Madoka family and she decided to play with her little sister in the sensational game Space Arrays. The rules of the game are as follows: Initially, a sequence a1,a2,…,aN is given. The players alternate turns. In each turn, the current player must choose an index i and increment a...
In your algorithm you don't check if first player initially loses without making a turn but the sum is lower than n*(n+1)/2, e.g. for input 1 5 1 1 2 5 5 The sum is 13. 5 * (5 + 1) / 2 - (1 + 1 + 2 + 5 + 5) == 1 But first player can't do anything and has lost before the first turn. Ssecond player wins. Actual output ...
66,578,966
66,584,713
Weird return value of C++20 requires expression
Consider the requires expression: constexpr auto b = requires { []{}; }; GCC pass the following two static_assert: static_assert(b); static_assert(!b); This looks extremely weird. I expect that the value of b should be true. Is this just a GCC Bug?
This isn't Schrödinger's Requirement: b should clearly be either true or false. The requirement here: constexpr auto b = requires { []{}; }; is a simple-requirement. We're just checking that if the expression []{} is a valid expression. And... it is! So b should just be true. This is a gcc bug (and doubly so with Stor...
66,579,052
67,372,572
Singleton in libfuzzer
Will singleton created in libfuzzer be "one instance per run" or "one instance per multiple runs"? Example: // singleton example int& Singleton() { static int a = 0; return a; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { // Usage example Singleton() += Size; } 1 run: Size = 1...
Late answer - there will be single instance per multiple runs.
66,579,140
66,579,251
SFINAE for types that don't have particular members
Why doesn't the following code compile and what is the most concise solution for enabling templates for types with particular members? Also it compiles if template variable is replaced with an expression, which is used to initialize it, directly. #include <iostream> template<class T> constexpr bool is_rect = std::is_s...
The problem is that is_rect<T> is always specified as template argument for std::enable_if_t as part of the signature of f(), and it's invalid expression when T doesn't have particular members. You can apply partial specialization to make is_rect gives true or false based on the type has particular members or not. e.g....
66,579,147
66,579,418
Failed to load font in SFML
if (!font.loadFromFile("sansation.ttf")) { std::cout << "Failed to load font "; return -1; } Here is my code when I try to compile I get this error: Failed to load font "sansation.ttf" (failed to create the font face) Failed to load font Program ended with exit code: 255 Can...
I realized I had to Select "Edit Scheme…" in the "Product" menu; Check the box "use custom working directory"; Fill the text field with the folder path containing your resources;
66,579,970
66,581,659
Using typedef void* within a .dll
I try to make a .dll from the Verialtor source code, since they've implemented this possibility. They use a common handler typedef void* svScope to initialize scopes. The .dll uses this handle aswell. Now I'm able to create new functions using __declspec(dllexport) svScope svGetScope( void ); Here's the header code svd...
You need to use XXTERN on a function delcaration. You're not showing us any actual source code that contains functions that must be exported, but let's imagine this: svScope foo(); This function will return a svScope, which is just a void *. If you want it to be exported you must mark it so with __declspec(export) (or...
66,580,004
66,580,292
implement a operator - function in vector c++
Hi I am trying to implement a operator - function for my vector class. The function should takes two pre-sorted Vectors called v1 and v2 which are provided as parameters to the operator. The operator function returns a Vector that has all the elements of v2 that are common in v1 removed from v1. For example v3 = v1 - v...
Instead of the O(n x m) solution you provided above you could do it with in a O(n + m), something like this: int i=0, j=0; while(i < v1.getCount() && j < v2.getCount()) { if(v1.at(i) == v2.at(j)) { i++; j++; } else if(v1.at(i) < v2.at(j)) { v3.push_back(v1.at(i)); i++; }...
66,580,320
66,580,412
Reverse Words in a String , I do not know why I am getting this output
class Solution { public: string reverseWords(string s) { int n=s.size(); string p; vector<string> arr; for (int i=0;i<n;i++){ p=p+s[i]; if (to_string(s[i]) == " "){ arr.push_back(p); p = ""; ...
std::to_string() is a function which converts a number to std::string. Since no number can ever be represented as " " (a string containing a single space), your condition is never true. Change your condition to if (s[i] == ' ') to compare characters.
66,580,460
66,580,726
Decreasing (Worsening) performance in C++ code
I need to add some artificial latency to my code without using std::this_thread::sleep_for() to test some hardware. In fact, I need a function like: addLatency(10m) // Do dummy computation for 10 milli second I know that one possible solution is by doing a dummy calculation like: long int j=0; for (long int = 0; i < M...
This loop on its own is not reliable to have any effect: long int j=0; for (long int = 0; i < MAX_SIZE < i++) j++; Unless you use the value of j afterwards the compiler may remove the loop entirely. If you want to keep the CPU busy for some time you need to measure the elapsed time (copy-pasted & modified from h...
66,580,461
66,810,732
C++ Database get array of rows from a table using SQL ODBC
Refering to this link C++\SQL ODBC: Get row from table I don't understand the docs and have tried many variations to get something to work but it just outputs complete jibberish. Basically, how can I get data from my Microsoft Access Database into my C++ program. I would eventually want to get the entire table stored a...
You need to use SQLGetData, passing SQL_C_WCHAR type, for example, if your column is text. Here's example how to get values of the single text column and put them to vector: #include <iostream> #include <string> #include <vector> #include <Windows.h> #include <sqlext.h> WCHAR szDSN[] = L"Driver={Microsoft Access Drive...
66,580,628
66,580,825
CRTP: I can't get rid of duplicate code even with static polymorphism
1. Problem Description I have two classes Derived1 and Derived2. All functions are the same and most of them contain around 100 lines. The only difference are the static objects that are being manipulated. Derived1 is manipulating p1 and Derived2 is manipulating p2. Both classes use static functions. But there is a con...
I am not sure if you can get that to work with CRTP, but it is pretty easy by using non-type template parameters: #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Point { std::vector<int> points; }; // Hides the points class Encapsulate { template<Point &p> class C {...
66,580,734
66,580,881
Variadic template with function, inputs and outputs types
I'm trying to understand how to create and call variadic templates with function, inpus args and output args types. I wrote this toy example: #include <tuple> template<typename Func, typename... Inputs, typename... Outputs> std::tuple<double, Outputs...> foo(int init, Func&& func, Inputs&&... args) { return std::f...
You can write this template function as: template<typename Func, typename... Inputs> auto foo(int init, Func&& func, Inputs&&... args) { return std::forward<Func>(func)(init, std::forward<Inputs>(args)...); } The problem with the original version is with typename... Outputs, they cannot be deduced. You would need...
66,580,774
66,580,935
qt class using new return non-pointer
Seeing that QT has a piece of code like this, how can new return an object instead of a pointer?
You made the wrong conclusion. new always returns a pointer. You need to read the documentation of the classes you are using to know how their constructor works. One way to enable foo f = new foo; is the following: struct foo { foo(foo*){} foo(){} }; int main(){ foo f = new foo; } Note that = here is not ...
66,580,906
66,580,948
why did I get "ambigous" error when invoking same-named function in different namespace?
I implement a function named make_heap() in namespace dsa. and I get error when I tried to invoke it and std::make_heap() to make comparison. GCC told me that: call of overloaded 'make_heap(dsa::Vector::iterator&, dsa::Vector::iterator&, std::greater)' is ambiguous The code is following, any suggestions? template<typ...
ADL strikes back: make_heap(first, last, std::greater<value_type>()); has as argument std::greater which is in namespace std, so unqualified name make_heap also looks into namespace std. "Solution" is to make qualified name lookup (or use name which don't conflict): dsa::make_heap(first, last, std::greater<value_type>(...
66,581,246
66,581,655
Output of code prints a weird negative instead of my input
My professor at the end of the class gave us this code and told us to put it in our compiler and play with it to better understand the fundamentals, however, after I copy-pasted the code it doesn't do what it was supposed to do. Here's the code: #include <stdio.h> #include <string.h> class Clock { private: int hour...
It looks like you are using C library. my solution is: Clock::Clock(char *text) { if (strlen(text) == 5) { sscanf(text, "%2d:%2d", &hour, &minute); } else { hour = 0; minute = 0; } } In the main(), ISO C++ forbids converting a string constant to 'char*' So my solution is: char t...
66,581,384
66,581,501
How to enqueue each element in a vector of unique pointers? (C++)
I'm trying to push each element of a vector of unique pointers into a queue, but for some reason my code won't compile. The error I'm getting is: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Foo; _Dp = std::default_delete<Foo>]’. Since I'm moving th...
You have an extra const which avoid the move and do a (deleted) copy instead: Remove it and use: for (auto &e : c) { queue_.push(std::move(e)); } Demo
66,581,555
66,583,517
C++ wrong output for little numbers for function (1-exp(-x))/x
I need to find function (1-exp(-x))/x values from 10^-30 to 10^9. But for very small numbers the output is 0 but it should be 1. X is correct but there're some issues with fx, and i've not idea how to solve it. #include <math.h> #include <iomanip> int main() { double fx ,x; x=pow(10.0L,-30); std::cout<<"f...
You are right that fx should be equal to about 1 for small x. The issue is that double has a finite precision. Its relative error is much higher than 10^{-30}. A mantissa of at leat 100 bits would be needed. This is illustrated by the following relation: (1 - (1-x)) = 0 for very small x. See the code hereafter. In oth...
66,581,572
66,581,850
Why printing out the characters “” (147, 148 ascii) does not work as expected on c++?
I do not understand what's going on here. This is compiled with GCC 10.2.0 compiler. Printing out the whole string is different than printing out each character. #include <iostream> int main(){ char str[] = "“”"; std::cout << str << std::endl; std::cout << str[0] << str[1] << std::endl; } Output “” �� Why a...
Bear in mind that, on almost all systems, the maximum value a (signed) char can hold is 127. So, more likely than not, your two 'special' characters are actually being encoded as multi-byte combinations. In such a case, passing the string pointer to std::cout will keep feeding data from that buffer until a zero (nul-te...
66,582,270
66,582,893
How to understand the partial ordering by constraints
The partial ordering rules of constraints are defined as: [temp.constr.order#1] A constraint P subsumes a constraint Q if and only if, for every disjunctive clause Pi in the disjunctive normal form of P, Pi subsumes every conjunctive clause Qj in the conjunctive normal form of Q, where a disjunctive clause Pi subsum...
Both A ∧ B and A are already in disjunctive normal form and conjunctive normal form. In this case, there is one disjunctive clause in P, and one conjunctive clause in Q. You then check if any subclause of P0 (A ∧ B) subsumes any subclause of Q0 (A), which it does (A subsumes A).
66,582,577
66,584,305
template method overload resolution rule of class template
I am not able to understand the following overload resolution of a template method defined inside a class template. ///g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 #include <iostream> #if defined(_MSC_VER) #define PrinF std::cout << __FUNCSIG__ <<" "<< __LINE__ << std::endl; #else #define PrinF std::cout << __PRETTY_FU...
There’s no overload resolution here; you specialized the member function template, and so that’s what you call for T=int.
66,582,843
66,582,938
c++ writing data to a given position in an array
I am reading an image with opencv and I want to have an array of images. This is how I init my array. I need to do it with the new keyword because the array is really big. unsigned char* imageStack = new unsigned char[frame.cols * frame.rows * channels * numberOfImages]; Now I want to write my image to a position in...
imageStack is a pointer to to the first of some number of unsigned char. imageStack[imageStackIndex] selects one of those char (or attempts to; it may be out of bounds). Therefore, it is an unsigned char. frame.data is presumably a pointer to unsigned char or is an array, which is automatically converted to a pointer t...
66,583,024
66,583,520
this pointer in c++ maybe 0xffffffff
After read Inside the C++ Object Model, I try to call member function from vptr. I found the following situation by accident gcc version 9.2.0 (tdm64-1) #include <iostream> class Foo; Foo* foo; class FooBase { public: virtual void Bar1(){}; virtual void Bar2(){}; }; class Foo : FooBase { public: void Bar1...
When you access Bar1 via Func1, this ends up being whatever was on the stack in the first arg's position. It wasnt a default value - it just happened to be there from your previous calls. No surprise that the stack can change with change to previous calls. As you probably found out, calling a class member functions ca...
66,583,049
66,588,319
How to transfer constraints of string type to z3 solver expr in C++?
For example, I got a constraint: "(number < 10) && (name == "hello")"; I can do the following now: context c; expr number= c.int_const(number); expr name = c->string_val(name.c_str()); expr constrain = ***procedure***("(number < 10) && (name == \"hello\")"); How can I implement this procedure()? there is an incomplete...
Try: #include <z3++.h> using namespace z3; using namespace std; int main () { context c; expr number = c.int_const("number"); expr name = c.constant(c.str_symbol("name"), c.string_sort()); expr hello = c.string_val("hello"); expr constraint = number < 10 && name == hello; solver s(c); s.add(constra...
66,583,315
66,583,389
About templates in C++
Why isn't this working? I am new to c++. And why is & used in function parameters? How can I use templates? template <typename T> void swap(T&a,T&b) { T temp=a; a=b; b=temp; }
There's already a standard std::swap function with the same signature. If you're using namespace std in the same scope, it's likely there's a conflict.
66,583,646
66,583,782
Is Parameter pack contained in other Parameter pack
I'm writing a class that manages a function object(for fun:)). I want a templated member function of a templated class to check if all of the types given to it were already given to the class. template<typename... Args> class funclass { public: template<typename... types> void funfun () { static...
You can use a helper to check if a given T is part of the Args... pack: template <typename T, typename ...Args> struct contains { static constexpr bool value = (std::is_same<T,Args>::value || ...); }; Then check it for all types in types...: template<typename... Args> struct funclass { template<typename... typ...
66,583,829
66,585,134
Is overriding a function with derived class argument considered name hiding?
I is this considered name hiding? As according to the output it is: class A { public: A(){} virtual bool f(A& a) { std::cout << "A" << std::endl; return true; } }; class B : public A { std::string s; public: B(){} bool f(B& a) { std::cout << "B" << std::endl; ret...
It seems you want multiple dispatch. Double dispatch pattern is a solution. With c++17, we have std::variant which might do the dispatching for us: class A; class B; using VariantA = std::variant<A*, B*, C*>; using VariantConstA = std::variant<const A*, const B*, const C*>; class A { public: virtual ~A() = defaul...
66,584,229
66,606,043
Node.js add on module in C/C++
I have been exploring writing add-on modules for node.js in C/C++. So far I have a simple add on working where I can call an add on function form JavaScript, it's very simple. The routine is called hello, its passed a string and then returns the same string prefixed with Hello with a space between the two words. pack...
In JS: Create a class that inherits from EventEmitter. Doing this you'll be able to listen to events from this class. If you call your addon's function with a callback from this class and in the callback you emit your event you can achieve what you want. Something like this: const test = require("./build/Release/test")...
66,584,389
66,584,689
CMake Beginner's Question: project with 3rd party library gets not compiled
So I am struggeling with cmake for some time now. I want to use the xmlrpc-c library from here. So I started a new project with main.cpp and CMakeLists.txt and copied the xmlrpc-c as a subdirectory into my project (since xmlrpc-c is unfortunately not a cmake library): My code is exactly a example from here and looks li...
Since the library you want to use doesn't have a cmake project you need to handle this on your own. I would suggest using add_subdirectory and creating a sub-project, where you build the library (either as shared or static depending on your needs). In addition you need to point cmake to the location of the headers. Try...
66,584,709
66,855,295
Initiate an async operation with a result
I'm currently working on a project that uses boost asio for networking. I want to implement a function that look like this: template<command T, response R = typename T::response_type> auto send_command(T c) -> boost::asio::awaitable<R> { // ... } In my code, when I'm writing the command to the socket, I will event...
It turns out that there are a number of fixed signature a async operation can take. The void(void) is one, but to have a result, we can simply use void(T): return asio::async_initiate<CompletionToken, void(R)>( [self = shared_from_this()](auto&& handler) { self->callback_queue.push(std::forward<decltype(han...
66,584,787
66,584,887
How to use std::min_element on map with unique pointer values? (C++)
I have a map with unique pointer values, and want to get a reference to the pair with the smallest value. I'm using the code below to do this, but am getting an error in the line where I call std::min_element. The error message is: no matching function for call to object.... What should I do to fix this? using pair_t...
std::map's value type is std::pair<const Key, Value>, you can't edit the key whilst it is in the map. using map_type = std::map<std::string, std::unique_ptr<int>>; map_type map; map.insert(std::make_pair("a", std::make_unique<int>(1))); map.insert(std::make_pair("b", std::make_unique<int>(2))); map.insert(std::make_p...
66,585,202
66,586,696
Generating Table with random Numbers from 1 to 100.000.000 without any doubles in a short amount of time
for a Project do I need to create a Table that stores 100.000.000 Numbers in a random Order without any doubles, which then get saved as .csv File. void Anonym_Option::GenerateTable(){ ui->progressBar->setValue(0); QList<int> l(100000000); std::iota(l.begin(), l.end(), 0); QVector<QList<int>::iterator>...
If you are storing the keys, then a shuffle is just as fast. I tried to keep as much as possible similar, but when shuffling, a std::linear_congruential_engine both doesn't make sense and it took ~4 times longer. I include both methods so you can comment out and test them yourself. While not super-scientific, my shell ...
66,585,452
66,585,992
How to disable scrolling in QGraphicsView?
I am trying to implement mouse wheel zoom in/out. It works BUT when I zoom in/out, the image is getting smaller AND scrolls up/down at the same time with zoom function. Look like events exist at the same time and work together. I cannot find how to disable scrolling with mouse wheel. May be there is a way to make possi...
I was overriding the main method of mouse wheel but it was causing the effect I wrote above void MainWindow::wheelEvent( QWheelEvent* event ) Solved by using event filter. The code below provides zoom in/out with holding ctrl button. bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (event->type() == ...
66,585,746
66,588,424
Windows: Check existence of named pipe
I am writing a C++ program that makes use of named pipes on Windows. I can create and work with them quite fine. The only piece missing to the puzzle is a function to check for a pipe's existence. Coming from the Unix world I originally tried std::filesystem::exists("\\\\.\\pipe\\myPipe") but this is not reliable and o...
std::filesystem::exists("\\\\.\\pipe\\myPipe") returning ERROR_PIPE_BUSY means it is using CreateFile() to actually connect to the pipe. It is not unreasonable for an exists() implementation to attempt to open the requested file to check its existance. Per the CreateFile() documentation: If there is at least one acti...
66,585,784
73,177,816
cannot open source file "crtdbg.h" (dependency of "iostream") C/C++(1696)
I am using VSCode and the code compiles just fine with the .run extension but the C/C++ extension is throwing me this error and underlining #include <iostream> as an error. And yes I have MinGW installed in my system. Furthermore, I get the same error on visual studio community 2019, it does not execute there at all. S...
2022 UPDATE: answer by @Prabhat Bhargav worked for me, but I had to change path to C:/MinGW/bin/g++.exe instead of C:/MinGW64/bin/g++.exe Guess they changed default folder name by removing 64 (at least on windows 10). After that it worked properly. Also if you changed the default installation folder when installing Min...
66,586,008
66,588,252
clang-format removes indents in if condition when there is a line break
I have this function: bool WS::receive(MB *const buffer) const { updateLastPackage(); if ((!lastPackage_.empty()) && (lastPackage_.size() <= buffer->capacity()) && (lastUpdate_.getTime() <= settings_.refreshPeriod)) { buffer->clear(); (*buffer) << lastPackage_; re...
Thanks goes to Yksisarvinen. Solution: AlignOperands: false ContinuationIndentWidth: 8
66,586,061
66,586,111
How can I use std::sort() with std::unique_ptr<[]>?
std::unique_ptr<type[]> D{ std::make_unique<type[]>(10'000) }; std::sort(D2[0], D2[10'000], [](auto& a, auto& b)->bool {return a < b; }); //error I use std::unique_ptr<[]> to read binary-file. if I want to sort this data, Am I have to make another vector or something? I have no idea how to use sort func with unique_...
You can use pointers as iterators for the sort routine: std::sort(D.get(), D.get() + 10'000);
66,586,807
66,586,932
I dont get how command design pattern works in game development
Maybe that's my lack of c++ knowledge or lack of programing skills, but i'm trying to understand command design pattern in c++ for game development. I'm reading this book (its literally called "Game Programing Patterns" and i quite like it), and i decided to use one of the design patterns in real code to see if i reall...
What your missing is binding buttonX_ and buttonY_ to do something. I think all you're missing is a constructor (or some other mechanism) that does something like this: buttonX_ = new JumpCommand(); buttonY_ = new FireCommand(); Right now, they're not pointing to anything. Point them to something and you'll be happier...
66,587,190
66,588,963
How to return cv::Mat in nodejs addon
I've written nodejs addon using V8. I'm stuck at a point where I'm trying to return Mat but all I'm getting is corrupted image with size of 2mb (for particular image). Am I doing something wrong? How can I do this using V8? CPP code snippet cv::Mat image = ... std::string my_cv_mat(image.begin<unsigned char>(), image.e...
I don't think a UTF-8 encoded string (or, more accurately: constructing a JavaScript string from raw image data that you're telling the String constructor to treat as UTF-8 and decode accordingly) is the right tool for the job. Try creating a Buffer directly in your addon, and returning that as the call's result (inste...
66,587,269
66,587,408
What causes difference of size of structs between inheritance and member?
I cannot understand the reason for difference in size of C and C2 in the following code: #include <iostream> struct A { int* x; }; struct B { A a; int y; }; struct C : B { int z; }; struct B2 : A { int y; }; struct C2 : B2 { int z; }; int main() { std::cout << sizeof(A) << std::endl; ...
C++ allows subobjects introduced in a derived class to overlap (padding in) base subobjects as long as those objects are not standard-layout. It does not allow any overlap between member subobjects, or overlap of a standard-layout base subobject. Look at the size and layout of struct B to understand why struct C has in...
66,587,510
66,587,825
How do i store position and direction vectors
drone.cc #include "drone.h" namespace dr { Drone::Drone(std::vector<float> position, std::vector<float> direction, const picojson::object& details) { //store the position and direction vectors. } const std::vector<float>& Drone::GetPosition() const { return this->position...
This should work Drone::Drone( std::vector<float> p, std::vector<float> d, const picojson::object& details) : position( p ) , direction( d ) { }
66,587,672
66,597,886
How to change default C/C++ gnu readline newline character?
My goal is to use the C/C++ readline library on the telnet server-side as it delivers all necessary terminal functionality out of the box. Readline is already connected to the telnet socket, read and write to the socket works fine. I'm using libtelnet by Sean Middleditch. The problem is that the readline outputs '\n' i...
It's not readline that should be changing its behaviour IMO, but libtelnet that should be performing the appropriate translation. The documentation for libtelnet mentions void telnet_send_text(telnet_t *telnet, const char *buffer, size_t size); Sends text characters with translation of C newlines (\n) into CR LF a...
66,587,994
66,588,331
(C++) Visual Studio 2019 - std::std::_Invoke_traits_nonzero has no 'type' member
I have a struct Foo that accepts as template T a lambda function and as ...Qs other Foo's. Inside this Foo struct I define R as using R = std::invoke_result_t<T, typename Qs::R...>. The entire code looks as follows: #include <type_traits> template<typename T, typename ...Qs> struct Foo { using R = std::invoke_resu...
I guess you wish using R = std::invoke_result<T, typename Qs::R...>; The std::invoke_result_t after expanding is using R = std::invoke_result<T, typename Qs::R...>::type; Qs::R is invoke_result_t, and invoke_result_t does not have the member ::type (std::invoke_result<T, typename Qs::R...>::type::type)
66,588,692
66,588,834
C++ 32-bit vs 64-bit executable notation
How should executables for 32-bit and 64-bit be differentiated? At the moment i use "-x86" for 32-bit and "-x64" for 64-bit. Is this correct or is there a standard for this kind of stuff?
There's no standard as far as I am aware. But maybe this answer will help you understand the differences. If you want to make it clear to the user, which system architecture the executable is intended for, then adding "-32x" or "-64x" is clear enough. Most people use the "-x86" and "-x86_64" as extensions however, and ...
66,588,985
66,590,041
Should volatile be used when mapping GPU memory?
Both OpenGL and Vulkan allow to obtain a pointer to a part of GPUs memory by using glMapBuffer and vkMapMemory respectively. They both give a void* to the mapped memory. To interpret its contents as some data it has to be cast to an appropriate type. The simplest example could be to cast to a float* to interpret the me...
OK, let's say that we have a compiler that is omniscient about everything that happens in your code. This means that the compiler can follow any pointer, even through the runtime execution of your code perfectly and correctly every time, no matter how you try to hide it. So even if you read a byte at one end of your pr...
66,589,047
66,590,021
divide array when encountering zeroes
I want to divide an array into multiple(or one, maybe zero) arrays like the example below: array = [0 1 1 2 3 4 0 3 0 3 3 0 5 6 7] -> array1 = [1 1 2 3 4] array2 = [3] array3 = [3 3] array4 = [5 6 7] my naive approach to do this was first removing zeros from left and right then proceed to use two iterators to find the ...
In the following approach that I propose you can retrieve the sub-arrays with a single sequential scan, with no need to exclude zeros at the beginning or at the end: std::vector<std::vector<int>> arrays; std::vector<int> currentArray; for (int i = 0; i < a.size; i++) { if (a[i] == 0 || i == a.size - 1) { ...
66,589,173
66,632,320
Can C++ std::thread callable's object pointer be invalidated after the thread begins execution?
I have this chunk of code... A non-static member method (serving as callable for thread): void Object::unregister() { ... } and destructor like this: Object::~Object() { std::thread cleanup(&Object::unregister, this); cleanup.detach(); } What I see as a problem is that I am running a thread with parameter this...
is safe if this would be invalidated (destructor finishes) before the call to unregister finishes completely (in other words is it ok, if it already started, but did not finish completely)? No, it's not safe. Consider the following C code: void Object_unregister(void* obj) { Object* this = (Object*)obj; fclos...
66,589,295
66,589,390
I want my program to stop accepting input from console when I type STOP in console C++ Program
I am making a C++ program which accepts input from user (even \n) is required but the program should stop when I type STOP, so can anyone help me out. Earlier I was using getline but that also got some issue like when I enter \n two (hit enter two times) it stops the whole code. So can anyone guide me what to do, I wa...
fgets() includes '\n' in the output, if the read is terminated by ENTER, so you need to check for that, eg: while (fgets(array, sizeof(array), stdin) != NULL) { str = array; if (str == "STOP" || str == "STOP\n") break; } Or: while (fgets(array, sizeof(array), stdin) != NULL) { if (strcmp(str, "STO...
66,589,383
66,589,690
Address of reference to this not the same as this
I have the following snippet of code: class Base { //... }; class Subclass : public Base { public: void foo() { Base& ref = (*this); } //... }; Where I pass this reference to the constructor of some other objects for later use. According to the following article (and what I know about references), if...
I found the source of the problem, and it has to do with multiple inheritance. Here is a simplified example: #include <stdio.h> class Base1 { private: int _a; int _b; }; class Base2 { public: ~Base2() { } virtual void* foo() = 0; private: int _x; }; class Child : public Bas...
66,589,838
66,589,897
Using Class vectors to display the contents. Vector.size() goes to 0 when not in constructor
So I am trying to make a program that stores polynomials the user enters as vectors, then my program will allow to the user to do operations on these polynomials with overloaded operators. However, when I create a class object, using my constructor the proper vector is created, but when I try and use the same vector in...
You constructor is creating a local variable called P which has precedence of the class member with the same name. You are building the vector locally and then throwing it away.
66,589,964
66,590,142
Does the below code lead to a dangling reference?
int& getRef() { int* ptr = new int; *ptr = 42; return *ptr; } int main() { int& ref = getRef(); std::cout << ref; } Is ref here a dangling reference after the call to getRef()? This is how I typically reason about dangling references: A reference is an alias to an object If the object is destroyed...
A reference is not exactly an alias, it is a different variable that points to the same address that you initialized it with during all its lifetime. If you want to know if a object is being destroyed or not in some conditions, you can take advantage of destructors. #include <iostream> class myClass { private: int...
66,590,820
66,590,899
Variadic template arguments by reference
How can I make this template function variadic : template <typename T> void checkedAlloc(size_t count, T*& x) { x = new T[count](); if(nullptr == x){ fprintf(stderr, "Error: not enough memory (%llux%llu bytes).\n\n", count, sizeof(T)); exit(1); } } size_t *A; checkedAlloc(20, A); so as to be able to do ...
template <typename ...T> void checkedAllocV(size_t count, T*& ...x) { ((checkedAlloc(count, x)), ...); }
66,590,865
66,642,165
VS Debug / Release execution speed and code skiped in C++ console program
When I compile C++ (console program) with "release" instead of "debug", it seems that empty loops (this might seem weird, but it's important for testing purposes) get just skipped. Is this some compiler setting, because when building with "debug" they won't get skipped, but rather get executed like expected. Is there ...
Solution: You either change the "debug" or "release" compiler settings or just create your own compiler settings. In the compiler settings under the optimization tab you can choose custom settings for the optimization where you can disable code skipping by disabling to prefer execution speed, or just disable optimizati...
66,591,308
66,623,631
Mixing C++ and C/C++ static library with CMake
I have searched various forums and cannot find a solution to my problem. I'm trying to write unit tests of a function in a C file. I'm using google test library. Although I follow the guides, the project doesn't compile properly. Tests written in C ++ do not see functions in C file. (undefined reference) Below I am a...
The reason it doesn't work is that you have a typo in the main CMakeLists.txt: You define the variable Source, but use the variable Sources when populating the sources of the pir_driver target. Consequently the .c file isn't compiled and the linker can't find the symbol defined within. The missing .c file is also the r...
66,591,336
66,593,069
Replace Macro with modern C++
I have the following macro #define Error(error_msg) ErrorMsg(__FILE__,__LINE__,error_msg) I was wondering whether this could be replaced with more modern c++ which can be defined once and for all in a header file? My function ErrorMsg has following interface void ErrorMsg(const std::string &file, int line, const std:...
Like @m88 said in the comments, std::source_location is the modern C++ way to get the filename, function name and line number - so modern, in fact, that it is only supported for really new compilers that support C++20. Here is a program that does both the macro way and the std::source_location way so that you can compa...
66,591,437
66,591,510
What does the MINGW64 on Git Bash mean?
So, I am planning to start learning C++ today, and I prefer using VSCode over other text editors/IDEs, and don't want to use replit.com either. However, while watching a tutorial, the explainer said that you should download mingw, which caught my eye. I had already downloaded Git Bash a while ago, and I realized that ...
The mingw-w64 project is a complete runtime environment for gcc to support binaries native to Windows 64-bit and 32-bit operating systems. https://sourceforge.net/projects/mingw-w64/
66,591,490
66,592,382
C++ to_string not a member of std on Dev C++
#include <iostream> #include <string> using namespace std; int subtract(int num1, int num2) { return num1-num2; } int main() { cout << "Input the number to subtract from: "; int num1; cin >> num1; cout << "\nInput the number to subtract from " + std::to_string(num1); int num2; cin >> num...
Make sure you have passed flag -std=c++11 or -std=gnu++11 to the compiler. This should be set somewhere in the project options. Otherwise, compiler that is included with Dev-C++ might operate by default in the c++98 mode, which, obviously, doesn't have std::to_string(), i.e. that is correct for C++98, which you likely ...
66,591,623
66,591,685
C++ Object definition vs initiation
I everyone, I am new with C++ and I don't understand when a object is created when its definition is inside a library. For example the next code in Object1.h: class Object1 { public: Object1(int cause); void start(); void f2( string msg ); void f3( uint32_t ts ); bool f4(); private: void reset(...
when I create an instance of Object1 an instance of Timers is also created for these Object 1 or ... Yes. ... is only a definition and is created else where? When is called the constructor for the object Timers? You got it right the first time. The Timers instance _timers is created when an Object1 is created. When...
66,591,822
66,592,369
c++ inconsistent unsigned to signed subtraction results only fails for one permutation
I realize that there is a rule by which numbers with a width smaller than int can be promoted to a wider type for the addition operation. But I cannot fully explain how only one permutation of the following print_unsafe_minus will fail. How is it that only the <unsigned, long> example fails, and what is the take-away f...
Before we start, let us assume OP is using an implementation with 32-bit int type. That is, int32_t is equivalent to int. Let X be the width of M, and Y be the width of N. Let us divide your test cases into three categories: First Category: X <= 16 Integer promotions applies here, which is always done before invoking a...
66,591,993
66,616,580
Xcode 12 builds Document file instead of Unix file when using SDL2 and c++ (command line tool) MacOS 11.2.3
Hello I am working on simple game engine with SDL2 and c++ in Xcode 12.4 (command line tool). My Problem is that when I include SDL and run the project, the Product is a Document file instead of a Unix file. Xcode runs the project with no problems but I cant use it. When I tested it without SDL, it compiled to a unix f...
I found the mistake. I may have named my project "Engine 1.1", which means that the compiled file was also called "Engine 1.1". As a result, the file extension ".1" was not recognized. Since the Unix files have no extensions in MacOS, I didn't notice that. So when you create a project in Xcode, just don't use dots.
66,592,082
66,622,936
How to find a point of an elliptic curve in crypto++ (with given x)? Or how to compute a root in finite field? Or root of Polynomial Ring?
Is there any way in crypto++ to check if an EC contains a point with a given x-coordinate? One solution would be solving the EC polynomial for given x. One side of the equation already done in code. I 'just' need to compute the root of it (over a finite field) //clang++ -o ectest ectest.cpp -lcryptopp #include "cryptop...
Yes, you can. The library has support for compression and decompression of points. During the decompression, the library must find y if it can. The header of the DecodePoint bool ECP::DecodePoint(ECP::Point &P, BufferedTransformation &bt, size_t encodedPointLen) const The error returned with if (Jacobi(P.y, p) !=1) ...
66,592,139
66,593,321
How to use the getline() function if I don't use "using namespace std;"?
I just started learning C++ recently, so please excuse me if I have some mistakes in my question. In most of the tutorials I have watched, I have been taught to use the "using namespace std;" statement. But later I found that it is a bad practice, so now I don't use it. The problem I have is that if I use the getline()...
The issue is that a ot of things are in the std namespace. Because you are not using using namespace std; everything that is in this namespace must be explicitly prefixed with std::. In this situation my_str has a type string. But there is no type string there is a type std::string. You need to be explicit. #include <i...
66,592,824
66,592,910
How to fix c++ not outputting the input
How to fix c++ not outputting the input I got no idea! So please help me I am new to c++! #include <iostream> using namespace std; int main() { std::cout << "Please type if you want pickup or delivery: "; string input; string pickup; string delivery; string address; if (input == "pickup") ...
You are not asking for input... std::cout << "Please type if you want pickup or delivery: "; after this line you need to get the user to input either pickup or delivery ie std::cin>>input; next you need to swap getline(cin,address); and cin.ignore();arround.. currently you are asking for input and then clearing the b...
66,592,902
66,593,088
Why std::filesystem::file_size(file) is differnt with real file-size?
#include<iostream> #include<random> #include<fstream> #include<filesystem> int main(){ std::default_random_engine dre; std::uniform_int_distribution<> uid{ 1, 100'000 }; std::filesystem::path file("./test.txt"); std::unique_ptr<int[]> D{ std::make_unique<int[]>(10'000) }; for (int i = 0; i < 10'0...
std::ofstream buffers its output, so it is possible (even likely) that by the time you are calling file_size(), there are still bytes in the buffer that ofstream has not written to the actual file yet. Close the ofstream first: std::ofstream out(file, std::ios::out | std::ios::binary); out.write((char*)D.get(), sizeof(...
66,593,297
66,593,559
Why conditional_variable::notify_all may not wake up any thread?
I use conditional_variable::notify_all() to wake up a waiting thread(only one thread is waiting for the unique_lock indeed). This code snippet works well at most time, but the log files(for details, see below) indicates that the parent thread could not aquire the unique_lock after the new created thread allready return...
You are misusing a condition variable. To use a condition variable: One thread must be notifying another thread about some change in shared state. There must actually be some shared state that has changed. The shared state must be protected by the mutex associated with the condition variable. The shared state must ...
66,593,317
66,595,388
User-defined deduction guides for non-type template parameters
I have the beginnings of a matrix class. Here's the code- template<int h, int w = h> class mat { public: mat() : values(h, std::vector<double>(w)) { if (w == h) { int x = 0; for (int y = 0; y < h; y++) { values[y][x] = 1; x++; } } ...
if you provide a constructor like this: template<int w, int h> struct A{ A(double (&&c)[w][h]); // `double const (&c)[w][h]` is also OK. }; without any other deduction guide, you can use it as follow: A a{{ {1, 2, 3}, {4, 5, 6} }}; A b = {{ {1, 2, 3}, {4, 5, 6} }}; A c({ {1, 2, 3}, {4, 5, 6...
66,593,809
66,593,847
Why is my for loop not calculating the number of words correctly?
So I am trying to create a program that reads a line of text and calculates the number of words in that line of text. My idea was to search for the number of spaces(' ') in that line of text and then add 1 to this number to get the word count. For some reason, when I use getline it miscalculates this but calculates the...
Replace if(n[i]=' '){ by if(n[i]==' '){ Since you are not using the comparator (==) hence it never enters the count increment logic area.
66,594,520
66,595,310
How to get current video location name in splitmuxsink?
I'm using splitmuxsink element to save videos based on size, I can use format-location signal to set the next video name to be used for dumping video. static gchararray format_location_callback (GstElement * splitmux, guint fragment_id, gpointer udata) { static int ...
I'm able to get video location using GstMessage of type GST_MESSAGE_ELEMENT by listening on the GstBus. The splitmuxsink has message with name splitmuxsink-fragment-opened when video split takes place. const gchar * location; const GstStructure* s = gst_message_get_structure(message); if (gst_structur...
66,594,589
66,625,685
Atomically share(without a mutex) boost::intrusive_ptr?
I know boost has atomic_shared_ptr which can be used with a shared_ptr. But is there a way to do something similar with boost::intrusive_ptr ? i.e. is it possible to share boost::intrusive_ptr across one writer/multiple reader threads WITHOUT using mutexes ? Back ground : Unfortunately, my workplace allows only till C+...
It seems this is impossible (at least with C++11) as even boost::atomic_shared_ptr seems to use a boost::detail::spinlock for this. ref : https://github.com/BeamMW/boost-linux/blob/master/boost/smart_ptr/atomic_shared_ptr.hpp
66,594,604
66,594,684
why using std::move and assign to rvalue does not steal internal content?
As is known to all that c++ std::move would steal internal content if used with non-fundamental type. I suddenly have a brainwave that what will happen to rvalue if move a lvalue to it. I initially thought it would still steal the content. But nothing happened,a has its string still. Does this caused by ignoring the mo...
It is because c is declared as a reference (rvalue reference) to a. It is not a different string. In order to "still" (i.e. call the move constructor), c needs to be declared a string. Then, string a is "moved" to string c: int main() { string a="4"; string c = move(a); cout<< "a :" <<a << ":" <<endl; ...
66,594,766
66,596,953
Using ranges of an enum for simple state tracking
I am using a series of enums used for state management on an embedded system. What I am now implementing is a system to display the state of particular modules in a simplistic way to a user. So I would like to translate these various states to 3 super states, in this case red/yellow/green to indicate error/configuring/...
That looks "hacky" indeed. Instead consider using a state machine where each state in turn uses its own internal state machine. This internal state should be of no concern to the rest of the program but privately encapsulated. Also avoid assigning values to the enum manually, if you don't then you can use the enum type...
66,594,801
66,680,056
TAzureBlobService->GetBlob fails on big files
I'm using TAzureBlobService->GetBlob( ) to open text files in Azure. It fails on files over 100M; it fails after 30 seconds with "The connection with the server was terminated abnormally". The files are fine, other apps (in other compilers) are happy. Is there a size or time threshold with GetBlob()? 13 Mar --- I've p...
While the underlying HTTP connection is set up with various timeouts all equating to 60 seconds (see this documentation page for an example of one of those defaults), the important one, the Azure timeout, has a default timeout of 30 seconds. Therefore what your sample code is missing is something like this, where Servi...
66,594,946
66,595,358
I am trying to perform DFS using STL stack but it is giving unexpected results
This my code for DFS and it should give output like this: Following is Depth First Traversal: 0 1 3 2 4 but it is giving the output: Following is Depth First Traversal: 0 2 3 4 1 1 1 I am not visiting the visited element again still it is not working. #include<bits/stdc++.h> using namespace std; void addEdge(vector<in...
Unless there is a good reason to use an explicit stack, I would recommend to use recursion(implicit stack). However I am going to fix it least changes to your code. There are 3 things to fix and I left comments below. void DFS(vector<int> adj[], int V, int s) { stack<int> st; vector<bool> visited(V, false); // ...
66,595,254
66,595,438
Dereferencing operator for custom array iterator
I am practicing implementing a random access iterator for a custom class: template<typename T> class Array{ friend class Iterator; private: std::unique_ptr<T[]> data; int front_index; //other variables public: class Iterator{ friend class Array<T>; pr...
It gives the following error: C++ no operator matches these operands, operand types are: * Array<int>::Iterator It seems like the error is coming from the return data[position]; line. If I only write return position that the code runs but this is not what I want (I want that when I dereference the ierator returns t...
66,595,473
66,595,595
no match for ‘operator=’ when std::shared_ptr
I see a code using exactly this, but that code works and mine not, any idea why? PD: im trying to implement this commit. See that the code is exactly the same for(const auto& tx : block.vtx) if (txHash == tx->GetHash()) { txNew = tx; foundAtOut = *pindex; return true; } main.cpp:2471:25...
Read the error message carefully: you are trying to assign an object of type const CTransaction to a shared pointer of type std::shared_ptr<const CTransaction>. But you can't do that using operator=, because its argument should be a shared_ptr or unique_ptr, as described at cppreference. Depending on your actual code, ...
66,595,964
66,596,133
How Can I Redefine a Classs Outside of A Loop?
I am getting redefinition of class error for the below code. But if I put this definition in a loop there is no error. What is the difference? using namespace std; #include <iostream> using namespace std; struct MyClass { int x; }; int main() { MyClass A; MyClass A; return 0; } I tried this but s...
Well, here MyClass A; MyClass A; you're defining the same class variable twice (which by the way should be highlighted by your compiler with a great compilation failure message) The same you're doing here, but worse MyClass* A; delete(A); MyClass* A; delete(A); since you're also trying to delete the point...
66,595,995
66,596,115
Why my program crash after dereference of returned iterator of erase() function?
Below is my code. I erase the element of which value is 3 and obtain next iterator by erase() function. But when I tried to print its value.It crashed to my surprise. Anyone know the problem?? int main() { std::vector<int> a = {1, 2, 3, 4, 5}; for(vector<int> ::iterator it=a.begin();it!=a.end();it++) { ...
Why my program crash after dereference of returned iterator of erase() function? After you have indirected through that iterator and inserted it into cout, you proceed to increment it which is (potentially) invalid, and then also compare it to another iterator and later indirect through it. This results in undefined ...
66,596,230
66,599,892
How to set dependency DLL paths in Visual Studio?
I am working with Cyclone DDS, and they have two builds, c build (contains multiple files in the bin folder) and c++ build (contains DLL file in the bin) after Cyclones DDS installation, I have to set these bin paths in system environment variables. how can I avoid this? I need to set them in the visual studio 2017 i...
Windows by default will prefer .DLL files in the same directory as the .EXE. So while developing, you can put them in your Visual Studio Debug and Release folders. For other people, you include the DLL's in the installer. The exception is the *140.dll stuff, for which you need the Visual C++ redistributable. That's ins...
66,596,316
66,596,855
How to create an installer with InnoSetup running in only one computer to prevent unauthorized copy
I am using Innosetup to create an installer for my application (test.exe using Qt creator). I need that my application should be running on only one machine (unauthorized copies in other computer). I don't know how to make a function in Innosetup to identify if the address IP corresponds to the authorized machine or no...
If you are looking for an solution for anti-copy the application, you can read the SID of the PC installed, store the SID in your application. Every time your application launches, the first step is to read the SID, then compare to the initial SID, if not match, exit your application.
66,596,552
66,596,764
memcpy writing to an object of type ‘class uint256’
Well, this is probably a really simple warning to fix, but I didn't figure it out yet. Some time ago, I made an update for my uint256 class, and after that, I get this warning: base58.h:261:52: warning: ‘void* memcpy(void*, const void*, size_t)’ writing to an object of type ‘class uint256’ with no trivial copy-assignme...
You have defined a copy-assignment for base_uint<N> class here And a copy constructor for base_uint here, and a conversion constructor uint256 here Also if you simply cast your (uint256*) argument to (void*) the warning will disapear, and you will have the expected behavior, but that's not the recommended way to do, be...
66,596,628
66,636,200
How can I combine templated derived class in CRTP with derived class expression templates?
My goal is to implement a vector class Vec that allows for efficient computation of arithmetic expressions like auto vecRes = vecA + vecB * vecC. This is a known problem and a solution using the Curiously Recurring Template Pattern (CRTP) can be found on wikipedia. I started by adopting an implementation for hardcoded ...
As pointed out by @super and @Jarod42 the solution is very simple: Don't use a template template argument in the base class or the expression templates for operators but instead replace the return type of double operator[] by auto. template <typename Exn> class VecExn { public: auto operator[] ( int32_t idx ) const...
66,596,749
66,596,818
Can vector erase() function delete two consecutive same elements?
Below is a snippet of my program. I iterate through a vector and try to delete all the element which has the value of three. But after I print the content of the vector,it's 1-2-4-3-5,it still has a number 3. Why? Do we have to deal with iterator specially if we want to delete two consecutive same elements? int main() ...
We can break down your example and only look at the last three numbers 3, 3, 5. After erasing the first 3, an iterator two the second 3 is returned in it = a.erase(it); But immediately after this it is incremented in it++; and now points to the 5. Here you can use the erase-remove-idiom. Example code: a.erase(std::r...
66,597,002
66,597,710
Using the Clipboard in Win32
I've created a small program in Code::Blocks using the Win32API GUI, all written in C++. I want to add a button to automatically copy the text present in an edit control, how do you do that? (Note that I'm new to the Win32API)
You need to associate with the edit control through OpenClipboard, and then call SetClipboardData to set the clipboard. Here is a sample: #include <Windows.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); #define IDB_ONE 3001 HWND edit; int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInsta...