question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
62,226,432
62,226,468
Is there a way of changing the type used in a struct depending on at template parameter in c++?
What I want is a way to have different data structures for the struct depending on template parameters template<uint32_t width, uint32_t height> struct S { templateif (width * height) > 32: uint64_t val; templateelse: uint32_t val; templatend; } Something like what you see above. Is there a...
You can try std::conditional template<std::uint32_t width, std::uint32_t height> struct S { using type = typename std::conditional<(width * height > 32), std::uint64_t, std::uint32_t>::type; type val; }
62,226,465
62,226,516
Displaying enumeration values from functions
The idea is to display all the data from the collected from the user in a tabular format according to the structures and enumerations defined. I've gotten some warnings about the use of the switch statement but the most inhibiting thing seems to be the use of the "s.width" when attempting to display the values. When I ...
You are missing a << cout << setw(4) << nameOf(circle) << setw(4) s.width << setw(4) s.length // ^HERE there should probably be '<<' << setw(4) perimeter(circle)<< setw(4) << area(circle)<< endl;
62,226,513
62,228,301
Boost bimap fails to compile with gcc 10, c++20. Looking for temporary fix
With gcc 10.1 and boost 1.73.0, the following code #include <boost/bimap.hpp> int main() { boost::bimap<int, int> lookup; } fails to compile with flags -O2 --std=c++20, but will succeed with flags -O2 -std=c++17 (verified with compiler explorer). This is possibly related to the following issue: https://github.com/...
The reason behind the error is not that the std::allocator<void> specialization is removed. Actually, it's still valid as the primary template with the void argument. The code fails to compile, because ::rebind is no longer part of std::allocator itself. Instead, an implementation should use std::allocator_traits<Allo...
62,226,696
62,226,862
C++ object construction -- direct initialization versus using the '=' operator, are they equivalent?
In C++, are these two styles of initializing a class-object functionally equivalent, or are there some situations where they might have differing semantics and generate different code? SomeClass foo(1,2,3); vs auto foo = SomeClass(1,2,3);
The 1st one is direct initialization. The 2nd one is copy initialization, in concept foo is copy-initialized from the direct-initialized temporary SomeClass. (BTW it has nothing to do with operator=; it's initialization but not assignment.) Because of mandatory copy elision (since C++17) they have the same effect exact...
62,226,698
62,226,725
How to check if an object is an instance of a template class in C++?
How do I check if a variable is a template class without knowing the template argument, so in the example below, how do I determine (prove) that A<int> is an A. template <class T> class A {/*----*/}; int main() { auto a1 = A<int>(); bool is_a1_an_A = some_method(a1, A); } Any help is greatly appreciated. Tha...
This is pretty straightforward using a specialized helper class: #include <type_traits> #include <iostream> template<typename T> class A {}; template<typename T> struct is_a : std::false_type {}; template<typename T> struct is_a<A<T>> : std::true_type {}; int main() { auto a1=A<int>{}; bool b1=false; ...
62,226,731
62,272,610
ReSharper In An Unreal Engine Project Giving Wrong Errors
I know about this question. However, I tried every single answer and none of them worked. I just created a new Unreal Engine Project, and enabled ReSharper. When I created a new Actor class, it's showing errors with red squiggly lines, even though I can run it just fine. Why is this happening? I disabled code analysis ...
I finally found the answer. You have to go to the Unreal Editor, and click File | Refresh Visual Studio Project. Then when you open Visual Studio it won't show the errors.
62,227,378
62,227,693
Are these two expresions all the same:"CTest cTest(t);" "CTest cTest=t;" in C++? Only different in efficiency?
As the subject, the related code is listed below.You could check it on https://godbolt.org/z/bcf8js. There is no doubt that EntityId_t c_SEDSubscribe(ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER); calls the user defined constructor EntityId_t(int id) whereas I think EntityId_t c_SEDPPubWriter = ENTITYID_SEDP_BUILTIN_PUBL...
ClassName var{foo}; This directly calls the constructor, passing in foo. ClassName var = foo; This attempts implicit conversion of foo to ClassName, and requires that such a mechanism be available. This could be a non-explicit conversion constructor on ClassName or a non-explicit operator ClassName on foo's type. I...
62,227,393
62,227,922
What is delete this use case and behaviour in c++?
class Person2 { Person2(){}; Person2(const Person& _){}; ~Person2(){}; int refcount; public: //static method to create a Person2 static Person2* create() { Person2* p = new Person2(); p->refcount=1; return p; } void add_ref() { refcount++; } ...
In isolation (i.e. since no information is provided about code that uses the Person2 class) this "use case" is one of a poorly implemented reference counted object, in which other code calls Person2::create() to create an instance, uses the add_ref() member to increment a reference count, and the release() to decrement...
62,227,635
62,227,659
"Pointer being freed was not allocated" while deleting allocated (?) pointer
The error occurs at the "delete pointer;" Code: #include <iostream> int main() { int i = 5; int* pointer = &i; *pointer = 0; std::cout << "Value: " << i << std::endl; delete pointer; std::cout << "This does not print" << std::endl; return 0; } Output: Value: 0 untitled1(11320,0x106c20dc0)...
You haven't allocated any pointer. You're also confused over terminology. Allocation here is refering to dynamic allocation. In dynamic allocation you allocate memory and you assign the address of that memory to a pointer. Memory is allocated with new So the correct version of your code is #include <iostream> int main...
62,227,674
62,227,769
String variables order
I'm currently learning through Bjarne Stroustrup's book "Programming: Principles and Practice Using C++". I'm at the point where we try to concatenate strings using the following example (edited for the actual code as requested): I apologize I failed to mention that the program works. But whenever I type both names it ...
I mean it probably did work. The problem here is that the result isn't what you think it is. Strings are usually empty by default. So an empty string + a space + another empty string = just a space. It's highly likely you're seeing this space, but it looks empty because spaces are, well, spaces. If you want to concaten...
62,228,043
62,228,633
C++ dynamic code generation based on input parameter
I have the following function: void scan(DataRow& input) { if(input.isRaw()) { ... } if(input.isExternal()) { ... } if(input.hasMultipleFields()) { ... for(auto& field: input.fields()) { if(field.size() == 2) { ... } } ...
You cannot easily manipulate executable code during runtime. But your question doesn’t look like you’d have to go down that road anway. You have groups of rows with similar properties and special processing logic for each group. Also, there seems to be a small fixed number of different kinds of groups. You have all nec...
62,228,109
62,228,248
error: cannot pass object of non-trivial type 'std::string' and more errors
I'm running a build in Travis CI, and during the compilation, this error occurs. I tried specifying the C++ compiler and tried using g++ but that resulted in more errors. $ clang -I ./jsoncpp/include/ -L ./jsoncpp/build/debug/lib -std=c++14 -v test.cpp -o buildtest.exe ... ./IBMWatson.h:79:44: error: cannot pass object...
curl_easy_setopt is a C function, where variadic actually means the <cstdarg>'s ... parameter. It accepts only trivial types, which std::string is not (i.e., it cannot be copied with memcpy, and instead, a non-trivial copy-constructor is involved); otherwise the behavior is undefined or only conditionally supported. In...
62,228,538
62,236,723
Mixing Rcpp modules and Rcpp::export
I want to expose a C++ class and a function that takes objects of that class as a parameter to R. I have to following simplified example. I created a package using Rscript -e 'Rcpp::Rcpp.package.skeleton("soq")' and put the following code in soq_types.h #include <RcppCommon.h> #include <string> class Echo { private...
The error message is complaining about the declared but not defined Echo(SEXP), which is meant to extend Rcpp::as<>. For classes handled by Rcpp modules it is easier to use the RCPP_EXPOSED_* macros: #include <Rcpp.h> class Echo { private: std::string message; public: Echo(std::string message) : message(messa...
62,228,573
62,228,608
loop parameter pack lambda
I have a small bit of code. I want to know if i could cut out my ProcessArg function I would like to loop the parameter pack from inside my call function. Im i best to use a lambda function in initializer_list or something else, if so how do i do it. Thanks template <class R, class Arg> R ProcessArg(Arg&& arg) { st...
With c++17 fold-expressions, you can replace: std::initializer_list<R>{ProcessArg<R>(std::forward<Args>(args)) ...}; with: ((std::cout << typeid(args).name() << (std::is_reference<Args>::value ? "&" : "") << std::endl ), ...); Or with a lambda expression to improve readability: auto process =...
62,228,713
62,230,941
Leetcode 1423: How to optimize brute-force recursive approach?
I came across this question on Leetcode. The question description is as follows There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You h...
if you closely look, it can be solved by sliding window. What are possible cases of selection after completion of Kth pick up if we forget the order we picked up? The possible combinations will be: 0. 0 card picked up from rightmost, K cards picked up from leftmost 1. 1 card picked up from rightmost, K-1 cards picke...
62,228,768
62,228,817
Finding length of int array in c++, how does it work?
Someone gave this code as a method to find the length of an array called a: std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl; The only thing I don't understand is sizeof(*a) I don't know what the * is doing here. I also assume it's a fraction. What's it doing in the denominator?
In C++, an int is 4 bytes. sizeof(*a) is getting the byte size of the type stored by your array. What (sizeof(a)/sizeof(*a)) is doing is dividing the total bytes stored by your array by the byte size of the array type, thus giving you the length. Ex: you have an array [1, 2, 3, 4] which is 16 bytes, and the size of an ...
62,229,310
62,274,641
Postgres vs MySQL: Commands out of sync;
MySQL scenario: When I execute "SELECT" queries in MySQL using multiple threads I get the following message: "Commands out of sync; you can't run this command now", I found that this is due to the limitation of having to wait "consume" the results to make another query. C ++ example: void DataProcAsyncWorker::Execute()...
"Question: Does PostgreSQL have this limitation as well? Or in PostgreSQL there is also such a limitation?" No, the PostgreSQL does not have this limitation.
62,229,566
62,229,947
Could somebody explain the functions of a member function with the delaration 'explicit operator const GUID_t&() const'?
What's the function of 'operator const GUID_t&() const' in the code snippet below. It's quoted from a wellknown open source project,so i don't doublt the correctness.It does not look like ordenary operator overload,eg:CTest operrator(CTest&&), which you could clearly know the return type.Is there a term for this kind o...
It's a user-defined conversion function of a general form: operator T(); Here: T = const GUID_t& That is, it allows instances of InstanceHandle_t to be converted to const GUID_t& using the operations defined in the operator's body. The additional explicit specifier is optional, and prevents implicit conversion, i.e.,...
62,229,629
62,229,677
std::is_class is false on a reference class
How come std::is_class is false when I test it on a reference ? int main() { struct foo_struct { int i1; int i2; }; std::cout << std::boolalpha << std::is_class<foo_struct>::value << std::endl; // true std::cout << std::boolalpha << std::is_class<foo_struct&>::value << std::endl; // fala...
Reference types and class types are different types; reference types are not class types themselves. As type classification: The C++ type system consists of the following types: ... compound types (see also std::is_compound): reference types (see also std::is_reference): lvalue reference types (see also std::is_lv...
62,229,865
62,229,910
How to set background color in OpenGL
The background color of my scene is black. How can I change this color? Looks like I'm doing something wrong because glClearColor() function is not working: I tried to change the values but nothing happened. I'm new to OpenGL and programming in general. #include <GL/glut.h> void Ayarlar(void); void CizimFonksiyonu(voi...
Ayarlar() has to be called be for glutMainLoop(). glutMainLoop enters the GLUT event processing loop and never returns. You have to set the OpenGL states before. glutDisplayFunc(CizimFonksiyonu); Ayarlar(); glutMainLoop();
62,229,895
62,229,949
Pass enum in a scope to another as function argument
How to pass enum in a scope to another as function argument? As this is failing: enum class L; struct TestClass { void foo(L n) { int v = static_cast<int>(n); int r[v] = { 9 }; cout << "\n" << v << "\n"; } }; int main() { enum class L : int { A, B, C, D }; TestClass m...
How to solve this (in the exact place, not move enum to a scope else)? Cast the enum while passing as a parameter. main.foo(static_cast<int>(L::D)); Then your member function would be void foo(int n) { std::vector<int> r(n, 9); // used `std::vector` instead of VLA std::cout << "\n" << n << "\n"; } (See sampl...
62,229,968
62,231,820
Program exits with status code 0 in the middle of the execution in debug
I've reduced my program to the absolute minimum, and seem to have a weird bug in debug mode (it works in release mode). Whenever I set a breakpoint on the line auto* buckets = new Temp[bucket_count];, Clion exits with Process finished with exit code 0 within a half of a second after stopping at the line. No more lines ...
CLion bug report submitted by OP CPP-20658: Program exits with status code 0 in the middle of the execution in debug Original answer (prompting OP to open the bug report) You program is well-formed, and this is very likely a bug in CLion's debugger subsystem, to which there are already several similar open bug repor...
62,230,054
62,230,967
Is it dangerous to pass a pointer to a subobject that is not constructed yet to a constructor of another subobject during the object construction?
The subobject won't be used before its construction, only the pointer to it will be stored. Consider the following code: class Base1; class Base0 { public: Base0(Base1* obj1) : anotherObj(new AnotherClass(obj1)) // only saves the pointer, doesn't use the object {} AnotherClass* anotherObj; }; ...
This is a somewhat dangerous pattern in general. It's possible to keep things strictly valid, but in the example shown, it's actually the conversion from Base1* to AnotherClass* which is not allowed by the Standard. [class.cdtor]/2 gives some restrictions on converting a pointer from derived class to base class: To ex...
62,230,135
62,240,638
What is the difference between L2_NORM and NORM_MINMAX implementation in cv::Normalise()?
I was trying to replicate the Dense optical flow as discussed here : https://nanonets.com/blog/optical-flow/ .This is the snippet , I have used to process each frame for optical flow. The intution is that H->Angle of gradient,S->255,V->Norm value of Magnitude of gradient.The gradient is from output of calcOpticalFlowF...
cv::NORM_L2 normalises your data such that if you took the entire image and converted it into one long vector, the magnitude of this vector is such that it becomes alpha. beta is ignored in the normalisation. Therefore, once you normalise by cv::NORM_L2, after you normalise if you were to consider this normalised in...
62,230,314
62,230,749
How can I get the created object of the class that is constructed in main() function?
I want to get the object of the class which is constructed in main() function and use this object in another class. This is the class I want to take the object of it: typedef enum { DOWN = 1, LEFT = 2, UP = 3, RIGHT = 4 } tWaypointDir; class Waypoint { sf::Texture texture; sf::Sprite sprite; ...
You can pass pointer or reference on Waypoint class as argument in Car class constructor or method. Car class could store this reference or pointer as member. Then you can access this object from Car class
62,230,315
62,231,100
Locating doubles in a char array (C++/ROOT)
I have parsed some XML data, and I want latitude and longitude information. The line I need to parse is this: trkptlat="60.397015"lon="5.32299" This is an element in a char array, how can I extract/parse the numbers as doubles? Note that the number precision varies as the data goes on, so I can't solely rely on picki...
You are using C-Style char arrays as strings. So, my assumptions that you still are on C. Otherwise, you would std::string. Ìn C++ there is no jsutification to use a char array instead of a std::string. Please see the C-Style solution: #include <cstring> #include <cstdlib> #include <cstdio> int main() { char data...
62,230,431
62,230,736
Debug assertion (invalid comparator) when sorting in a QTreeWidget
I've the following custom QTreeWidgetItem that I use in my QTreeWidget: #ifndef FEDERATELISTITEM_HPP_ #define FEDERATELISTITEM_HPP_ #include <QTreeWidgetItem> class FederateListItem : public QTreeWidgetItem { public: enum Type : int { Federate = 101, FederateNamespace = 102 }; public: FederateListIte...
My guess written in comment: You don't consider the case that (type() == Type::Federate) && (other.type() == Type::FederateNamespace) which should result in false regardless of the text(0)s. I know this VS error and it results from an assert which checks !(B < A) for A < B to ensure that the strict order is achieved/g...
62,230,650
62,230,814
C++, should I call destructor?
In c++ I have a class which allocated memory using new[] so I wrote the destructor as following: Matrix::~Matrix() { delete[] data; } My Matrix class contains field called complex which is a member of a class Complex that I wrote. my question is, should I call the destructor for complex too, and how?
No the destructor of the outer class calls the destructors of inner data members. If you compile and run the following code, u will see that the destructor of A, the class of the inner data member, is called although it hasn't been called explicitly in B destructor #include <iostream> struct A{ ~A(){ std::c...
62,230,704
62,230,805
What does basic_string<char> means in typedef basic_string<char> string;
Hello does anyone know what basic_string<char> in typedef basic_string<char> string; stands for? What does basic_string<char> mean?
It's basic type for creating different strings with different types that are representing a symbol. For example, in typedef std::basic_string<wchar_t> std::wstring; they make analogical string but with wchar_t type.
62,230,846
62,230,927
C++ partial template specialization issue
Given a matrix class using index_t = int; template<index_t M, index_t N, typename S> struct mat { // matrix implementation }; I would like to have a generic way of obtaining the elementCount for a given type T that will work for both matrices and scalars. For example, I imagine being able to do this: dimensionalit...
First, the specialization cannot have more template parameters than the primary template, but your code puts typename = std::enable_if_t for the arithmetic case. Secondly, in order to make this std::enable_if_t to work, it would need to result in something that makes the specialization more specialized than the primary...
62,230,868
62,230,999
"lambda capture" on regular function?
void startDrawLoop(function<bool()> func) { while (func()) {} } int main() { CubeRenderer cubeRenderer; TextRenderer textRenderer; // Do initialization auto drawLoop=[&] () { cubeRenderer.draw(); textRenderer.draw(); return true; } startDrawLoo...
You can just make drawLoop accept arguments and call it from a lambda that does the capture. void startDrawLoop(function<bool()> func) { while (func()) {} } bool drawLoop(CubeRenderer const& cubeRenderer, TextRenderer const& textRenderer) { cubeRenderer.draw(); textRenderer.draw(); return true; } int ...
62,230,886
62,231,145
I cant iterate through pixels of all the image, it is iterating through parts of it. OpenCV
I have the following code: void white(Mat&src,Mat&dst){ double h = src.cols; double w = src.rows; dst = src.clone(); for (int i = 0; i < dst.rows; i++) { for (int j = 0; j < dst.cols; j++) { dst.at<uchar>(i, j) = 255; } } } My expected result is to get a completel...
It's a color image. Each pixel consists of 3 values. You have to set each color channel void white(Mat&src,Mat&dst){ double h = src.cols; double w = src.rows; dst = src.clone(); for (int i = 0; i < dst.rows; i++) { for (int j = 0; j < dst.cols; j++) { for (std::size_t c = 0; c < 3; ++c) { dst....
62,230,935
62,231,081
Trying to understand passing by reference C++
I understand the basic difference between the passing by value and passing by reference. Passing by value means that you pass values as function arguments and passing by reference means that you just simply pass the variable. What I don't get is how exactly works. Here is my example. #include <iostream> // Initializin...
You are correct that the unary & operator gives the address of a variable. However, & in function arguments is not the address-of operator--it's marking that particular parameter as being pass-by-reference, which has different semantics than passing around pointers. If you want to pass in pointers, you'd use int *first...
62,230,973
62,231,142
Assigning a variable within a class with value of a method
Is there a way to assign a variable within a class with a value of a class method? I was trying the example below, but it is obviously not working. Is there a correct way of doing this? #include <iostream> using namespace :: std; class rectangle { public: rectangle(double h, double w) { height...
The problem is that member variables are initialized in the order they are declared within the class. Also, your constructor creates the object before you have actually initialized width and height, as you do your initial assignment in the body of the constructor, rather than in an initializer list. Thus, when myarea i...
62,231,362
62,231,506
Using template value inside nested class
I have the following class definition: template <int B> class SparseBitvector { typedef typename std::vector<std::bitset<B>> BitsetVector; public: class iterator: public std::iterator<...> { public: explicit iterator(..., BitsetVector::iterator* _chunksIt, ...) {...} } } At compila...
You need to use typename keyword for depended types. Here for example typename BitsetVector::iterator* _chunksIt //^^^^^^ Secondly, there is no typename needed for the template type alias typedef std::vector<std::bitset<B>> BitsetVector; // or better use // using BitsetVector = std::vector<std::bitset<B>>; The minima...
62,231,637
62,231,839
How do I save an object containing a vector of another object into file and read back from file using binary files in C++?
This is my code for reading and Writing vectors; I get no errors while execution, but whenever I read back from it; it gives random values of integer instead of 50, and 100. What is it that I am doing wrong? I have used vector objects inside of another object, and I am trying to file it using binary filing of objects. ...
Basically what you're doing wrong is that you can't just cast C++ objects to char * and dump some bytes on disk and expect that to work. Now that is going to work in some limited circumstances like when you're just writing primitive objects like integers or structs containing only integers or something of the sort, but...
62,231,780
62,232,046
For which class is the instance created and what is the derived class doing in this code?
What is the derived class doing in this code like: class Base { public: virtual std::string Name(){ return "Base Class"} }; class Derived : public Base { public: std::string Name() {return "Derived Class"} } int main() { Base* object = new Derived(); return 0; } I was following a tutorial but d...
The goal is to implement polymorphism, it's a OOP concept which allows you, among other things, to make derived class methods override the base class. Consider the following: class Base { public: //virtual keyword allows method to be overriden virtual std::string Name() { return "Base Class"; } //virtual de...
62,232,059
62,232,121
getting error as deprecated conversion from string constant to 'char*' [-Wwrite-strings]
I'm getting error as deprecated conversion from string constant to 'char*' [-Wwrite-strings] at initgraph() function // C Implementation for drawing circle #include <graphics.h> //driver code int main() { int gd = DETECT, gm; initgraph(&gd, &gm, ""); //here I'm getting an error of string circle(250...
"" is a c-style string literal whose type is const char[1] and could convert to const char* implicitly. Implicit conversion to char* is not allowed since C++11. In C, string literals are of type char[], and can be assigned directly to a (non-const) char*. C++03 allowed it as well (but deprecated it, as literals are co...
62,232,180
62,233,060
How is [intro.object]/3 in the C++17 Standard Reference to be understood?
[intro.object]/3 of N4659 (March 2017 post-Kona working draft/C++17 DIS) states that: If a complete object is created ([expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std​::​byte” ([cstddef.syn]), that array provides storage for the created object...
How does that work out and harmonize with the basic things about arrays e.g. sizeof(array)? There is no interference between what that paragraph says and sizeof and other properties of an array. Besides pointers, what other complete objects do arrays provide storage for? It appears you misunderstood the examples. I...
62,232,308
62,234,799
Table/Grid using MFC
I just started developing an MFC application for the first time and I'm hoping to get more familiar with the whole "controls" concept. I am using the dialog editor in visual studio and so far I was not able to find functionality to add a simple table/grid. It seems quite basic to me, but I can't even find reliable info...
I use CGridCtrl which is very powerful and does a lot of the legwork for you.
62,232,753
62,234,967
What are the differences between a pointer and a reference in Rust?
A pointer * and a reference & in Rust share the same representation (they both represent the memory address of a piece of data). What's the practical differences when writing code though? When porting C++ code to Rust, can they be replaced safely (C++ pointer --> rust pointer, C++ reference --> rust reference) ?
Use references when you can, use pointers when you must. If you're not doing FFI or memory management beyond what the compiler can validate, you don't need to use pointers. Both references and pointers exist in two variants. There are shared references & and mutable references &mut. There are const pointers *const and ...
62,232,902
62,232,946
C++ for with multiple control statements using comma operator
How does comma operator if it is used in a 'for loop' for writing multiple control statements? i tried #include <iostream> using namespace std; int main() { for (int x = 0, y = 0; x < 3, y < 4; ++x, ++y) { cout << x << " " << y << endl; } return 0; } and it seems like only t...
This is how comma operator works. Its 1st operand x < 3 is evaluated, then the result is discarded; then the 2nd operand y < 4 is evaluated and the value is returned as the return value of the comma operator. x < 3 has not any effects here. You might want to use operator&& or operator|| for this case, e.g. x < 3 && y <...
62,232,953
62,288,308
Omnet++ issues running veins_inet example- undefined reference
This question is similar to Veins_inet: undefined reference to `__imp__ZTVN5Veins17VeinsInetMobilityE' when building in OMNet 5.1.1 I am running the latest versions of Veins, Sumo, Omnet, and Inet at the time of posting. I have created a project to run the veins_inet example. This project reference both INET and Veins...
I was running unstable builds of Veins and Inet. Updating these fixed the problem.
62,233,070
62,233,531
SFML player movement help in c++
I'm completely new to sfml, so I was following a tutorial on youtube. I did exactly as the guy did but still I'm having issue with my movements. Basically what's happening is that if I press a movement key the player (which is just a rectangle shape), moves just for a bit and when I release the key the player returns t...
The problem is you creating a character every frame in 100.0f 100.0f in while loop. So, you need to move the code of creating a character out of while loop. int main() { sf::RectangleShape player(sf::Vector2f(100.0f, 100.0f)); player.setFillColor(sf::Color::Red); while(window.isOpen()) { ...
62,233,076
62,234,323
Is it undefined behaviour to not call the destructor of an object?
This may seem like an obvious question, however I haven't been able to find the answer written anywhere explicitly. Consider the following code: { std::aligned_storage_t<sizeof(int), alignof(int)> storage; int& i = *new(&storage) int; } Here, I start the lifetime of an objected named i but this lifetime has no...
No this is not undefined behavior. The destructor of an object does not need to be called. (C++ standard example) N.B: Nevertheless, the life-time of the int object created by the placement new expression ends at the closing brace in you example. An object life-time ends if the destructor for that object is called or i...
62,233,356
62,233,460
Returning a pointer instance variable in C++
I have a command pattern class with a pointer to another object (let's call it Duck). Its subclasses will use Duck, but to control and track when Duck is used (for debugging) I made Duck private and subclasses can only get it through a method getDuck(); class Command { private: Duck* target; public: ...
Conceptually, there are two kinds of pointers: owning and non-owning. An owning pointer indicates that the holding object/function owns the allocation and is responsible for deleting the object. A non-owning pointer is a "borrowed" object; the holding object/function does not own the object and is not responsible for c...
62,233,423
62,236,225
How to add buttons to a main window by programmatically in Qt and change styles them by use css file?
I will add two buttons to the a dialog and I want to change style sheets of them by use css file: I also define the buttons as follows that didn't work: sendButton = new QPushButton(); sendButton->setVisible(true); sendButton->setText("sendButton"); sendButton->setStyleSheet("QPushButton#sendButton {\n" ...
If you are using the ID Selector QPushButton#objectName, be sure to also set the object name for your QPushButton, otherwise the selector will not work sendButton = new QPushButton(); sendButton->setVisible(true); sendButton->setText("sendButton"); sendButton->setObjectName("sendButton"); /* Set the object name */ se...
62,233,657
62,237,274
C++ Qt - Reading specific portion of a text file
I want to read a specific portion of a text file in a list widget. I have try different ways and looked online for some solutions but I couldn't find much. Im new using Qt but getting along well with it for the most part. QFile YearInfo("C:/Users/Documents/info.txt"); YearInfo.open(QIODevice::ReadWrite | QIODev...
The code that you have written works as long as you are trying to extract a section of text formatted in the following way 2019 Position Division Title <~~ this line is extracted Date (W.M./R.M./J.R) <~~ this line is extracted More stuff <~~ this line is extracted * If you have something formatte...
62,233,667
62,233,856
Sequence Containers - why a few expressions are only supported by a few sequence containers
I was going thru Sequence Containers named requirement : https://en.cppreference.com/w/cpp/named_req/SequenceContainer But then it states that the following expressions must be valid and have their specified effects for the sequence containers named: example: seqcnt.pop_front() Destroys the first element....
Because sequence containers are different and have different performance-friendly capabilities. A std::array is a fixed-length container; you cannot remove elements from it, because it's length is fixed at compile-time. So functions that remove (or insert) elements aren't present. std::forward_list, by definition, goes...
62,233,823
62,233,882
Is there a way to calculate the length of an arry inside a function instead of pass in as parameter?
I'm new to C++, and here is a template selection sort function I wrote which takes in an array and it length as parameter. """ template <class T> void mySort(T a[], int len) { for (int i = 0; i < len; i++) { int min = i; for (int j = i+1; j < len; j++) { if (a[min]>a[j]) ...
First, I know if we pass in array in to a function, it is actually not the copy of this array, so what is whole concept behind this? Is that we pass in its reference or the pointer to first index? It's a pointer to the first element. Even though you wrote T a[], the language converts it to T* a in a function paramete...
62,234,306
62,285,632
How to store zoom of Direct2D window when using WM_MOUSEWHEEL message handling
I'm trying to zoom in out of my ID2D1HwndRenderTarget* renderTarget-window at the mouse position using the Direct2D helper functions. After some testing I've discovered that GET_WHEEL_DELTA_WPARAM(wParam) returns 120 (int? short?) for each mousewheel click. But now need to know how to store my zoom level. Because ever...
As suggested by Jonathan Potter, to solution is pretty simple by just adding the zoom factor to the class containing my renderTarget
62,234,542
62,234,691
I have overloaded << and = operators. Why when I assign an object to another and try to print it I get junk printed out?
I have a program with a class Length. This class has an attribute named size of type int and a dynamic array *numb of type char. I have overloaded operators << and = so that I can print object values and assign values of an object to another. If I leave the return type of operator = to void, the program seems to work f...
You should return here reference: Length& Length::operator =(const Length &x) { if (this != &x) { delete [] this->numb; this->size = x.size; this->numb = new char[this->size]; memcpy(this->numb, x.numb, this->size); } return *this; } And add copy constructor: Lengt...
62,234,569
62,235,224
Arduino base 2 calculator not working C++
This is my code for an Arduino, I think the problem is the input(//nr1 and //nr2) because it worked before changing it to its current state. Thank you for helping in advance! int nr1 = 0; int nr2 = 0; int rs = 0; void setup() { // put your setup code here, to run once: pinMode(2, OUTPUT); pinMode(3, OUTPUT); p...
In your loop, you never assign nr2 a value. Maybe you want this: const unsigned int pin9 = (digitalRead(9) == LOW) ? 0 : 1; const unsigned int pin10 = (digitalRead(10) == LOW) ? 0 : 1; nr2 = pin10 << 1 | pin9; The above code fragment reads pin 9 and 10 once, converts them into a one or zero, then calculates nr2 base...
62,234,629
62,234,827
How to concatenate a string at the end of another string after using getch
For this code: #include <iostream> #include <string> #include <conio.h> int main() { std::string a; char c{}; while (c != '\r') { c = getch(); a += c; } a += "xyz"; std::cout << a; } Input: 12345, then Enter key Output: xyz45 How do I stop this from happening? Desi...
You need to avoid adding \r character to the string, something like: while ((c = getch()) != '\r') a += c;
62,234,768
62,234,894
Initialize array of pointers in a class and retrieve it in a different one
I want to initialize an array of pointers in a file, array.cpp, and retrieve it in a different main.cpp. I now have six headers/src files: parent.h/cpp, childA.h/cpp, childB.h/cpp. class Parent(){ public: Parent(); virtual void sayHi() = 0; }; Parent::Parent() {} class ChildA : Parent{ public: ChildA() ...
Simply use a std::vector instead of C arrays: class Array { public: Array() {} std::vector<Parent*> get_array(); }; std::vector<Parent*> Array::get_array() { return { new ChildA(), new ChildB(), new Child() }; } int main() { Array a; std::vector<Parent*> res = a.get_array(); res[0]->sayHi(); ...
62,234,931
62,236,303
Recursive computation using variable templates - gcc vs clang
Consider the following example: #include <cstdio> template <int N> int fib = fib<N - 1> + fib<N - 2>; template <> int fib<2> = 1; template <> int fib<1> = 1; int main() { std::printf("%d %d %d", fib<4>, fib<5>, fib<6>); } GCC 7.x, 8.x, 9.x, and 10.x all print out the expected result of 3 5 8. Clang 5.x, 6.x, 7...
From [basic.start.dynamic]/1: Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, is partially-ordered if the variable is an inline variable that is not an implicitly or explicitly instantiated specializati...
62,235,203
62,235,259
Do I need to use unique_ptr over std::function
I have a factory returning a function for data processing class Factory { function<void(Data&)> build(); } Now I am struggling whether the return type should be function<void(Data&)> or unique_ptr<function<void(Data&)>>. In other words, how heavy is the std function, is it okay to copy it around or is it better t...
std::function uses some form of type erasure, therefore, it itself shouldn't be too big. For instance, in my experiment with GCC and libstdc++, all instances of std::function I tried had 32 bytes: live demo. Therefore, moving std::function objects should be relatively cheap (copying might be a different thing). Anyway,...
62,235,322
62,298,518
UE4(С++) Сan I find out which key was pressed
In the project I need to process pressing numbers, for this I created a special Action Map: ActionMap After I announce the click handler: PlayerInputComponent->BindAction("EnterNum", IE_Pressed, this, &AMainPlayer::EnterNum); Can I know which key was pressed or I should create a handler for each number?
I see what you mean, but unfortunately you have to create a separate method for each number. For example, you can have an action mapping like this: Name: Num0 0 Num_0 Name: Num1 1 Num_1 ........... Then bind every single number with the corresponding method. Although I would agree it would be a very useful fea...
62,235,329
62,235,812
Call to non virtual function in derived class from base class (C++)
test is not a virtual function and is defined in both base and derived class. I have a derived class object. It ends up calling test of the base class instead of the one in the derived class. Why is this happening? How can I set it up such that test is called depending on the object type. current o/p B func ...
There ere 2 ways to archive the desired result: Using virtual Declaring base class functions as a virtual will make sure to call the most higher inheritance of the target functions by default. For example, in your case: class A { protected: /** * Declared also in the derived class, so as long the current obje...
62,235,979
62,255,976
Is it possible to make a cgal 3d multi-doamain mesh with no internal segmentation?
I am reading the "mesh_implicit_domain" example from here It uses a function wrapper to indicate the union of domains indicated by two functions(these 2 domains intersects and form a larger closed domain). But the cut view nearby on the page shows cgal's algorithm segment the mesh (i.e. clearly depict boundary of the t...
After quickly looking at the code, the default constructor defines 2 subdomains which is why you have the boundary between them. Since I don't think the "OR" is implemented in this class. I see two solutions: - use only one implicit function and do the "union" directly in the implicit function - Define your own domain,...
62,236,089
62,236,139
Why can an overloaded operator return something else than its return-type?
I was practicing for one of my upcoming exams and I came upon a weird piece of code in an exercise. For context, it's one of those exercises where you have to determine whether the code will run or not, what's wrong with it etc. The code that I find weird is the following: class A { int x; public: A(int i =...
int is implicitly convertible to A, via A(int) constructor. Your operator+ in effect performs return A{a.x + x}; This is not specific to overloaded operators - whenever an expression of one type is provided where another type is expected, the compiler is looking for ways to implicitly convert the former to the latter.
62,236,187
62,236,427
Are MOVNTI stores reordered relative to other MOVNTI stores made by the same thread?
TL;DR: I understood MOVNTI operations are not ordered relative to the rest of the program, so SFENCE/MFENCE is needed. But are MOVNTI operations not ordered relative to other MOVNTI operations of the same thread? Assuming I have a producer-consumer queue, and I want to use MOVNTI on producer side to avoid cache poll...
movnti stores are weakly ordered relative to each other as well. In asm you definitely need sfence after storing the data to get release semantics for the store to producer_index, whether you do that with movnti or a plain mov store. It might happen to work most of the time that the separate store wouldn't become visi...
62,236,358
62,236,405
How do I make it so no matter how many times the user presses enter with a blank string, it always prints the 'start' string?
This is my code - How do I make this loop unlimited? Like any terminal when you press enter with a blank string it rewrites your root #include <iostream> #include <windows.h> std::string input_t; void startup(std::string start) { std::cout << start; while(true) { while ( n = std::cin.get() ) { ...
You can use std::getline to keep reading in strings up to a newline: while(std::getline(std::cin, input_t)) { if (line.empty()) { std::cout << start; continue; } // else do stuff with input_t, or break }
62,236,657
62,236,675
What does "WM" mean in C++?
I just had a question. Why do we use WM before everything like WM_COMMAND or WM_KEYDOWN or WM_INITDIALOG? What does WM mean? I'm making a game in C++ and I didn't know what WM was used for.
I can't say with any real authority but a shrewd 'guess' would be "Window Message." Just before the definition of the first WM_ macro, in the WinUser.h header file, this comment appears: /* * Window Messages */ #define WM_NULL 0x0000 #define WM_CREATE 0x0001 //...
62,236,680
62,243,862
How can I insert tabs 4 spaces-wide and delete them by two spaces?
I like this type of indentation in C++: indents are 4 spaces wide, except for private/public/protected specifiers, which are indented only by 2, and do not alter the indentation of following lines. Example: class A { int x; public: int y; } int func() { return 1; } Therefore I would like Tab to insert...
This can be done by cino-g option when using cindent. For example, add this line in .vimrc :set cinoptions=g2 Also read following help topics to see more about C/C++ indenting: :h C-indenting :h 'cinoptions' :h cinoptions-values :h cino-g
62,236,883
62,236,993
reinterpret_cast fails constexpr function
Trying to create a constexpr capable class that reinterprets the bits of an IEEE double. Example: constexpr double pi = 3.14159265358979323846; constexpr fixedpoint a(pi); However, running into the problem that reinterpret_cast is not a constant subexpression. I am using this in the constexpr fixedpoint& operator=(dou...
Yes, use std::bit_cast, which is in header <bit>: #include <bit> #include <cstdint> constexpr double pi = 3.14159265358979323846; constexpr auto fraction = std::bit_cast<std::uint64_t>(pi) & 0x000F'FFFF'FFFF'FFFFull; You'll need a compiler with C++20 support. Currently there aren't any, but from Clang 9 you can at lea...
62,237,259
62,237,423
C++ Return a functor object as std::function
I have a factory method returning a std::function class Builder { public: function<void(Data&)> build(); } and a functor object class Processor { protected: vector<int> content_; public: void operator()(Data&) { .... } } Now I want to return the functor in the factory method, and I write fu...
A std::function hold and own its value. In fact, it requires callable object that are copiable so it can copy it when itself is copied. Your function would be perfectly fine like this, and potentially faster: function<void(Data&)> build() { Processor p; // fill items return p; // p moved into the returned...
62,237,802
63,025,933
Definition data of ClassTemplateSpecializationDecl is null
I recieve a class alt::VectorLayout<int, 4> for example, as a ClassTemplateSpecializationDecl and I'm trying to process the field and methods of the class, but it fails on an assertion where the definition data is null. I have the presumption that the template specialization is a forward declaration so it's not instant...
I could solve the issue with Sema::RequireCompleteType. I found that there would be no way to retrieve the Sema purely from a ClangTool instance. Instead of processing the source files with ClangTool, I made a CompilerInstance where the instance of the Sema was retrievable and ran a FrontendAction on the CompilerInstan...
62,237,854
66,459,221
DirectX 11 How process an image from sharedHandle on the GPU
I have a texture that exists on the GPU, I have a sharedHandle to that texture and want to do some image processing on that picture. I want to get the texture cordinates of the pixels of a certen color. For example I want all pixels of the color r135, g80, b175 with a shade variation of 40 (so a green color of 70 and ...
Solved this by first calling OpenSharedResource, CreateShaderResourceView, CopyResource, Map and then using the D3D11_MAPPED_SUBRESOURCE.pData as a starting pointer.
62,237,869
62,237,901
Unique pointer to Base class
I have two classes, Base which contains virtual method and D which contains overload that method. I want to create a variable with Base type, than pass there class D which inherits class Base. It's my implementation: #include <iostream> #include <vector> #include <memory> #include <cstdio> #include <fstream> #include <...
D inherits from B privately. Therefore, D* is not convertible to B*. You likely want class D : public Base { ... };
62,238,055
62,238,486
Insert data into an istream
I'm reading data from an ifstream. I have an object whose operator>> reads an integer n, an integer m and then n rows of m integers (a matrix). In my ifstream, I have a matrix list but without the integers n and m at the start of each matrix block. I would nevertheless like to read the istream using the >> operator of ...
The challenge is that once your matrix starts to extract something, you have no control anymore on the istream that is used. You can think of the following alternatives: Creating an adapter for the matrix with its own operator<< overload. You can then tailor the behavior of the extractor. But you'd probably have ...
62,238,227
62,238,268
error: assignment of function 'void digitalWrite(uint8_t, uint8_t)
Warning: I'm new to C++ (and most of programming in general) and am learning the language to be able to write code for my arduino I'm learning how to use a shift register using the Arduino IDE which i believe is in C++. Here is the code: const int latchPin = 12; // connected to ST_CP of 74HC595 const int clockPin = 8; ...
This line is the problem: int datArray[16] = (252, 96, 218, 242, 102, 182, 190, 224, 254, 246, 238, 62, 156, 122, 158, 142); Change it to: int datArray[16] = {252, 96, 218, 242, 102, 182, 190, 224, 254, 246, 238, 62, 156, 122, 158, 142};
62,238,240
62,240,178
Using Intel MKL to convert real time domain data to complex frequency and phase data and the inverse as well
I'm writing an audio plugin and I would like to convert a series of real numbers representing sample values into a complex array representing frequency and phase. Then I want to be able to do the opposite, turning a complex array of frequency and phases to a series of real numbers, reconstructing the original data. I'm...
Every real number is a complex number: ℝ ⊂ ℤ. So going forward from float or double in time domain to complex is trivial. The language does that for you! #include <complex> #include <iostream> int main() { double d = 42.0; std::complex<double> z = d; std::cout << d << " = " << z << '\n'; } Output: 42 = (42...
62,238,337
62,238,629
C++ broken_promise exception
I'm learning about std::async and came across the broken_promise exception. However, the following sample code doesn't seem to be causing the broken promise exception. My understanding is that when the promise is destroyed and the future is still waiting, the exception should be thrown. However, in my code the call to ...
The primary problem is that the wrong future is being waited on. You are waiting on int childValue = fut.get(); when you should be waiting on int childValue = retFut.get(); That being said, std::async is a part of C++ that is best sidestepped. In practice, it rarely delivers and in complex projects it's better to us...
62,238,412
62,238,554
binary_search() function doesn't work in my function body
The question is - Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element K. The task is to find the index of the given element K in the array A. Input: The first line of the input contains an integer T, denoting the total number of test cases. Then T test cases fo...
One of the preconditions of std::binary_search as you can see here, is that the array where you are searching on, must be sorted, instead you can write your own linear search: template<class Iterator, class ToFind> bool linear_search(Iterator start, Iterator end, const ToFind& element){ while(start != end){ if...
62,238,487
62,238,708
Receive any iterable container
Is there any way to receive any iterable container as a parameter? I would like a function to be able to receive any container while being able to begin() and end() on it. Unless I am wrong, every container should have these functions (std::view does not?). Specifically, is there a way to receive a Container as an argu...
You can simply use the same way the standard perform this action: template <typename Iterator> void do_stuff(Iterator first, Iterator last) { for (auto it = first; it != last; it = std::next(it)) { // do stuff with *it } } int main() { std::vector<int> vec = {1, 5, 9}; do_stuff(vec.begin(), ve...
62,238,613
62,238,812
C++: rvalue reference constructor and copy-elision
I'm trying to understand the rvalue reference constructor and assignment operator. I created the following source code which should invoke the rvalue reference constructor, however it doesn't occur. My suspicion is copy-elision optimization is the cause. Does anyone know if that's the reason? Also, if copy-elision ...
Add the following to main(): X x2(std::move(x1)); this manually indicates the object x1 can be moved from to work around copy-elision. copy-elision is not always invoked, so there may be cases where the rvalue reference constructor and assignment operator are required.
62,238,819
62,241,479
Can static and dynamic template initialization be interleaved?
As I understand it, given the following code: template<int N> int i = i<N - 1> + i<N - 1>; // primary variable template template<> int i<0> = 1; // and explicit specialization the following program must return 2: int main () { return i<1>; } but this program can return 0 or 4: int main () { return i<2>; } si...
You know from Recursive computation using variable templates - gcc vs clang that the dynamic initializations of i<1> and i<2> are indeterminately sequenced. Indeterminately sequenced evaluations can't interleave (overlap): Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is se...
62,239,353
62,239,387
C++: How to keep common code path for multiple overloaded functions?
Does anyone know how I can keep the code in swap_1() and swap_2() common? I'm a bit confused how to do that because the referencing of the argument types are different. // overload the function call template<class T> void swap_1(T&& a, T& b) { T tmp {move(a)}; a = move(b); b = move(tmp); } template<clas...
You could create a third template and call it from the other templates: template<class T, class U> void swap(T&& a, U&& b) { typename std::remove_reference<T>::type tmp {std::move(a)}; a = std::move(b); b = std::move(tmp); } // overload the function call template<class T> void swap_1(T&& a, T& b) { sw...
62,239,467
62,239,512
dynamic memory allocation to create array of objects using constructor with arguments c++
How can I allocate an array of objects using a constructor that takes an argument? I don't even know if I can? Or do I just have to create another class method to initialize the objects? #include <iostream> using namespace std; class Animal { string name; public: Animal(){} Animal(string name) : name(name...
The same way you'd do it for static arrays: #include <iostream> #include <string> class Animal { private: std::string name; public: Animal() = default; Animal(std::string name) : name(std::move(name)){} virtual ~Animal() = default; Animal(const Animal &other) : name(other.name){} void toSpeak() const { ...
62,239,604
62,241,619
How to rotate a point around an arbitrary axis?
I want to rotate a point in OpenGL around an arbitrary axis. I want to utilize that to rotate a sphere. This is what I got so far: float degreeBetweenTwoVec(glm::vec3 &a, glm::vec3 b) { float prod = b.x * a.x + b.y * a.y + b.z * a.z; float mag_axis = sqrt((b.x * b.x) + (b.y * b.y) + (b.z * b.z)); float mag_...
I recommend to use a rotation matrix. Use glm::rotate(), to set a rotation matrix by axis and angle. Convert the point to glm::vec4 and transform it by the rotation matrix: #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> glm::mat4 rot_mat = glm::rotate(glm::mat4(1.0f), glm::radians(degree), axis); glm::...
62,239,627
62,239,685
C++ - Why does this have a strong exception guarantee?
In The C++ Programming Language (4th edition), Stroustrup shows the following snippet when discussing exceptions (corrected version taken from this errata): template<typename T, typename A> void vector<T,A>::reserve(size_type newalloc) // flawed first attempt { if (newalloc<=capacity()) return; // never...
As François pointed out, std::copy is changing v, which isn't a member of this. Therefore, if it fails, this is unaltered.
62,239,636
62,239,851
Overload resolution based on template parameter
I'm unsure if what I want to do is possible in C++, so asking here. I have a templated class MyClass that has an optional template argument idx. I have another non-templated class OtherClass. What I want to do is to do some sort of overload resolution based on idx: If idx is provided (has a value other than -1), I wan...
Something along these lines, perhaps: template <typename T, int32_t idx=-1> class MyClass { OtherClass m_other; void myMethodHelper(T arg, std::true_type) { m_other.otherMethod<idx>(arg); } void myMethodHelper(T arg, std::false_type) { m_other.otherMethod(arg); } public: void myMethod(T arg)...
62,239,906
62,240,037
How to limit user input in C++ for strings & characters?
I'm trying to create a small restaurant program in which I'll be practicing everything I learned in C++ so far. However I jumped into a small issue. At the beginning of the program, I prompt the user whether they want to enter the program, or leave it by choosing Y or N. If the input is anything other than that the pro...
Before addressing your question I need to point out that you should always verify that the input was successful before doing anything with it. Processing variables which were not set due to the inout failing is a rather common source of errors. For example: if (std::cin >> ContinueAnswer) { // do something with suc...
62,239,974
62,242,738
Passing member function to Template function
Given the following function: template<class F, class... Args> auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared< std::packaged_task<return_type()> >( ...
In addition to what @IgorTandetnik has mentioned in the comments, you can also use std::bind with std::mem_fn to pass a member function to your method: struct Foo { void do_something() {} void do_something_else(int x, int y, std::string str) {} }; int main() { Foo foo; ThreadPool pool; auto func_sth = ...
62,240,054
62,240,070
C++ Stringstream initializations
I have two code snippets: This does not compile: std::string reverseSentence(std::string sentence) { std::stringstream stream = sentence; } This does: std::stringstream stream (sentence); It's my understanding that T foo = expr is T foo(expr). Thus, aren't the two stringstream initializations equivalent? Why is ...
The constructor of std::basic_stringstream taking std::string is marked as explicit, it's not considered in copy initalization like std::stringstream stream = sentence;. std::stringstream stream (sentence); is direct initialization, which considers explicit constructors too. Direct-initialization is more permissive t...
62,240,130
62,240,373
MAPI Stub Library cannot initialize MAPI for Outlook 2016(64bit)
My computer is Windows 7(64bit), I then install Outlook 2016(64bit). Then I follow the instructions in https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/how-to-link-to-mapi-functions?redirectedfrom=MSDN to use MAPIStubLibrary. The version of MAPIStubLibrary I use is updated on 2018-02-26. I include...
That means Outlook is either not installed or that it has a different bitness. Check Outlook bitness in File | Office Outlook | About Outlook.
62,240,203
62,240,231
How do I std::getline into a template type?
template <typename T> T getUserInput(std::string prompt = "") { T input; std::cout << prompt; if (std::is_same<T, std::string>::value) { std::getline(std::cin, input); } else { std::cin >> input; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); ...
When you call the function with some T other than std::string, then the getline code will not compile, since all the code needs to be compiled regardless of whether the branch is taken, or not. To avoid compiling the branch with the getline when not needed, you can use if constexpr, like this: if constexpr (std::is_sa...
62,240,838
62,241,083
String Pyramid with user input
I'm trying to read in a string and output it as a pyramid. I'm not concerned about the shape of the pyramid yet, I just want the string to output correctly. I listed an example of how I want the output to look like in my example code below. I would appreciate any help I can get, thank you. #include <iostream> #include ...
I think this code will produce your desired result. #include <iostream> #include <string.h> using namespace std; //Letter Pyramid //Ask user for input //Use loops to display user input as pyramid //User String "12345" /* 1 121 12321 1234321 123454321 */ int main() { //Store user input str...
62,240,917
62,241,155
Base64 Image encoding is incorrect
I am attempting to convert a .jpg file into base64 then into an svg file but my base64 is wrong I don't know if I'm doing something obviously wrong this is my first time working with base64 in c++ When I run the code I get an svg file with the proper format and the correct padding but the file is blank when I open it....
Your error is in the way you read the data from the file. Don't use getline on a binary file, apart from anything else it does not return the newlines to you. The second problem is that by using c_str() when you append each line you are assuming that there will be no null characters in your data, which is very unlikely...
62,240,930
62,240,993
How to make a declaration of a instance with parameter?
That's all my code class A{ public: A(int x){} }; int main() { A a; // error c2512 : no appropriate default constructor available if (4>3) a=A(3); else a=A(4); //and then do something with instance "a" return 0; } I wanna make a declaration of a instance ,and use it What should I do to...
To solve the compiler error, you would have to add a default constructor (one taking no arguments) to A, eg: class A{ public: A(){} A(int x){} }; Or: class A{ public: A() = default; // C++11 and later only A(int x){} }; Or, you can use your existing converting constructor and just make its argument op...
62,241,032
62,250,148
How to connect C++ system calls to freertos
I want to write a multi-threading program for microcontroller with free-rtos. but I don't want to use non-standard free-rtos functions, instead, I want to use the native c++ library to run parallel and async tasks. but I don't know how to write an adapter for connecting c++ system calls for thread creation to free-rto...
It seems that FreeRTOS has a POSIX threads adaptor layer. It's a subset, but probably enough to build a thread, mutex, and future from either GNU libstdc++ or clang libc++ against. You will almost certainly need a working std::atomic implementation. There's a lot of grot in POSIX threads that resulted from its retro-...
62,241,240
62,241,402
How to comprehend "std::future shared state"?
As per the documentation(http://www.cplusplus.com/reference/future/future/get/), which says that: [emphasis mine] Once the shared state is ready, the function unblocks and returns (or throws) releasing its shared state. This makes the future object no longer valid: this member function shall be called once at most...
According to the cppreference documentation on std::future: When the asynchronous operation is ready to send a result to the creator, it can do so by modifying shared state (e.g. std::promise::set_value) that is linked to the creator's std::future. Shared state here refers to some mutable stuff readable/writeable by ...
62,241,588
62,711,374
Canon SDK fails to download picture from camera
Below C++ with Canon SDK is about 80% working. It can set exposure time, set ISO, take pictures and save it to camera's SD card. However, after picture is taken, the code cannot save picture to my computer. Code never reach "EdsError EDSCALLBACK handleObjectEvent...". For some reason, my camera seem can not trigger...
Within take_one_bulb_photo() function. Before the last line "EdsCloseSession(camera);" Add below code; such as MSG msg; GetMessage(&msg, NULL, NULL, NULL); TranslateMessage(&msg); DispatchMessage(&msg); GetMessage(&msg, NULL, NULL, NULL); TranslateMessage(&msg); DispatchMessage(&msg); ...
62,241,676
62,246,861
how to use convex-hull concept to solve this problem
I was solving this SPOJ problem which uses concept of convex hull. Go through the above link to understand the question completely If this problem is changed a little bit and we are given a point say A(x,y) and asked to find maximum number of fences only around that particular point . My Approach (Correct me if i am ...
Your approach works fine. Both your problem and the SPOJ problem can be considered recursively as follows. Given a set of poles: determine the best possible outer-most fence Solve the problem again with the poles inside that fence Note that adding another pole to the problem will never lead to a worse result, becaus...
62,242,014
62,242,100
This code gives me runtime error. How to fix this code?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ this is a leetcode question and it start like thi...
In the converttoint function, I don't understand why you have: for (int i = 0; i < 3; i++) { number *= 10; number += array[i]; } I think it needs to be: for (int i = 0; i < array.size(); i++) { number *= 10; number += array[i]; } On a side note, you don't need all this vector stuff either (unless you'...
62,242,065
62,242,209
How to comprehend "std::relational operators (shared_ptr) compares directly the stored pointers"
As per the documentation(http://www.cplusplus.com/reference/memory/shared_ptr/operators/), which says: [emphasis mine] The comparison compares directly the stored pointers (i.e., the value the objects dereference to, and not their owned pointer (i.e., the managed objects that are deleted on destruction), which may...
Let's say, you have this struct: struct Foo { int a, b; }; Then you can generate aliased shared pointers like this: void f() { // create shared_ptr<Foo> orig(new Foo{1, 2}); // aliased pointer 1, points into object held by orig shared_ptr<int> pa(orig, &orig->a); // aliased pointer 2, ditto sha...
62,242,159
62,254,133
Returning the complete value in recursions
I've written a C++ code to convert a base 10 number into base two, but don't want the function to print it, but to return the value since I'll later need to use it in another function. The problem with returning is that the first time it returns it'll break out of the function, so it won't finish the process of convert...
Implementation of summing up (in fact it can be implemented iteratively but it seems you need to apply recursion so I provided recursive solution): int baseHelper(int a, int factor) { int returnedValue = 0; if(a==0 || a==1) returnedValue = factor * a; else { int adden...
62,242,378
62,242,399
got error while compiling memory allocation code of c++ program
i'm writing a memory allocation program in c++ but got an error in the program. i can't understand what is happening. Please help. #include<iostream> using namespace std; class Test{ int *m_ptr; private: void Test(){ m_ptr = new int(4); } ~Test(class Test){ cout<...
private: void Test(){ m_ptr = new int(4); } should be public: Test(){ m_ptr = new int(4); } There's no return type on a constructor, and if you want to use it in main it should be public. And ~Test(class Test){ cout<<"Object gets destroyed.."; } should be ~Test(){ ...
62,242,391
62,242,856
Have enum type of any tag in a class specialization
How to have enum type of any tag in a class specialization? as this works only for one ie. L enum : enum class K { a, b, c, d, e }; enum class L { a, c, e, }; template<enum L> struct J { constexpr static int N = static_cast<int>(L::e); int n[N] = { 7 }; void print() { cout << N << "\n"; ...
If you can provide one more template argument, you can pass any enums template<typename Type, Type en> struct J { // ... } and construct the object J <K, K::e> obj; obj.print(); (See demo online) Also checking the passed Type using std::is_enum, you can restrict the template types passed.