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,623,026 | 66,623,042 | MY C++ default constructor doesn't execute | I have a main routine that has two class objects.
One class has no parameters.
The other class has 1 parameter.
The class with no parameters does not execute.
Why not?
Main.cpp:
...
#include "Dummy1.h"
#include "Dummy2.h"
int main()
{
int x = 0;
Dummy1 First(); //This doesn't execute.
Dummy2 Second(x); //... | you came across most vexing parse. In short, C++ compiler will assume that your code is a function declaration, if this code can be perceived as a function declaration. To call the default constructor, you need to remove the parentheses, or write in curly braces.
So in code
SomeClass a();// func declaration
SomeClass b... |
66,623,157 | 66,623,369 | Is it possible to generate a variant from an integer sequence? | Would it be possible to generate a variant from an integer sequence like in this pseudo C++ sample:
#include <utility>
#include <variant>
template <int MyInt>
struct MyStruct{};
using MyIntegerSequence = std::make_integer_sequence<int, 3>;
using MyVariant = std::variant<MyStruct<MyIntegerSequence>...>; // Does not c... | It's possible, sure. The key is that one must use a pack expansion of some sort. Your struct takes an int non-type template parameter. So we must expand the integer sequence's pack to feed them into MyStruct one at a time.
MyStruct<MyIntegerSequence>... is not a pack expansion, since there is no template definition and... |
66,623,162 | 66,628,784 | What is the maximum time interval chrono can measure in C++? | I'm quiet experienced in programming, but new to C++. I'm trying to measure the time it takes to run a code. In the future I might write code that can take hours/days to finish itself. Therefore it is important for me to know the limits of the chrono time measurement. Accuracy in milliseconds should be sufficient.
What... | Here's an informative little HelloWorld:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
using namespace std;
using years = duration<double, ratio_multiply<ratio<86'400>, ratio<146'097, 400>>>;
cout << years{high_resolution_clock::time_point::max() -
... |
66,623,203 | 66,632,544 | How to detect SEXP type by using clang-tool | I want to detect "SEXP" return type function by using clang-tool , and print it .
My clang tool :
//define vistor
class myVisitor : public RecursiveASTVisitor<myVisitor>{
private:
ASTContext *ast_c ;
public:
explicit myVisitor(CompilerInstance *CI): ast_c(&(CI->getASTContext())){
myr... | I found where the problem is .
Need to add #include<R.h> #include<Rinternal.h> at the top of code
The headers of R are in /usr/share/R/include
But the path of clang will find header in normal include path , so we need to copy them into /usr/local/include/
|
66,623,549 | 66,623,641 | How can I access an array in another class via a pointer to that array in C++? | Usually in order to access a member variable of a class/object from a different class, you would use the arrow operator (->). In this case I would like to access an array, however the size of the array is only known at runtime, therefore I can't declare the array in the header file of the class. In fact, I only declare... | TokenPool::TokenPool(int K) {
...
int pool[K];
...
pointToPool = pool;
}
pool is declared on the stack, so it ceases to exist as soon as the constructor returns. You assign its address to this->pool, but the address no longer points into valid memory. Subsequently reading from this pointer results in u... |
66,623,616 | 66,623,711 | cannot convert 'this' pointer from 'const List<T>' to 'List<T> &' | I implement a doubly linked list. Then I used that linked list as container for stack. but I get Error C2662 'const T &List::last_elem(void)': cannot convert 'this' pointer from 'const List' to 'List &'. I tried to return as a value but it didnt work. I dont understand whether compiler points wrong point.
template<t... | Make last_elem() a const qualified with:
const T &last_elem() const
// ^^^^^
|
66,623,850 | 66,625,986 | Why did my code timed out if required time complexity is met? | I tried to solve CodeWars kata and got stuck on the time out error. I read in the comments that the code should be O(n) complexity. Though, my code is actually O(n). So, maybe i had made some mistakes and so on. Why did not this work? Should anyone explain why my code is slower than O(n) pls?
#include <string>
using n... | The biggest issue I see is that copy.find() & copy.erase() are more expensive than you think. They are essentially O(n), and since it's in a O(n) for loop, you have at least O(n^2) run time.
By counting letters, you can avoid that altogether. The code below is O(3n) --> O(n). It also passed all tests.
#include<string>
... |
66,623,931 | 66,625,271 | Creating global methods using templates that accepts single object as parameter in C++ | I have two classes Circle{float getArea()} and Rectangle{ float getArea()}. These two classes are not related to each other. I want to create a global method using templates that accepts a single object as a parameter and displays the area of the corresponding object.
#include<iostream>
using namespace std;
template<... | Just pass the call to the object:
#include<iostream>
class Circle{
private:
float m_r;
public:
Circle(float r): m_r(r) {}
float getArea() {return 3.14*m_r*m_r;}
};
class Rectangle{
private:
float m_a, m_b;
public:
Rectangle(float a, float b): m_a(a), m_b(b) {}
float getArea() {return m_a*m_b;}
... |
66,624,586 | 66,624,627 | vector.push_back increment shared pointer count? | In the following sample, the shared_ptr is a great help automatically freeing memory allocated by uf8toWide() (worker() has many code paths).
In my tests, Revisit.push_back() does not seem to increment the count of the shared pointer, and nothing can be retrieved in main().
Can this be done with smart pointers ? Other ... | vector<wchar_t *> Revisit;
should probably be
vector<std::shared_ptr<wchar_t>> Revisit;
in order to keep data referenced and prevent its automatic deletion (because p disappears right after being created).
Then you would have to use Revisit.push_back(p); (not fn).
And in this case
delete[] fe;
should be removed b... |
66,624,965 | 66,625,049 | Is overload resolution working differently inside template function? | Consider this piece of code.
Try to guess the output of the program before reading further:
#include <iostream>
using namespace std;
template <typename T>
void adl(T) {
cout << "T";
}
struct S {
};
template <typename T>
void call_adl(T t) {
adl(S());
adl(t);
}
void adl(S) {
cout << "S";
}
int main(... | The behaviors of name lookup are different for dependent name and non-dependent name in templates.
For a non-dependent name used in a template definition, unqualified name lookup takes place when the template definition is examined. The binding to the declarations made at that point is not affected by declarations vis... |
66,625,030 | 66,639,911 | GStreamer: get video from RTP, setting the format automatically | Let's say I've got a simple RTP video server:
ximagesrc ! video/x-raw,framerate=30/1 ! videoscale ! videoconvert ! x264enc tune=zerolatency bitrate=500 speed-preset=slow ! rtph264pay ! udpsink host=127.0.0.1 port=5000
And I'm receiving it just fine:
udpsrc port=5000 caps = "application/x-rtp, media=(string)video, cloc... | No. RTP streams are supposed to be initiated by SDP and RTSP control protocols which will tell you what kind of stream you are dealing with. If you want self describing media, perhaps try looking at MPEG-TS instead.
|
66,625,087 | 66,625,898 | OpenCL log file locates errors as if the code was a single long line | I produce a log file (with OpenCL on OSX) doing
void printErrors(const Program& program, const Device& device){
string buildlog = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device);
ofstream file("./error.txt");
file << buildlog << endl;
file.close();
}
But the resulting file seems to interpret the cod... | I think your issue is here:
char line[256];
file.getline(line, 255);
source += line;
getline will not include newline characters, so you will need to insert them explicitly. Try this:
source += line;
source += "\n";
This should also solve the issue of the entire source-on-one-line being included in the error message.... |
66,625,318 | 66,628,515 | C++ static reflection TS: would it support assign/call by name? | There is a C++ Technical Specification on static reflection (current PDF draft and cppreference page)
which might move into C++23 or later.
Would it be possible in the current draft (I understand syntax is perhaps not fixed yet)
to access struct fields / call class member functions by name?
For instance
struct Test {
... | get_pointer<X> gets you a pointer to member, get_name<X> gets its name. Throw in some iterating over members (also supplied), and handling of type mismatching (which could be done in c++03), and bob is your uncle.
C++ gives compile time reflection primitives; so you have to write the glue code yourself as far as I am ... |
66,625,332 | 66,625,333 | Yet another counterintuitive behaviour of vector's constructor | I hope you find this question and the answer instructional/educational (at least some of you).
First, lets try to guess the output of this program:
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<char> delimiters = { ",", ";" };
cout << delimiters[0];
}
Try to answer 2 questions:... | Well, as some of you may think (this is what I thought at the first place), this should lead to a compilation error, hence we are passing string literals instead of chars to the constructor, right?
Wrong!
Here we are trying to initialize a vector using two string literals, not two chars.
The initializer-list constructo... |
66,625,681 | 66,625,786 | Error in C++ Program for RGB to HSB conversion | I wrote the following code, which seems fine to me, but I'm getting a compilation error:
error: invalid operands of types 'double' and 'int' to binary
My Code:
#include <iostream>
#include <cmath>
using namespace std;
class ColourChecking
{
private:
double r, g, b;
public:
void hsb(double a, double c, double... | You cannot use the modulo operator on a floating point variable. Also modulo and division are not equivalent.
You can use the fmod function from math.h :
#include <math.h>
h = std::fmod(60 * ((g-b) / diff) + 360, 360);
|
66,625,728 | 66,632,462 | How to access elements of a std::vector<cv::Mat> and put them in separate matrices cv::Mat | I have a const std::vector<cv::Mat> containing 3 matrices (3 images), and in order to use each image further in my program I need to save them in separate matrices cv::Mat.
I know that I need to iterate over vector elements, since this vector is a list of matrices but somehow I can't manage it. At the end, I also need ... | In your code, note that imagesRGB is uninitialized, and its size is 0. The for loop is not evaluated. Additionally, the copyTo method copies matrix data into another matrix (like a paste function), it is not used to store a cv::Mat into a std::vector.
Your description is not clear enough, however here's an example of w... |
66,626,026 | 66,626,096 | c++ Destructor de-allocation failing | In the below c++ code, during destructor call, it is crashing with the below error.
If this message is printed, at least the program hasn't crashed yet!
But you may want to print other diagnostic messages too.
DSCodes(16782,0x1000efe00) malloc: *** error for object 0x10742e2f0: pointer being freed was not allocated
DSC... | In your Pair::Pair(const Pair &obj) you actually copy the pointer, which is double destructed lateron. You want to copy the content of the pointer instead (see the Pair::Pair(int p1, int p2) constructor).
|
66,626,404 | 66,626,454 | Where dose the compiler encounter floatinng point int the below program? What is the meaning of core dumped? | The below code is returning floating point error, where does it find the error from?
#include<iostream>
using namespace std;
int main(){
int x[10];
int y = 1000000000;
long z = 2312432321;
int a = 0;
for(int i = 0; i < 10; i++){
a = z/y;
x[i] = a;
y /= 10;
z %= y;
... | The error comes at execution time, not at compile time (so it is not the compiler that encounters the error).
On the last iteration, y /= 10 makes y be 0, so z %= y throws an error.
Also, as mentionned in the comments, you should use a debugger to detect those errors, that will help you in many situations, and save you... |
66,626,456 | 66,626,567 | unexpected behavior of overloaded operator "<<" c++ | I wrote a simple program to demonstrate the use of overloaded operator << in c++. According to this article: https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes?view=msvc-160, I tried writing my own code:
#include <iostream>
#include <string>
class Date
{
private... | Try with following:
int main()
{
Date dt;
std::cout << dt;
}
Which compiler you are using? Microsoft C++ compiler report a linking error with your main function without arg i.e. Date dt();
error LNK2001: unresolved external symbol "class Date __cdecl dt(void)" (?dt@@YA?AVDate@@XZ)
|
66,626,502 | 66,627,111 | How to make DFS algorithm continue working on a graph | I'm trying to search for a path(doesn't have to be the shortest path) on a 40 x 20 Graph. The starting and ending points are chosen randomly. The DFS works fine, until it hits and edge. Then, instead of going back and trying to search in the different direction, it just loops itself. Here's my code (small bit of it, bu... | A few issues:
You put the base case of your recursion in comments, but it is needed to end the recursion with a positive outcome:
if (startowy == koncowy) {
cout << koncowy << setw(5) << "target found";
return true;
}
The result of the recursive DFS call is ignored, and instead true is returned unconditional... |
66,626,659 | 66,627,100 | Interdependent header files and class/methods can't compile | I'm currently working on building a small ECS system, and in the process, I created an Application.h and Gameobject.h, where the Gameobject.h file requires both the declaration of the application class and some of its methods, and Application.h requires the gameobject class and some of its methods. I tried using a forw... | This is a common pitfall from those coming from Java (and likely C#) backgrounds. C++ sparingly defines class methods in header files, and only if they don't require any other dependencies, other than the class itself -- perhaps something else might be #included that they can use, but that's going off on a tangent. Any... |
66,626,746 | 66,627,822 | find volume of a box using object oriented programming with c++ | Write a class called boxVolume with length, width and height as data members and readData(), dispData() and computeVol() as functions. Also write a main() function to test the boxVolume class.
i tried -
#include <iostream>
class BoxVolume
{
public:
float length;
float width;
float height;
void re... | You should read a C++ introductory book to acquire the basics of the language first, and then start coding. I would suggest Accelerated C++ because is shorter than its competitors but still quite complete (at the time it was published). Now it lacks support for subsequent standards in the language, from C++11 onward, s... |
66,626,972 | 66,627,180 | How to delete types before T in a parameter pack? | For educational purposes (while reading book Modern C++ Design - A Alexandrescu) I want to write some helper to delete all types in parameter pack before type T.
For example delete_until_T<C,A,B,C,D> must be opened like tuple<C,D> or just <C,D>.
As I understand it may be done in old enough recursive way and non recurs... | One way of implementing this is to use partial specializations to match when the type that you're looking for is found in the variadic parameters.
// recursive case, first 2 template parameters don't match
template<typename T, typename, typename ...Ts>
struct delete_until_impl : delete_until_impl<T, Ts...> {};
// ba... |
66,627,005 | 66,627,230 | Reversing characters from input | I am trying to reverse a char which has been provided in input from an user. I am having issues with the reverse function, particularly the loop. I can't get it to work- can I get advice?
#include <iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char temp[len... | You have got several errors in the program.
The variable-length arrays are used here:
char temp[len];
This should not be applied in C++ since this invokes undefined-behavior. Note that this is a valid statement in the C99 standard.
There is a better alternative to this. That is to take the std::string built-in type i... |
66,627,155 | 66,627,412 | is there a way to use std::variant with arbitrarily many defined types? | I am just learning to use std::variant and I would like to declare a type list consisting of (in principle) arbitrarily many of my user defined types. I.e., something like
template<typename T>
struct MyType{
T x;
};
template<typename T, int N>
MyClass{
public:
MyType<T> y;
int z = N;
double w;
MyCl... | You indicated that you're looking to use another template parameter, to specify the number of values in the variant. In that case, it's a simple matter to use it to construct a std::integer_sequence, and then use it to create your variant type list.
#include <variant>
#include <type_traits>
#include <utility>
template... |
66,627,446 | 66,627,473 | How to prevent /* from creating a comment block? | I'm trying to print out the following:
cout << *pointer1/*pointer2 << endl;
However, because /* opens a comment block, everything past /* is treated as a comment. The solution I've come up so far is this:
int tempPointer = *pointer;
cout << *pointer1/tempPointer << endl;
This works but isn't very elegant.
Is there a ... | Just add a space or put the pointer dereference in brackets. (This also improves readability.)
cout << *pointer1 / *pointer2 << endl;
or
cout << *pointer1/(*pointer2) << endl;
|
66,628,814 | 66,758,715 | Meaning of RawStringFormats and Delimeters 'pb' in clang format | I cannot understand how does the following affect the formatting behavior in the clang format file:
RawStringFormats:
- Delimiters: [pb]
Language: TextProto
BasedOnStyle: google
Are these settings correct for a c++ project? (e.g. shouldn't the language be cpp?)
What does it mean 'pb' for Del... | [pb] as the delimiter there stands for ProtocolBuffers or Protobuf in short. The RawStringFormat formatting option is specifically for acting as a hint to detect and format code fragments that appear as raw strings within the file (for supported languages); It uses the Delimiters or the EnclosingFunctions to detect and... |
66,628,852 | 66,628,953 | C++: assignment operator not called | I have a following code which is below.
When I write o1 = o2, void operator=(TestClass& _rhs) is called. It's ok.
But when I do o1 = test_function();, first operator float() is called, then void operator=(float _value). It's logically correct, but why is void operator=(TestClass& _rhs) not invoked?
class TestClass
{
pu... |
why void operator=(TestClass& _rhs) is not involved?
Because that assignment operator is malformed. It should be:
void operator=(TestClass const& _rhs)
// CONST! ^^^^^
Your form, void operator=(TestClass& _rhs) will not accept prvalues (temporaries), like the temporary returned from test_function().
... |
66,629,081 | 66,629,148 | Constructor with an object as argument (C++) | I have this class:
class CContact {
public:
CTimeStamp m_Stamp;
int m_Num1;
int m_Num2;
CContact(CTimeStamp mStamp, int i, int i1) {
m_Stamp = mStamp;
m_Num1 = i;
m_Num2 = i1;
}
};
I get the following error:
Constructor for 'CContact' must explicitly initialize the member... | The error is self-explantory. Your CContact constructor is not passing any values to m_Stamp's constructor, so the compiler has to default-construct m_Stamp, but it can't because CTimeStamp does not have a default constructor.
You need to initialize CContact's members (or at least m_Stamp) in the CContact constructor's... |
66,629,159 | 66,629,240 | Pointer returning void working in C but not in C++ | I am trying to make a Native C/C++ app for Tizen platform and this a part of the code of a template Tizen Studio gives :
(Note this is C code)
static char*
gl_text_get(void *data, Evas_Object *obj, const char *part)
{
char buf[1024];
item_data *id = data;
int index = id->index;
if (index == 0)
... | In both C and C++, any pointer type is implicitly convertible to void*.
But in C only, void* is implicitly convertible to any other pointer type, whereas in C++ that is not the case, you need an explicit type-cast instead, eg:
Elm_Object_Item *it = (Elm_Object_Item *) event_info;
appdata_s *ad = (appdata_s *) data;
ite... |
66,629,160 | 66,631,847 | Exposing a generic method and preserving information about the type | I would like to build a generic event-bus in c++, which allows messages of arbitrary type to be passed into it, and which allows registering of handlers based on the type of the message. IE I would like to expose a method like the following:
void registerHandler((OutputType) handler(EventType));
such that after callin... | Extrapolating from the similar answers I put in the comments, this works for me:
#include <iostream>
#include <unordered_map>
#include <typeindex>
struct OutputType {};
struct EventType1 {};
struct EventType2 {};
struct EventType3 {};
OutputType event1(EventType1 event) { std::cout << "Called: " << __PRETTY_FUNCTION... |
66,629,278 | 66,629,448 | C++ not rounding as it should when using both cout and printf | I need to make a program that calculates cos(x) and my problem is that when I use printf for example cos(0.2) is 0.98 but it comes out as 0.984 and it's not rounding to 2 numbers.
My code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float x = 0.2;
cout << "x=" << x << " cos(y) y="... | As others have said in the comments, mixing std::cout and printf does not do what you want. Instead use the stream manipulators std::fixed and std::setprecision:
#include <iomanip> //Required for std::fixed and std::precision
#include <iostream>
#include <cmath> //Notice corrected include, this is the C++ version of ... |
66,629,443 | 66,641,142 | calling a function from a class inside a namespace? | I wrote a code with a class existing inside a namespace.
This is the header file: As you can see, the class is created inside the namespace, in frileg.h.
namespace frileg
{
class legeplads
{
public:
int x;
int y;
int z;
void print();
};
}
Then I also have defined the fun... | I was able to get this working using the following methods.
Create a new folder in VSCode. I named it SO_66629443_20210315 and put it in my X:\test folder
Add the 3 files.
Fix the missing includes. legeplads.cpp requires #include <iostream> and #include "frileg.h" and main.cpp requires #include "frileg.h"
Modify ma... |
66,629,735 | 66,629,788 | Memory allocation when passing a std::vector to a function in C++ | Consider the following simple example:
#include <vector>
void func(std::vector<int>* output) {
std::vector<int> temp(10000);
/* ... do work here and fill temp with useful values ... */
// now send the result to main
*output = temp;
}
int main(void) {
std::vector<int> vec;
// func will put useful values i... | From the reference for std::vector:
The storage of the vector is handled automatically, being expanded and
contracted as needed.
It is precisely this quality of std::vector that renders it quite easy to use.
In your code
*output = temp;
This line copies the temp vector into output, i.e., invoking the assignment oper... |
66,629,780 | 66,629,910 | Print the new value of an initialized integer after modifying it inside a void function? | I would expect the following C++ code to print 6, but instead it prints 5. How would I change it so that the new value gets printed?
#include <iostream>
void increment(int a) {
a++;
}
int main() {
int number = 5;
increment(number);
std::cout << number; // prints 5, not 6
}
| The way you have defined the function means that a copy of the number variable gets passed to it. Changing the copy inside the function does not affect the original variable.
If you want to refer to the original integer variable inside the function, you need to define the function to take a reference to the variable:
v... |
66,629,946 | 66,630,776 | How to replace the character 'a' with "aaa" in a string C++? | I have to replace all the 'a' characters with "aaa" in a string.
So, what I'm trying to do. If the input is water, the output has to be like this: waaater.
I tried this:
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
char s[100], t[100];
int i;
cout << "The string is: " << endl;
... | You are trying to modify s in-place, but after each replacement of 'a' with "aaa", you are not skipping the new as you just inserted, so you end up replacing them as well, ie water -> waaater -> waaaaater -> waaaaaaater, and so on in an endless loop until an error occurs.
Try this instead:
#include <iostream>
#include ... |
66,630,493 | 66,630,674 | boost serialization vector in c++ | Hello so i have this two classes and i want to serialize the vector
class PlayerInventory
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar &itemID &itemCount;
}
public:
int itemID;
int itemCou... | My strongest suspicion is that you might not fully flush the archive stream before reading.
Simple proof of concept, note the comment:
Live On Coliru
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <iostream>
#include <iomanip>
cl... |
66,630,954 | 66,631,320 | Why does clicking on edit box close win32 window(C++)? | The code below should create a simple window with a menu, static text, and an edit box but When I try to create an edit box it either does not run at all (with no errors) or when it does run and I try to click on the edit box the window closes. I am really stuck and any help would be greatly appreciated! Side note: I a... | When you use else if (FILE_MENU_EXIT), this result is always true. You can try:
case WM_COMMAND:
if (wp == 1)
{
MessageBeep(MB_OK);
}
else if (wp == FILE_MENU_EXIT)
{
DestroyWindow(hWnd);
}
break;
Also you can use:
case WM_COMMAND:
switch (wp)
{
case FILE_MENU_NE... |
66,631,781 | 66,631,872 | Ignore the "#" symbol when reading the file C++ | I have a file with the format below. I want to read the file in and print it out. But when I do read in and print, it will be some garbage. I think it is because the # symbol starts at the line. So, what is the right way to read in the whole file while ignoring the "#" line
int main(){
ifstream inFile;
inFile.o... | You can do this:
#include <iostream>
#include <fstream>
int main(){
std::ifstream inFile;
inFile.open("city_list.txt");
std::string line;
while(std::getline(inFile, line)) {
std::string cleanLine = "";
for (int i = 0; i < line.length(); i++) {
if(line[i] != '#') {
... |
66,632,048 | 66,632,215 | std::set as a class member can't use function pointer as key_comp | I want to define a class member std::set with function pointer as key_comp, but compiler report "is not a type".
bool compare(unsigned v1, unsigned v2)
{
...
}
std::set<unsigned, decltype(compare)*> GoodSet(compare);
class BadSet{
public:
...
std::set<unsigned, decltype<compare>*> Set2(compare);
};
int m... | You can't pass parameters to a member's constructor using parenthesis from inside the parent class declaration, like you are trying to do. You need to either
use the member initialization list of the parent class's constructor:
class BadSet{
public:
...
std::set<unsigned, decltype<compare>*> Set2;
BadSet... |
66,632,241 | 66,632,682 | difference in constructor usage in c++ | I tried to make a simple implementation of the stack using the class mechanism in c ++, when the program runs everything works as I expected, here is the code prototype
class Stack {
private:
int keep_track {10};
int * data {};
public:
// Stack () {
// data = new int [keep_track];
//}
Stack (): data ... | If you make a class like this:
class Stack {
private:
int keep_track {10};
int * data {new int[keep_track]};
public:
~ Stack () {delete[] data;}
// ...
};
Then you don't need a separate constructor because you have done member-wise initialization of each separate member. It's the same as having a cons... |
66,632,520 | 66,632,573 | Segmentation fault when Using std::initializer_list<std::string> in Constructor | Hi i am trying to understand how constructors work and so reading different examples. I have a class constructor that takes an initializer_list but it keeps giving Segmentation fault. The files that i have are as follows:
strvec.h
class StrVec {
public:
StrVec(): elements(nullptr), first_free(nullptr), cap(nullpt... | [Just guessing here since you don't show a proper minimal reproducible example.]
You have a set of pointers in your class.
Your StrVec(std::initializer_list<std::string> il) constructor does not initialize these pointers, so push_back will most likely use these uninitialized pointers and you will have undefined behavio... |
66,633,183 | 66,635,004 | Use std::all_of with boost::irange to get the loop index | I was wondering if it is possible to write an std::all_of statement with boost::irange at the same time to get the index of the item I am looping at each moment. My purpose is to refactor an expression of this kind, which looks like both of them combined:
for (auto instance : boost::irange(instances))
{
if (not fun... | If you are already using boost, you can use boost::all_of, that has an overload taking a range and a predicate, rather than two iterators and a predicate.
return boost::algorithm::all_of(boost::irange(instances), func);
|
66,633,979 | 66,634,136 | invalid conversion from 'void* (*)(int*)' to 'void* (*)(void*)' | I am trying to calculate the multiple thread C++ program to compute the sum of the cubes of the N first integer numbers.
Each thread should compute a partial sum to divide the work among them evenly.
Struggling with pthread_create arguments it's giving error.
#include <iostream>
#include <pthread.h>
#define n 6
#de... | There is thread support in standard library since c++11 standard, so you can use std::thread instead using pthread. It have no problems with different thread function signatures, but has good support for any variants of functions you need.
#include <iostream>
#include <thread>
#include <deque>
#include <algorithm>
#d... |
66,634,236 | 66,634,293 | confused in copy constructor and objects in C++ | I saw the others question on Stack Overflow but they only answered a part of it.
suppose we have a class-
class student
{
public:
string name;
student(string a)
{
name = a;
cout << "parmeteised const." << endl;
}
student(student &a)
{
name = a.name;
cout ... |
We have argument &a in the copy constructor but we input only a while making an object c.
In the function student(student &a) variable 'a' is reference on a student. It is not a pointer (student* a).
You will have to implement the comparison operator == if you want to compare two student objects:
operator_compariso... |
66,634,308 | 66,657,928 | QScrollBar singleStep is different from its actual step | When I Scroll a widget in QScrollArea, its scrollbar's step is not singleStep() but singleStep() * 3.
I set singleStep of QScrollArea's verticalScrollBar() to 30 in order to scroll 30 per scroll, but it scrolls 90 per scroll.
MyScrollArea::MyScrollArea(QWidget* parent) : QScrollArea(parent) {
this->verticalScrollBa... | As mentioned in the comments, your single step is being multiplied by the system's number of lines.
If you want to have the same scrolling step regarding less system's settings you always adjust the step accordingly. For example, for Windows:
#include <winuser.h>
#include <QScrollBar>
void setSingleStep(QScrollBar* ba... |
66,634,420 | 66,635,804 | CodeMR Analyzer in Eclipse does not work with C/C++ Code | I want to use CodeMR in Eclipse for analysing C/C++ code. I installed CodeMR via the marketplace. It works well for Java applications but when I go to "CodeMR" -> "Extract Model" I get to following error:
No suitable extractor found for selected files, extension list: [cpp,
h]
I installed the C/C++ Development Toolin... | The CodeMR component containing the extractor for C/C++ might not be installed since you installed it before you installed the C/C++ Development Tooling for Eclipse.
As a solution, reinstall CodeMR or uninstall+install CodeMR while C/C++ Development Tooling for Eclipse is installed.
|
66,634,945 | 66,635,054 | Can `printf()` have a macro parameter? | I am using the following printf function:
printf("%-8s%-21s%-17s%-6s\n", "index", "Name", "Effect", "Type");
However, instead of "8", I'd like to use a pre-defined macro:
#define NAME_SIZE 8
When I tried to replace it, the IDE doesn't recognise it and gives the error: Invalid conversion specifier N (the first let... | Yes you can indeed do this (although in your specific case you can pass the parameter width which is a better method). Indeed some of the standard libraries for C and C++ exploit this (or put another way, ratify this as a legitimate technique), for example with PRId64 for the correct formatting of int64_t:
#include <in... |
66,635,738 | 67,521,465 | Does that the current draft permit to form an overload set that consists of two non-static member declarations where one has ref-qualifier | The basic.scope#scope-3.3.1 says
both declare functions with the same parameter-type-list, equivalent ([temp.over.link]) trailing requires-clauses (if any, except as specified in [temp.friend]), and, if both are non-static members, the same cv-qualifiers (if any) and ref-qualifier (if both have one)
The above rule co... | This change was an inadvertent result of phrasing the rules more orthogonally, but since that orthogonality allows a few additional meaningful overload sets, there hasn’t been any hurry to “fix” it. In particular, it might work well with the proposal for deducing this that’s currently under consideration.
|
66,635,787 | 66,636,238 | Order of initialization with mixed inline and constructor initializations | [This question arised from this question]
Consider the following program:
#include <iostream>
struct Foo
{
const size_t size;
int* arr{ create_arr(size) };
Foo(size_t s)
: size{ set_size(s) }
{
}
static int* create_arr(size_t s)
{
std::cout << "Creating array with size " <... |
I know that initialization is done in declaration order, but does it
include inline initialization as well?
Yes, it must, see class.base.init :
13 In a non-delegating constructor, initialization proceeds in the
following order: (13.1) — First, and only for the constructor of the
most derived class (4.5), virtual bas... |
66,635,926 | 66,644,584 | removing duplicate vector from 2d vector | I have coded this to remove similar vector from 2d vector, this can be for any numbers of vector inside 2d vector but for example I have taken only 3 vector.
here, {1,2,3,4} is similar to {3,2,1,4} so I have to remove {3,2,1,4}.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()... | You can easily sort your 2d vector's elements and then compare them one by one.
Here, one function compares two 1d vectors and returns the result.
Note: When an element of your 2d vector gets deleted, the next element replaces it, so you shouldn't increase the target index (index k in my code). Increase the index only ... |
66,636,841 | 66,636,987 | Function overloading with template and constant pointer | I want a generic function which takes a template and some specialization via function overloading. However the wrong function is called when using the keyword constant or using a pointer.
What I want is:
#include <Eigen/Dense>
#include <iostream>
template <typename T>
void myFunction(const T variable){
std::cout <... | Because you're overloading the function, you're relying on the type of the variable passed to the function to invoke the right one. Your template function covers any type that isn't of the exact type const Eigen::MatrixXd*
So in your first example, you're calling myFunction with the argument &my_variables. Since my_var... |
66,637,095 | 66,637,096 | Why not specialize function templates? (Q&A) | I will try to organize this problem alas Q&A and hope that there will be colleagues who will take something from this.
First, lets answer at first glance a simple question, what is the output of this program?
#include <iostream>
template<class T>
void f(T) { std::cout << 1; }
template<>
void f<>(int*) { std::cout << ... | If your answer was 3, congratulations, you are free to skip this Q&A.
For everybody else:
I personally thought that the output should be 2, if you got to this point, I guess you too.
Now lets dive a bit deeper.
The name f is overloaded by the two function templates void f(T) and void f(T*). Note that overload resolutio... |
66,637,326 | 66,641,570 | Boost log 'text_file_backend' - rotate file on demand | I want to cover the cases when my process crashes or just does not shutdown properly and the logs are not rotated.
2 specific cases:
if I use a fixed name for my log file (e.g. keywords::file_name = "app.log") and the process did not manged to rotate the log on shutdown (let's say it crashed), then when it gets restar... | As Andrey Semashev mentioned, in order for rotate_file() to work, you first need to log something so the log file is actually opened.
Taking this into account I do the following during logger init (on app startup):
disable rotation on shutdown (keywords::enable_final_rotation = false) - this is so for the cases where ... |
66,637,498 | 66,638,149 | C++14. Declare a function with same-type-and-fixed-length argument list | Is there a possible way to implement sort of helper struct using C++14 which takes as a template argument a Number, return type Ret and input type T and would contain a member type std::function<Ret(T...)> where sizeof...(T) == Number?
| I suppose the following C++14 code can show you a way
#include <utility>
#include <functional>
#include <type_traits>
template <typename T, std::size_t>
using use_type = T;
template <typename...>
struct bar;
template <typename Ret, typename T, std::size_t ... Is>
struct bar<Ret, T, std::index_sequence<Is...>>
{ std... |
66,637,621 | 66,638,146 | How to redirect std::cout to file conditionally | In my code I have a a function that takes as argument a boolean variable. If this variable is true then the output shall be redirected to a file. If not, then to std::cout
The code looks like this and Its been inspired by a relevant question [1]
void MyClass::PPrint(bool ToFile)
{
std::streambuf *coutBuffe... | Don't redirect std::cout. Write your print in terms of a std::ostream & parameter, and choose an appropriate std::ostream to pass.
void MyClass::PPrintImpl(std::ostream & out)
{
out << "Will I be written to a file or to cout ?\n";
}
// a.k.a
std::ostream & operator <<(std::ostream & out, const MyClass &)
{
r... |
66,637,748 | 66,637,876 | compile a cpp file with multiple different header files | I have a single cpp file and multiple hpp files. For each hpp file, I want to create an executable using the same cpp file. The header files have different names. Can I do this in CMake?
So I have
source_1.cpp
header_1.hpp
header_2.hpp
...
and I want to create
executable_1
executable_2
...
| The C++ preprocessor can use macros for #include.
That is, you can have something like:
#include HEADER_FILE_TO_INCLUDE
Then when building the source file you could define the macro on the command-line:
g++ -DHEADER_FILE_TO_INCLUDE="\"header_1.hpp\"" source_1.cpp
To do this with CMake you first of all need multiple ... |
66,638,433 | 66,638,673 | C++ circular template dependency between Producer and Consumer in callback | I am designing two classes which encapsulate a producer and consumer. One class does single-thread processing, the other (not shown here) two threads.
The producer and consumer are passed to each 'threading class' by template parameters.
*this is passed to the producer to enable a callback upon each message:
template<c... | You can omit the template arguments:
template<class THREADING_CALLBACK>
class Producer
{
public:
Producer(THREADING_CALLBACK& cb) : _cb(cb){}
void receiveMessage(const char* message, int len)
{
_cb.processMessage(message, len);
}
THREADING_CALLBACK& _cb;
};
template<template <class> class... |
66,638,961 | 66,639,016 | what is the difference between initializing a string outside the for loop and inside the for loop? | I have two code's here there are the same, The only difference that I am using in the first code a string initialized inside the for loop, In the other hand I am using a string initialized outside the for loop but still getting to different answer's
string initialized inside the for loop :
#include <iostream>
#includ... | When you initialize the string inside the loop, the string is initialized in each iteration.
In other words, the string is set to "******" at the beginning of each iteration and then something is added to that.
On the other hand, when you initialize the string outside the loop, the string is initialized only once befor... |
66,639,047 | 66,639,098 | Palindrome number code not working for fringe cases | I've been doing some leetcode questions but I hitched at this one: Given an integer x, return true if x is palindrome integer.
It works for almost all cases, except for numbers like 12321 or 88888
Why doesn't it work
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0 || (x % 10 == 0 &&... | The line
z = z * p + x % 10;
is wrong. z should be shifted by one digit. The shift size shouldn't be changed in the loop. Using the line, the value will be x = 12, z = 1203 after the loop for the input 12321. You see the extra 0 is inserted. It is because you used the wrong shift size.
The line should ... |
66,639,120 | 66,639,211 | From two dice (6 sided). How can I find the numbers that give the sum of 9 in C++? (e.g die1 + die2 = 9) | It loops 1-6 and assign two values, num1 and num2.there's something wrong with logical operation/if statement that it's not working in first place for some reason. Any help? (I edited my question)
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
for (int i = 1; i <= 6; ++i){
int ... | Haven't tested it, but I would try:
for (loop in your first dice){
for (loop in your second dice){
add the 2 numbers together;
if (the sum is equal to 9) {
cout << sum;
}
}
}
The double for loop should check every number with all the numbers of the second dice and check if t... |
66,639,194 | 66,640,505 | CMake cannot find the header files of a git submodule | I have two git repositories with CMake, one is a game engine, and the other is a game that I am making with the game engine.
It turns out, this game engine has a submodule that is included in the project's CMakeLists.txt, and in the game repository, the game engine is added as a submodule that is also included in CMake... | If you use directory based property like include_directory or link_directory, you'll have to repeat requirements:
include_directories(
"${PROJECT_SOURCE_DIR}/include"
"${PROJECT_SOURCE_DIR}/src"
"${PROJECT_SOURCE_DIR}/libs/enel/include"
"${PROJECT_SOURCE_DIR}/libs/enel/src"
# Repeat all requirements... |
66,639,664 | 66,639,808 | 2D array of chars to 1D array of strings | what is the easiest way to copy a two-dimensional array of chars into a one-dimensional array of strings in c++?
something like that:
char inCharArray[3][255];
string outStringArray[3];
for (int i = 0; i < sizeof(inCharArray) / sizeof(inCharArray[i]); i++)
{
outStringArray[i] = inCharArray[i];
... | Using STL algorithm is one of the best way to do it.
char inCharArray[3][255];
string outStringArray[3];
std::transform(
std::begin(inCharrArray),
std::end(inCharArray),
std::begin(outStringArray),
[](char const* c_str) -> std::string {
return std::string{c_str};
}
);
This is assuming the ... |
66,640,271 | 66,640,907 | C++, Array adds data instead of a pointer to data | I am working on a DLL project in C++ for a Delphi executable.
This executable has a structure like :
size
data[]
for example :
02 00 00 00 // Size
30 31 32 33 // data[0]
34 35 36 37 // Still data[0]
31 32 33 33 // data[1]
33 33 33 33 // Still data[1]
I tried by doing a class like :
class LittleList
{
private:
int... | You're literally interpreting data, so there is a valid point to use a reinterpret_cast here. Don't be too afraid of Undefined Behavior - using Delphi is Undefined Behavior per se.
The easiest way seems to be a
private:
DataType& at(size_t i) {
assert(i<size);
return reinterpret_cast<DataType*>(&size+1)[i];
}
whi... |
66,640,289 | 66,714,720 | definite integration with monte Carlo does not have the acceptable error | I wish to calculate the integration of e^(- landa x) cosx from zero to positive infinity. The exact solution is landa/((landa^2)+1). The example I'm trying to solve forces me to have a maximum error of 0.01.
Here, the approach I am taking is that I first generate a random number from uniform distribution function [0,1]... | What @Damien wrote is good wrt the fact that you have to remove exponent part from function, you already using it for sampling.
Where he is wrong, is the fact that you have to remove whole NORMALIZED exponential PDF
PDF(x|λ) = λ*exp(-λ x),
which means that integrated function shall pick up λ in the denominator. In othe... |
66,640,481 | 66,640,600 | Why does assigning an integer to a string result in blanks? | I was trying to write Fizz Buzz and I came across an unexpected interaction. If I do std::cout << i, it automatically converts i (int) into a string and prints it? But if assign i to a string variable, it prints a blank instead? I managed to solve it by using std::to_string, but I was just wondering why printing to_pri... | There is no string::operator=(int), but there is string::operator=(char), which is selected as the best viable candidate.
So you're assigning single characters with codes 1..10 to the string, which apparently get printed by your terminal as blanks.
Try assigning 65, it should print A.
|
66,640,963 | 66,641,033 | Why is worst case of is_permutation O(n^2)? | The C++ docs say that the worst case time complexity for is_permutation is O(N^2):
At most O(N^2) applications of the predicate, or exactly N if the sequences are already equal, where N=std::distance(first1, last1). However if ForwardIt1 and ForwardIt2 meet the requirements of LegacyRandomAccessIterator and std::dist... | is_permutation doesn't require the ranges to be sortable. It only uses the bool-valued comparison predicate.
Furthermore, the ranges are immutable, so even if they could be sorted, the sorting would imply creation of an index on one of the ranges. That would add O(N) memory cost to the O(NlogN) cost of index generation... |
66,641,095 | 66,641,350 | Operator overloading with multiple arguments | I am self-learning C++. Following the example of operator + at this link. Suppose I want to modify the operator + a little: instead of adding box1 and box2, I want to input a scaling factor z to the overloaded operator +, so that the intended operator is box1 + z*box2, where z is multiplied by box2.length, box2.height ... | If you want to add two boxes, your operator+() should only add two boxes.
The expression you want to use involves two operations, addition and multiplication. So you need to implement a multiplication operator overload. After that, you just let the order of operations take over. Because you want one operand to be a dou... |
66,641,245 | 66,641,656 | calling perfectly forwarded lambda | I have the following class which stores a perfectly forwarded reference to a function:
template <class F>
class Visitor
{
public:
Visitor(F &&f) : _f(std::forward<F>(f))
{
}
xt::LOOP_CONTROL OnElem(xvi::Elem &elem)
{
return _f(elem);
// or should it be:
// return std::fo... | Lambda cannot have ref qualified operator () currently, so for them, both forms are equivalent.
For custom functor, it might differ with std::forward<F>(_f)(elem);:
struct MyFunctor
{
xt::LOOP_CONTROL operator()(xvi::Elem &elem) & { std::cout << "lvalue"; return {};}
xt::LOOP_CONTROL operator()(xvi::Elem &elem... |
66,641,415 | 66,641,513 | How the Node* type value is returning in Iterator type? | I created a linked list class having a head pointer of type Node.
In the method begin(), I want to return an Iterator type object.
But if I return a pointer of type Node* in the begin() method instead, it is able to compile and run properly. Why???
class LinkedList {
class Node;
Node* head;
public:
class... | It implicitly converts Node* to Iterator via the Iterator(pointer_t ptr) constructor.
|
66,641,554 | 66,641,759 | C++ library in Visual Studio Code | I have made a c++ project in CodeBlocks. Now I started using Visual Studio Code and I can't figure out how to connect files. I have main.cpp with my main code, then I have sortlib.cpp with some sorting functions and I have sortlib.h. My question is how do I connect these files, so I can #include "sortlib.h" in my main.... | Minimal code structure
main.cpp
// Other header files
#include "sortlib.h"
int main(void) {
...
}
sortlib.h
void someFunction();
...
sortlib.cpp
// Include headers that are required
void someFunction() {
...
}
The minimal required command
g++ -g main.cpp sortlib.cpp
|
66,642,198 | 66,645,368 | C++: Generic if statement supporting std::complex<double> AND double | We want to enable complex step differentiation in our C++ code. To this end, we introduce a generic template parameter template<typename number>, where number should be default set to double or if requested to std::complex<double>. In certain functions, we also have if statements, which should be also callable with com... |
Is there a smarter way than the one below [...] Smarter in the sense (i) I do not want to extract the std::real part of a double value (which could be achieved by distinguishing between the typename in make_real (ii) I though it might be possible to overload the comparison operators to use them also for double vs. st... |
66,642,716 | 66,642,992 | Coroutine debugging in c++ | I am trying to test out the coroutine feature of c++20 I have included the necessary flags, but when I #include <coroutine> I get the following error:
cannot open source file "coroutine". I'm sure it's a stupid error!
Code:
// lazyGenerator.cpp
#include <iostream>
#include <vector>
#include <coroutine> // <---- the i... | At the time of writing, the current release of Clang does not fully implement the coroutines as described here.
However, the last release support a old coroutine TS that has been superseded since C++20. If you want just to play with coroutines temporary, you can enable it by using the compilation flags -std=c++20 -stdl... |
66,642,965 | 66,643,026 | Can I call destructor for a class member, which is an object using dynamic memory? | If I have the following classes:
class Small {
public:
Small();
Small(const Small &small);
~Small();
private:
int *arr;
};
and
class Big {
public:
Big();
Big(const Big &big);
~Big();
private:
char *name;
Small smallObject;
};
When I call ~Big() I delete the dynamic memory, allocate... | Whenever the destructor for a composite object such as Big completes, it automatically calls the destructors for all member and base objects, so you don't want to call such destrutors explicitly. If you did, the object destructor would be called twice, which would cause problems.
So in this case, the Big destructor wi... |
66,643,696 | 66,643,884 | Can we initialize a pointer with a variable qualified as constant and having value 0 in C++? | According to the book C++ Primer, we can assign a variable qualified as const and having value 0 to a pointer. Here's the relevant line from the book.
It is okay to assign the literal 0 or a const whose value is known to be 0 at compile time:
and then the following code snippet is provided.
int ival;
int zero = 0;
co... | Depending on your version of the C++ Primer (and indirectly the standard revision it's targeting), this may just be a case of outdated information.
You see, there was a change of definition between C++03 and C++11. In the past, it said:
[conv.ptr]
1 A null pointer constant is an integral constant expression (5.19)
rva... |
66,643,815 | 66,679,510 | c_str() is terminating my encrypted message is there a way to bypass this? | I am encrypting a message using RSA.
Everything works fine if I try to encrypt/decrypt the message locally, however, when converting the string to void constant* in order to use the socket::send method like so,
int sendRes = send(socket, tempMessage.c_str(), tempMessage.size() + 1, 0);
the following happens,
My origin... | In the end, it was an easier fix.
Since all messages are encrypted following the same type, the length of the bits will always be the same for the encrypted part.
In my case, this was 256, meaning that I can now send-receive without any further issues since I now know the real string length.
If this would not have been... |
66,645,179 | 66,646,023 | Data byte offset of elements of a vector inside a struct | If I have a struct with members int a, b, c;, I can get the byte offset of each member using offsetof(structName, member).
Now, if I have a struct with a vector<int> { a, b, c }, I can get the offset of the vector using offsetof(structName, vectorName).
Knowing this, is this operation:
offsetof(structName, vectorName) ... | First off, b is the vector's 2nd element, but sizeof(int)*2 would return the offset of the 3rd element instead.
But more importantly, the vector's element array is not stored inside the vector class itself, so using offsets relative to the vector itself will not work. The actual array is stored elsewhere in memory, an... |
66,645,286 | 66,647,554 | CMake multiple errors when include boost/beast/http.hpp | I'm trying to build my project that uses boost beast library with cmake.
When I use only boost asio library everything builds okay. But when I add boost/beast/http.hpp header when cmake gives a huge amount of errors.
CMake file:
cmake_minimum_required(VERSION 3.10)
project(ConsoleChat.Server)
set(Boost_USE_STATIC_LI... | Yup. The preprocessed source confirms that the first mention of is_const_buffer_sequence is from line 116485 (eek), which is attributed to
# 49 "/usr/local/include/boost/beast/core/detail/buffer_traits.hpp" 3
from line 116467. On my system, that's not the first mention, because (obviously?) the declaration in boost_1... |
66,645,466 | 66,652,037 | Override virtual method from abstract class | I need to test notifying system based on observer pattern. Here is my Observer class:
template <typename DataType>
class Subject;
template <typename DataType>
class Observer {
public:
virtual ~Observer() {}
virtual void receive(Subject<DataType> *subject) = 0;
};
DataType is tparam data. receive() will receiv... | I missed public word, right code:
template <typename DataType>
class TestObserver : public Observer<IdString> {
public:
virtual void receive(Subject<DataType> *subject) override {};
};
After that it compiles
|
66,645,570 | 66,648,371 | Representation of a simple undirected graph | I need your expertise:
I am about to implement a graph class in c++ and thinking about the right representation. The graphs are simple and undirected. Number of vertices get for now just up to 1000 but maybe higher in the future. Number of edges up to 200k and maybe higher. Each vertex got a color (int) and an id (int)... | A 1000x1000 matrix with 200,000 edges will be quite sparse. Since the graph is undirected, the edges in the matrix will be written twice:
VerticeA -> VerticeB and VerticeB -> VerticeA
You will end up filling up 40% of the matrix, the rest will be empty.
Edges
The best approach I can think of here is to use a 2D v... |
66,645,630 | 66,645,829 | Unsigned integer wrapping, different behaviour | Here is a code in C:
#include <stdio.h>
int main()
{
printf("Int width = %lu\n", sizeof(unsigned int)); // Gives 32 bits on my computer
unsigned int n = 32;
unsigned int y = ((unsigned int)1 << n) - 1; // This is line 8
printf("%u\n", y);
unsigned int x = ((unsigned int)1 << 32) - 1; // This... |
There is no warning for the line 8, but I was expected the same warning as for line 11.
The C standard does not require a compiler to diagnose an excessive shift amount. (Generally, it does not require C implementations to diagnose errors other than those explicitly listed in “Constraints” clauses.)
The compiler you ... |
66,645,667 | 66,645,897 | Visual Studio: Resolving build Flags/Settings for a project dependency | I'm trying to compile a C/C++ library, originally developed for *nix systems, on windows Visual Studio 2019 and it's hitting a snag in a dependency; boost in this case. The error reported is as follows :
Error C2039 '_snprintf': is not a member of 'std'
I believe the egregious lines are the following :
#if ( defined(_... | _MSVC_VER is defined by the compiler itself and will always be present when using MSVC (I believe it will also be present when using the clang distributed through VS but I'm not as certain of that). BOOST_VER will be present after (and in the middle of) boost headers. BOOST_VER is defined early in the boost header casc... |
66,646,327 | 66,651,636 | How to get a MeshHandle from a mesh instance in OpenMesh? | I am trying to use this function to compute the center of mass of a mesh structure. This is the signature:
Point calc_centroid (MeshHandle _mh) const
So it takes a MeshHandle object as a parameter. My question is, how to get such a MeshHandle from a mesh instance? I have a mesh instance defined as
typedef OpenMesh::... | A MeshHandle holds no reference to a mesh instance. You can just create one with a default constructor:
MyMesh mesh;
mesh.calc_centroid(OpenMesh::MeshHandle());
|
66,646,806 | 66,646,874 | How to have a template argument with arbitraty type? | I need to wrap various free functions with a common logic, but I don't want to write the wrapping code multiple times. The wrapped functions need to be "plain" free-functions (because I want to export them again for external use), hence I need to use a template. This is how far I've got:
#include <mutex>
std::mutex mu... | C++17 introduced auto non-type template parameters for exactly this use case:
template<auto Func, typename... Args>
auto forward(Args&&... args)
{
auto lock = std::unique_lock<std::mutex>{mutex};
return Func(std::forward<Args>(args)...);
}
void func1(int i)
{
//...
}
int main()
{
forward<&func1>(42);
... |
66,646,891 | 66,647,041 | How to Read Audio Files in C++ | So I basically want to write a program in C++ that takes in a .wav file (or any other uncompressed format for that matter) and returns sheet music. No problem with calculations provided that I learn how to actually get access to the time-pressure map. Is there any way to implement this without any fancy libraries? I ju... | Here is a library that isn't fancy. It is called "ffmpeg". Here is a c++ wrapper: https://github.com/Raveler/ffmpeg-cpp . You can leverage this powerful library to implement the solution.
|
66,646,992 | 66,658,393 | Boost python passing named parameter to member class | I have the following struct:
struct StuffMaker {
static std::string makeStuff(po::dict options = {})
{
//makes some stuff
}
};
I want to expose it in my python module to do some stuff:
BOOST_PYTHON_MODULE(stuffMakers)
{
po::class_<StuffMaker>("StuffMaker")
.def("create", &StuffMaker::makeStuff, (ar... | In order to pass the self parameter through you have at least 2 working choices of signature:
struct StuffMaker {
static std::string makeStuff(StuffMaker self, po::dict options = {})
{
//makes some stuff
}
//alternatively
static std::string makeStuff(StuffMaker* self, po::dict options = {})
{
//... |
66,647,123 | 66,647,142 | For loop only executing once? | I don't know if I'm just being stupid, but Visual Studio says that my for loop is only executing once, and it does seem to be the case. However I can't figure out why. I'd really appreciate it if anyone could tell me what I'm doing wrong.
for (int i = (nbToVerify - 1); i == 1; i--)
{
if (nbToVerify % i == 0... | i == 1 should be i != 1, that's it.
|
66,647,207 | 66,647,229 | Why does replacing an argument with its value cause an error? | I'm fairly new to C++, and I wanted to test what I know about it by implementing a mediocre List class.
List.hpp:
#ifndef LIST_HPP
#define LIST_HPP
// Only supports int lists up to 100 items for now.
class List
{
public:
List(int arr[], int length);
void append(int item);
void print();
... | In List mylist({1, 2, 3}, 3);, {1, 2, 3} isn't an array, its a std::initializer_list.
|
66,648,598 | 66,648,763 | Is it okay to assign values to map.end()? | I'm wondering whether it's a bad practice to assign values 1 past the last element in a map like the example below.
using namespace std;
auto chances = map<int, int>{};
chances[0] = 20;
chances[1] = 10;
chances[2] = 30;
int last = 0;
for (auto it = chances.begin(); it != chances.end();) {
last = it->second;
(+... | Yes, it's bad practice to assign to the end() iterator of any container (not just map)
In all standard C++ containers, the end() iterator is not dereferencable. Any attempts to dereference (in this case, assign) to the end() iterator is undefined behavior.
In your example code, a dereference of this end() iterator occu... |
66,649,184 | 66,773,708 | Boost python producer consumer problem (execute boost python thread, std::mutex deadlock) | I'm trying to create boost python module and test producer & consumer problem.
But I faced some error and problems...
Below image shows my goal architecture.
I implemented boost python module
and here is python code snippet (main.py)
import threading
import datetime
import PyDataTest
queue = None
def thread_functi... | Ok. I found how to solve that problems..
I found the way using scoped gil release. this question very helpful for me
When I run the thread, I face error windows above... it cause by I cannot join the thread in C++ module. I added thread join code inside run function the error goes away
I thought directly sharing a q... |
66,649,373 | 66,784,113 | Which is the best viable operator == function between these two declarations? | #include <iostream>
template<typename T>
struct A{};
struct Y{
template<typename T>
bool operator==(A<T>){
std::cout<<"#1\n";
return true;
}
};
template<typename T>
bool operator==(T,Y){
std::cout<<"#2\n";
return true;
}
int main(){
A<int> a;
Y y;
a==y;
}
For the above ... | Short answer: You used different Clang versions in your examples, Clang 11 has a correct implementation, while Clang 10 does not.
In my answer I go into detail why Clang 11 and MSVC are right and GCC is wrong in both cases.
From [over.match.oper]#3 the candidates include four sets:
For [...] a binary operator @ [...]... |
66,649,545 | 66,653,167 | Method outside template class with enable_if | I have the following code where I want a template class to check the template value as one of int64_t or unint64_t upon init. The class has a GetValue method that is implemented outside the class.
template <typename T, typename std::enable_if<std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t>>::type>
class Class... | Issue with
template <typename T,
typename std::enable_if<std::is_same_v<T, int64_t>
|| std::is_same_v<T, uint64_t>>::type>
class Class;
is that is result into
template <typename T_OK, void> class Class;
or
template <typename T_KO, /*Subsitution failure*/> class Class;
Which a... |
66,649,869 | 66,649,975 | C++: using directive statement in main function Vs global scope | Following code results in an error as it is not considering ::x in global scope.
#include<iostream>
namespace nspace
{
int x = 2;
}
int main()
{
using namespace nspace;
std::cout << ::x; //error: ‘::x’ has not been declared
return 0;
}
Following code results in output 2 without any compilation error.
#... | [namespace.qual]/1:
Qualified name lookup in a namespace N additionally searches every element of the inline namespace set of N ([namespace.def]). If nothing is found, the results of the lookup are the results of qualified name lookup in each namespace nominated by a using-directive that precedes the point of the look... |
66,650,129 | 66,650,219 | (C++) error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] | I'm trying to write a function that would return a substring from the given start and end indices. This is the code that I've written but when i run it it gives me error. I'm using gtest to run it not main().
template <typename S>
S substring(S string_, int Istart, int Iend)
{
S substr = string_[Istart];
for(in... | Assuming that the intended type is string. A += operator exists for the string type.
A simple fix is to replace
S substr = string_[Istart];
with
S substr;
substr += string_[Istart];
which will not work for const char* types as pointed out
The following works for both string and const char*.
#include <exception>
#incl... |
66,650,918 | 66,651,390 | Search for set/unset bit combination in value C++ | It's my first time working with C++ and I'm tryin to identify if the bits of a given int fall into a specific category:
For each int passed to the function, we implement the rule that every 2 bits represent a singular value within the message, and if that message's value is 2 (10 binary) then we need to return a boolea... | unsigned int condition=((value&0xaaaaaaaa)>>1)&((~value)&0x55555555);
This computes a number which has a bit set for each message that is 2. If for example value=0b11011001, value&0xaaaaaaaa is 0b10001000, shifting right produces 0b01000100 ~value is 0b11111111111111111111111100100110, anding with 0x55555555 produces ... |
66,651,061 | 66,651,151 | What is "OpType" in C/C++ programing | In the program, there are many OpType opType as a input for functions, but there is no definition/declaration for OpType opType. Therefore, the program encountered the error:‘OpType’ has not been declared.
In addition, there is a switch-case as below, that get error: was not declared in this scope, too:
switch (opType)... | There is no such thing as "OpType" neither in C nor in the C++ language. It is a name that can be declared by the program. If such name is declared by the program, then its meaning depends on that declaration. If such name isn't declared, then the name cannot be used.
If you attempt to use an undeclared identifier, you... |
66,651,215 | 66,651,980 | Does std::any_cast call destructor? How the cast works? | #include <iostream>
#include <any>
using namespace std;
class c {
public:
c() :a{ 0 } { cout << "constructor\n"; }
c(int aa) :a{ aa } { cout << "Constructor\n"; }
~c() { cout << "destructor\n"; }
int get() { return a; }
private:
int a;
};
auto main()->int
{
any a{ 5 };
cout << any_cast<in... | You are copying a c (or X) from the one within the std::any. That copy is destroyed at the end of the expression, after having been streamed out.
any_cast does not do any conversion. It throws if you ask it for a type different to the one it stores. When you have emplaced a c and asked for an X, it throws std::bad_any_... |
66,651,672 | 66,651,974 | different size of array in a struct c++ using a Template | I have a typedef struct that contains an array with a different size, depends while running the app.
The app should read the size then it creates a struct with its specifics size of the array.
Here is the struct that I want to use it.
template <int N>
typedef struct Frame{
float time;
float zone_values[N];
}Fra... | Your struct has a non-type template (see https://en.cppreference.com/w/cpp/language/template_parameters)
which cannot be determined at runtime, you should instead use the answer provided by Sparkofska. If you still want to use a compile time version, you can do it like this with C++17
#include <array>
#include <cstddef... |
66,652,015 | 66,652,214 | C++ class destructor not being called automatically causes memory leak? | (Before anyone asks: no, i didn't forget the delete[] statement)
I was fiddling around with dinamically allocated memory and i run into this issue. I think the best way to explain it is to show you these two pieces of code I wrote. They are very similar, but in one of them my class destructor doesn't get called.
// mem... | This is constructing a temporary object and then assigning it. Since you didn't write an assignment operator, you get a default one. The default one just copies the vector list.
In the first code you have:
Create a temporary Leak object. It has no pointers in its vector.
Assign the temporary object to the leak object.... |
66,652,076 | 66,652,114 | Does unique_ptr swap copy contents? | I have a class C with multiple member variables and I'm programmig a binary heap whose elements are of the type std::unique_ptr. For the reordering of elements in the heap, I'm currently calling std::swap(x,y) where x and y are references to unique_ptr.
I'm a bit confused with the explanation of this function on cplusp... | std::swap(x, y) swaps the contents of variables x and y.
If x and y are unique_ptrs then it swaps the contents of the unique_ptr variables. A unique_ptr variable holds a pointer, not a whole object. Since the pointers were swapped, now y points to the address that x used to point to and x points to the address that y u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.