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
63,621,156
63,621,298
From std::string<char> to unsigned char[], an error "non-constant-expression cannot be narrowed"
There is an error message: non-constant-expression cannot be narrowed from type 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >::value_type' (aka 'char') to 'unsigned char' in initializer list [-Wc++11-narrowing]. The problem is treated by MSVC and GCC as warnings but Clang treats it as an error...
As std::string is basic_string<char> you are assigning a signed type char to unsigned char hence the narrowing. Freely speaking a narrowing conversion is an implicit conversion, where the converted type cannot be represented in all cases by the target type, which is the case, converting signed to unsigned. As the stan...
63,621,355
63,621,419
Compute Power(x,y) code clarification C++
int Power(double x, double y) { long long power = y; double result = 1.0; if (y<0) { power = -power; x = 1 / x; } while (power) { if (power & 1) { result *= x; } x *= x; power >>= 1; } std::cout << result; return result; } I am...
When the power is negative where is it multiplying 1/(x*y)? Nowhere. When y is negative the code uses power = -power; x = 1 / x;. In the if statement inside the while loop it tests to see if power%2 == 0 but if it is not mod 2 then where is that calculation taking place? No it doesn't. The code does not check ...
63,621,549
63,621,651
*** Error in `': free(): invalid next size (fast): 0x0000000000667890 ***
This was a function that i made, it calculated Fibonacci Numbers, but when I run it i get the following error Error in `': free(): invalid next size (fast): 0x0000000000667890 int fib(int n) { int fibn=0; std::vector<int> x{0,1}; for(int i = 2 ; i <= n ; i++) { x[i]=x[i-2]+x[i-1]; } fibn=x[n]; return fibn; }
std::vector<int> x{0,1}; You have a vector with two elements. Valid indices are 0 and 1. for(int i = 2 ; i <= n ; i++) { x[i]=x[i-2]+x[i-1]; } After the first iteration, you access x[2] and beyond which is outside the bounds of the vector. The behaviour of the program is undefined. You don't need to store th...
63,622,089
63,622,277
What's the relation between libraries and namespaces?
Just started collage and I'm new in the world of programming. So, as I was learning C++ I bumped into a question that wouldn't let me be : "Why do i need to include "using namespace std" in my code to be able to write or read if i already got iostream?" , because I've been told that "cin/cout" are already defind in ios...
Libraries and namespaces are related by convention. By convention, the symbols that a library provides to the programmer-user are contained in a namespace. This organizes things, and there are some higher level language features (ADL) that mean code in a namespace behaves differently than code outside of it. When you ...
63,622,291
63,623,636
_WIN32_WINNT Not defined
I had a problem with using winternl.h, I was using some of the datatypes out of there and have sucessfully compiled it for x64 without any problems. However I made some changes and now for some reason its failing to compile, through debugging I've found that the reason seems to be down to _WIN32_WINNT not being defined...
_WIN32_WINNT comes from the include file <windows.h>, so in order to fix the error you are seeing: In the file throwing the error, change this: #include <winternl.h> // ... to this: #include <windows.h> #include <winternl.h> // ...
63,622,764
63,622,798
Process was terminated. It took longer than 12000ms to complete
Create a function that takes a sentence and turns every "i" into "wi" and "e" into "we", and add "owo" at the end. I was creating the function for the above question and received an error: Process was terminated. It took longer than 12000ms to complete Can anyone please help me with the fix? #include<string> std::...
Your code turns "e" into "we". But then it turns the "e" in "we" into "we", creating another "we" that also gets replaced. One simple fix is to increment i an extra time after the replacement.
63,623,056
63,623,252
Calling functions from separate C++ files in main.cpp trouble
I have been searching online for solutions to this rather simple problem. My goal is to call a function from a separate .cpp file in my main.cpp file. What I have found thus far has told me to define my function in a separate .cpp file (averageScore.cpp) which looks like: void averageScore() { "Blah, Blah, Blah" } ...
To achieve what you want, you must create a header file, and declare your function there, for example: lesson1.h void averageScore(); In a .cpp file, you define that function and include the header you just created: lesson1.cpp #include "lesson1.h" void averageScore(){ // Do what you want in this function } Then...
63,623,766
63,626,282
Detect specific tag match in Catch2 at runtime
I have integration tests in my Catch2 project that depend on some expensive global state being set up. I'd like to only initialize that global state when the test runner will actually be testing the systems that depend on it. What I have appears to work, but it's a little horrifying... it depends on rather a lot of imp...
Just do the initialization on demand, using something like std::call_once: TEST_CASE("expensive-to-initialize system", "[.integration]") { static std::once_flag init_flag; std::call_once(init_flag, do_expensive_setup); // ... } This will ensure that do_expensive_setup is called one time, but only if n...
63,624,014
65,147,753
Why does clang, using libstdc++, delete the explicitly defaulted constructor on a type containing std::optional?
Consider the following structure with an std::optional containing a type that definitely has a "normal" default constructor. #include <optional> #include <string> struct Foo { Foo() = default; const std::optional<std::string> m_value; }; bool function() { Foo foo; return bool(foo.m_value); } Compilin...
This is a combination of: an underspecification in the Standard; a suboptimal Library implementation; and a compiler bug. Firstly, the Standard does not specify whether for the default optional.ctor a permissible implementation would be to defined it as defaulted: constexpr optional() noexcept = default; ...
63,624,300
63,624,922
Invoking method inside of an unknown struct in c++
Lets say a user creates their own struct that contains some code: struct NormalShader { vec3 normal; vec3 color; void main() { color = normal * 127.5f + 127.f; } }; Then the main piece of code runs and tries to simulate this struct: void ShaderRun() { void* structData = alloca(structSi...
Make Invokemain() take a template parameter that the caller can use to specify the structure type being passed in, eg: template <typename T> void Invokemain(T &data) { data.main(); } Then the caller can allocate whatever struct it needs to, eg: struct NormalShader { vec3 normal; vec3 color; void main(...
63,624,458
63,624,659
OpenCV - merge function Exception at memory location
I am trying to merge single-channel images into one multiple-channel image. But it shows an error at the merge function: cv::Exception at memory location code: #include <vector> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main() { Mat input = imread("a jpeg image"); Mat B, G, ...
You declare a couple of vectors of 3 elements (size) each, but do not initialize their values: vector<Mat> channels(3), channels2(3); What's the initial value of these first 3 elements? After this, you push_back another 3 elements into the same vector: channels2.push_back(B); channels2.push_back(G); channels2.push_bac...
63,625,272
63,627,516
How to use Glad in DLL and exe
Is there any way to use Glad within a DLL and exe? I feel like there may be problems since DLL's have their own memory space that is separate from the exe, but I'm not sure how I would go about refactoring my code to represent this. My situation is that I have a game engine which contains numerous methods that use Ope...
It's important to remember the distinction between a pointer variable and what it points to. If you have one instance of GLAD in a DLL and another in an EXE, then for each GLAD function pointer, you will have two pointer variables. However, they will both point to the same function. They are after all loading function ...
63,625,405
63,625,848
Assignment grammar conflicting with λ-calculus application grammar
I am implementing an extended λ-calculus interpreter using ANTLR4 and it's C++ target. Here is the language grammar: grammar lambda; program: expression|; expression: (Int | Bool) # literal | Identifier # variable | expression expression ...
If you want newlines to be significant, then let them pass through the lexical scanner. WS: [ \t\r]+ -> skip; NL: [\n]; Then you could define a program as a sequence of expressions terminated with newline characters: program: ( expression NL )*; If you want semicolons to work as well, just change the definition of NL...
63,625,418
63,625,428
C++, how do I printf a substr?
I'm just trying to print out a substring via printf, but keep getting an error #include <iostream> #include <string> #include <cstdio> int main(int argc, char *argv[]) { std::string argv1 = argv[1]; if (argc == 2 && argv1.length() > 3) { printf("%s\n", argv1.substr(0, 2)); } } The error is showing: warnin...
printf with %s expects a char *, but string::substr returns another std::string. You can get the underlying char* from the string via the c_str() method. printf("%s\n", argv1.substr(0, 2).c_str());
63,625,570
63,625,605
How to change the ouput from 1 to Monday?
I am using code from here: https://www.geeksforgeeks.org/find-day-of-the-week-for-a-given-date/. It finds the day of the week a date falls on. The output is a number corresponding to the day of the week but I would like it to say 'Monday' instead of '1'. How do I change it? #include <iostream> using namespace std; in...
Write a method that takes an integer input and returns a string. const char* day(int n) { static const char* days[] = { "Monday", "Tuesday", …, "Sunday" } if (n >= 1 && n <= 7) return days[n-1]; else return "Failday"; } I assume here Sunday is 7; adjust accordingly if it's 0. Y...
63,625,574
63,639,847
Can't get the protobuf example code link step in C++
I am trying to compile the example code offered in the github source for the protobuf (adds address and then sends it in a serialized manner to another program that deserializes it and displays it). The protobuf source code was compiled and installed successfully. (version 3.13.0). The challenge started when I tried co...
Libraries are missing, because you have only specified libdirs. Have you actually linked required libraries? Because specifying libdirs (-L for gcc) is only a convenience so you can use -lmylibname and not specify full path (check bottom of this article to see the difference). So, in terms of g++ instructions, assuming...
63,626,095
63,626,182
How do I inline a pointer in CPP?
Hey I'm new to c++ coming from java and I can't understand how to make this: std::string some_string = "some text"; string* some_pointer = &some_string; all in one line. Example of what I am thinking of: void some_function(string* some_pointer); some_function(get_pointer_of("test"));
This can be done but it would be a bad practice. You must handle the pointer inside the function or return the address again to handle it later. An example #include <string> #include <iostream> std::string* fun(std::string * str){ std::cout << *str; *str = "ff"; return str; } int main(){ auto ptr = fun(...
63,626,238
63,626,869
What is the logic of this C++ Loop that converts Decimal to Binary
I am searching for codes that converts decimal to binary and i stumbled upon this: #include <iostream> using namespace std; int main() { int num; cout << "Please enter a number: "; cin >> num; if (num > 0) { int i = 1; while (i <= num) i *= 2; i /= 2; do { i...
When working to understand any algorithm, you step through it with pencil-and-paper validating each step of the code. Pick a small test case, such as 10 as your input, which you know has a binary representation of 1010 and step through the four-iterations understanding what is happening. If you do so, you will find the...
63,626,718
63,626,990
Abstract Class in std::unique_ptr as a Return from Function not Working
class Base{ public: virtual std::string typeName() = 0; virtual ~Base() = 0; }; Base::~Base(){} class D1 : public Base{ public: std::string typeName(); std::vector<std::unique_ptr<Base>> children; ~D1(){}; }; class D2 : public Base{ public: std::string typeName(); std::unique_ptr<Base> chil...
The underlying issue is explored in Abstract class and unique pointer, but solutions details are different. A call to std::make_unique<T> dynamically allocates an object of type T. The parameters do not affect what is created, only how it is initialized. When you provide an object of type D1 to initialize a dynamically...
63,627,021
63,627,070
Why operator<< does not implicitly converting my custome class object to string
I have a class implemented a public string conversion memeber function. When coupled with operator<<(iostream &, xxx) , what I expect is that my class would be automatically(implicitly) converted to string thus suits for the parameter type. However, that's not true. Why, I don't wanna to write a operation<< function. #...
The operator<< for std::string is a template, and implicit conversion won't be considered in template argument deduction, which fails. Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later. As you've showed, you ca...
63,627,049
63,627,121
class B inside class A inherits class A
I tried the following and failed to compile. class A { //...members class B : public A { //<---failed here using A::A; } } Is this possible(specially in c++17)? Do this just have wrong syntax? If not possible, why this does not work?
This can be done, but the definition of B needs to be moved outside of A. Until the closing brace, A is an incomplete type, whereas the base class must be complete. This would work: class A { class B; }; class A::B : public A { using A::A; };
63,627,111
63,627,234
Using g++ and ./a.out
Hello everyone I have finally decided to learn to code, even if it is just a hobby, I once picked it up years ago and I am gong through the tutorials on codeacademy, I have a question for everyone. Tonight I downloaded Codeblocks with Ming compiler, the programs work fine, the ones I have tried to rewrite from memory f...
I first commented, then I decided to make it a full answer, since I kind of answered the heart of the question in the comments by accident anyway. Yes, you can absolutely do this yourself. Using an IDE (Integrated Development Environment) like Codeblocks will make things easier for you, but there is no harm in learning...
63,627,118
63,627,252
Return the address of the argument which passed by value in C
void* func1(int a) { void *b = &a; return b; } int main(int argc, char** argv) { int d = 9; void *c = func1(d); printf("%d\n", *((int*)c)); return 0; } I am confused about why it works. From my understanding, memory of "a" will release after func1. Why the void* c can still access "a...
I am confused about why it works. The behaviour of the program is undefined. The program doesn't "work" - In my opinion. Although "workingness" may be subjective. From my understanding, memory of "a" will release after func1. Correct. Why the void* c can still access "a" after finish the function? Behaviour of th...
63,627,144
63,627,230
is not a class or a namespace name - except it is
I've got the two classes below, and the "BitmapIterator" class is refusing to recognize that the "Bitmap" class exists, and I can't figure out why... I've declared the Bitmap class prior to creating the handle, HBitmap class, and HBitmap is recognized by other classes I'm using. I've included the header files. I can't ...
Bitmap.h includes BitmapIterator.h which includes Bitmap.h before it gets to code, which is skipped due to pragma once, then proceeds to use Bitmap before it is defined. Or the other way around. Header files shouldn't be including each other. Clean up your dependencies. Try dropping include of iterator from bitmap and ...
63,627,226
63,627,353
Proper way to return stl container
A lot of times, we need to return a container constructed inside a function. Say I have a function to get all primes in some range. std::vector<int> getPrimes() { std::vector<int> primes; ... reutrn primes; } This seems need to copy all primes to the returned object. Then pointers are needed. // ==========...
If you're using a modern compiler, just use your original code; NRVO (Named Return Value Optimization), a form of copy elision, is performed by most modern compilers in the simple case you're demonstrating. If for some reason you can't rely on this, and profiling shows this is a big problem on this crappy compiler you'...
63,627,238
63,627,285
How to dynamic_cast and test for success for a reference
I'm trying to downcast from VPN to OpenVPN (which obviously inherits from VPN) like this: void to_json(json &j, const VPN &p) { if (auto& pp = dynamic_cast<const OpenVPN&>(p)) { to_json(j, pp); } else { //throw ...
You may write simply: void to_json(json &j, const VPN &p) { to_json(j, dynamic_cast<const OpenVPN&>(p)); } If the dynamic_cast succeeds, then to_json is called. If the dynamic_cast fails, a std::bad_cast exception is automatically thrown by the runtime. Since you don't seem intent on reacting to the exception in t...
63,627,279
63,628,177
Visual Studio disable warnings for files in specific directories
We have a VS 2019 project which includes external source libraries which we add to our project. For instance we are using WTL (Windows Template Library). During compile time, these libraries produce huge numbers of warnings (particularly for members which do not have default values). For those files, we would like to c...
There are several ways to disable the warning: Project Properties->C/C++->General->Warning Level->select level Here is the Warning Level: Turn off all warnings (/W0): Turn off the display of all warning messages. Level 1 (/W1): Display serious warning messages. Level 2 (/W2): Display level 1 warnings and some less s...
63,627,409
63,669,454
How to get pointer to const pointer to const int from int reference in one line?
Is there any way I could write the two lines (7 and 8) of code into one line? I think I understand why the error occurs. int value = 5; int &GetValue() { return value; } int main() { const int *my_value = (const int *)&(GetValue()); // 7 const int *const *my_value_pp = (const int *const *)&...
First, the two lines does not require casting, so just write: const int* my_value = &GetValue(); // 7 const int* const* my_value_pp = &my_value; // 8 You can however not write that as a one-liner as the function you are going to call needs the address of my_value. You can however skip my_value_pp and call your...
63,627,534
63,627,755
C++ how can I make a swap function between two variables which are different in type
I want to make swap function, which can take two different type of variables as parameters. for example) int a = 2; double b = 1.1 swap(a,b)//wish a = 1.1, b = 2 template<typename T, typename U> void swap(T& x, U& y)//it doesn't work due to automatic type cast { U temp = x; x = y; y...
You cannot do that because the objects types can't be changed. the double will be truncated as an int and the integer will be saved as a double. However, you can use std::variants, as follows #include <variant> #include <iostream> void swapDoubleVariantByIntOne(std::variant<int, double>& intVar, std::variant<int, doub...
63,627,765
63,629,427
C++ DLL to Delphi: How to pass a pointer to data from C++ DLL to Delphi program?
I want to store data in a DLL and pass its reference and size to the Delphi program. I created a C++ DLL project and a Delphi application project. Then I load the DLL explicitly by LoadLibrary and GetProcAddress. However, I couldn't access the data using the returned reference. Following are the source codes: C++ DLL c...
There are numerous mistakes in this code. On the C++ side; The data parameter is being passed by value, so reassigning its value will only be local to the function and won't affect the caller at all. You need to pass the parameter by reference/pointer instead. You are attempting to do that with the bufferLength parame...
63,627,776
63,628,094
Functional composition with std::bind
I am reading the second edition of the beautiful book of Nicolai Josuttis on C++11 STL. I found the following piece of code: #include <functional> #include <iostream> int main() { auto plus10 = std::bind(std::plus<int>(), std::placeholders::_1, 10); std::cout << "+10: " << plus10(7) << std::endl; ...
It is called nested binding (i.e. std::bind). A std::bind call has one or more std::binds. In that case, it works as follows: First, invoke the nested std::bind expression, meaning this std::bind(std::plus<int>(), std::placeholders::_1, 10) with the first argument to the plus10times2, and pass to the outer one: i.e. ...
63,628,024
63,628,294
Why garbage value showing up?
User enters a string like '3+2+1' or '1+3+2+1+3+1'. And I just have to sort the string. But after 4-5 test cases error shows up. Input - 2 Output - � Input - 2+1+2+2+2+3+1+3+1+2 Output - �+1+1+1+2+2+2+2+2+3 #include<iostream> using namespace std; int main() { string s; cin>>s; for(int i=0;i<s.size();...
As ggorlen said, garbage is showing up because you're accessing a value that's out of bounds. Try checking if your "j" index plus 2 is out of bounds before doing any swap. #include<iostream> using namespace std; int main() { string s; cin>>s; for(int i=0;i<s.size();i+=2) { for(int j=0;j<(s.si...
63,628,159
63,628,792
How to correctly setup cmake for glfw on clion on MacOS
I've recently bought a Macbook and I want to start writing some OpenGL code for a project. SPECIFICATIONS MacOS Macbook pro 16inch 2019 Clion glfw3 (precompiled binaries 64 bit) The CMake doesn't complain, but as soon as I start compiling I get the following error /Applications/CLion.app/Contents/bin/cmake/mac/bi...
Did you read the documentation? You're missing three frameworks if you compile like that: target_link_libraries(graphics glfw3 -framework Cocoa -framework OpenGL -framework IOKit) Better to just use the find_package approach
63,628,479
63,628,576
C++ include loop. Can't use forward declarations
I want to do something like this, running from main(): Main.cpp #include "A.h" #include "B.h" int main(){ A* a = new A(); B* b = new B(a); b->render(); return 0; A.h class B; class A { public: void renderObject(B* b); } A.cpp #include "A.h" void renderObject(B* b) { int* data = b->data; //...
For this line in A.cpp you need more than "it is a class", the information provided by a forward declaration. I.e. in this file you need an additional #include "B.h" Similar for B.cpp, it needs to include A.h for the contained code. (Thanks, Scheff.) And, at least if only looking at the shown code, you do not really n...
63,628,498
63,628,735
Class destructor is causing problem with overloading + operator
I can't figure out what is the problem with my C++ class (using Visual Studio). Visual Studio is not giving any desired output, just saying " exited with code -1073741819". I created a class named Complex using raw pointers, when no-args or parameterized constructor is called, memory is allocated using new int and when...
You don't allocate any memory in your copy constructor, so your assignments happen to uninitialized memory. Complex::Complex(const Complex& source) { *(this->real) = *(source.real); *(this->complex) = *(source.complex); } If I change it to this: Complex::Complex(const Complex& source) : Complex() { *(this-...
63,628,639
63,628,749
Understanding working of copy constructor
To understand working of constructor, copy constructor, destructor, I wrote the following code. #include <iostream> using namespace std; class Cat { public: Cat(); Cat(Cat&); ~Cat(); int itsage; }; Cat::Cat() { cout << "Constructor called\n"; cout << this << endl; itsage=2; } Cat::Cat(Cat& theCat) ...
Your first code returns a copy of Frisky from myFunction, that is where the additional copy comes from. Your second code doesn't work because your copy constructor erroneously takes a non-const reference and you can't pass the temporary value returned from myFunction to a non-const reference. Not directly related to yo...
63,628,752
63,629,606
Does a class template's requires clause have to be repeated outside member definitions?
When the member of a class template that uses the requires clause is defined outside the class, gcc does not complain if requires is not specified, whereas clang does. Consider the code snippet below: #include <concepts> template<typename Container> requires std::integral<typename Container::value_type> class Foo ...
A bug should be filed for GCC, because it accepts the code, even though the declaration of the member outside the class does not have an equivalent template-head. [temp.class] 3 When a member function, a member class, a member enumeration, a static data member or a member template of a class template is defined outsid...
63,629,468
63,642,572
How to link a dynamic library in QtCreator use qmake and MinGW32?
I am trying to use hiredis and libevent in my project, I downloaded their source code and compiled them with CmakeGUI and MinGW32. Then i got the header files and those library files. libevent.a libevent.dll libevent.dll.a libevent_core.a libevent_core.dll libevent_core.dll.a libevent_extra.a libevent_extra.dll libeve...
I once set a 64-bit version of MinGW in environment variables, but I forgot When I changed it to the 32-bit MinGW path, the compilation was successful and the dynamic library can be used
63,629,578
63,629,650
Why do we need a null terminator in C++ strings?
I'm new to programming and very new to C++, and I recently came across strings. Why do we need a null terminator at the end of a character list? I've read answers like since we might not use all the spaces of an array therefore we need the null terminator for the program to know where the string ends e.g. char[100] = "...
The other characters in the array char john[100] = "John" would be filled with zeros, which are all null-terminators. In general, when you initialize an array and don't provide enough elements to fill it up, the remaining elements are default-initialized: int foo[3] {5}; // this is {5, 0, 0} int bar[3] {}; ...
63,629,798
63,630,028
Assigning a pre-determined value to an input variable if not specified
I have a variable as an input which you should be able to initialize or not. Trying to explain better through code: double simulate(double a, double b, double x, double u, double dt) I want to have the possibility to initialize dt as 0.1 if it's not specified by the user. For example: int main() { std::cout << sim...
Using a default parameter is the easiest solution: double simulate(double a, double b, double x, double u, double dt = 0.1); int main() { std::cout << simulate(2.5, 1.2, 6.2, 3.0); std::cout << simulate(2.5, 1.2, 6.2, 3.0, 0.0); } Another option is to overload the function: double simulate(double a, double b,...
63,630,069
63,630,292
const_cast: modifying a formerly const value is only undefined if the original variable is const
https://stackoverflow.com/a/332086/462608 modifying a formerly const value is only undefined if the original variable is const ... if you use it to take the const off a reference to something that wasn't declared with const, it is safe. ... This can be useful when overloading member functions based on const, for i...
Regarding your first two quotes: void do_not_do_this(const int& cref) { const_cast<int&>(cref) = 42; } int main() { int a = 0; // "if you use it to take the const off a reference // to something that wasn't declared with const, it is safe." do_not_do_this(a); // well-defined // a is now 4...
63,630,760
63,630,934
Does dynamic_cast work even when there is no inheritance?
std::bad_cast: https://en.cppreference.com/w/cpp/types/bad_cast An exception of this type is thrown when a dynamic_cast to a reference type fails the run-time check (e.g. because the types are not related by inheritance) So, if the types are not related by inheritance then it throws an error, so how it the following...
Sideways cast would be for example like this: class Base1 { virtual ~Base1() = default; }; class Base2 { virtual ~Base2() = default; }; class Derived: public Base1, public Base2 {}; int main() { Base1* p1 = new Derived; Base2* p2 = dynamic_cast<Base2*>(p1); } Types Base1 and Base2 are unrelated to each other,...
63,631,035
63,632,036
Doxygen manner of presentation member variables
How to change in doxygen on graphs this: to include member variables in second empty field? Edit: Inheritance graph is ok, only colaboration is problem Doxygen version : 1.8.17 Doxyfile: # Difference with default Doxyfile 1.8.17 PROJECT_NUMBER = Beta PROJECT_BRIEF = Game FULL_PATH_NAMES = N...
I found it, I had to set HIDE_UNDOC_RELATIONS to YES. FRom the documentation: HIDE_UNDOC_RELATIONS If set to YES the inheritance and collaboration graphs will hide inheritance and usage relations if the target is undocumented or is not a class. The default value is: YES.
63,631,107
63,631,213
The equivelant code %SystemDrive% in batch translated into C++
To anyone that can help Please, (My operating system is Windows XP) I have looked on the this forum but have not found a similair answer that I could use or adapt to suite this particular situation. I will try to explain (I apologise in advance if my question seems confusing) I am constructing a batch file that will ca...
The search term you should be looking for is Known Folders. Specifically, calling SHGetKnownFolderPath() with the FOLDERID_System identifier, one of the many IDs found here. That's for Vista or better. For earlier than that (such as XP), you have to use CSIDL values, CSIDL_SYSTEM (see here for list) passed into SHGetFo...
63,631,140
63,631,375
Why passing a pointer by reference here causes an error?
I have a template node class: template<typename T> class TNode { T data; TNode<T>* left; TNode<T>* right; public: TNode() { left = right = nullptr; } TNode(T d) { data = d; left = right = nullptr; } void setData(T d) { data = d; } T getData() { return data; } void setLeft(TNo...
The getLeft method returns a copy of the left member variable, so even if your code compiled it would not alter left. However it doesn't compile because of the rule that you cannot bind a reference to a temporary. Several solutions are possible, the one that seems the best to me is to replace getLeft with left and getR...
63,631,603
63,631,861
How to pick a random position from a fixed array with a required value
Let's say we have an array, block[5]={0,1,0,3,0}. The array has three zeroes and I want to find a random position of one zero. And how can i make this with a bidimensional array?
You can use std::vector #include <vector> std::vector block = {0,1,0,3,0}; std::vector index_vector; auto it = block.end(); while(it =! block.begin()) { auto newit = std::find(block.begin(), it, 0); if (newit =! it) { it = newit; int index = std::distance(block.begin(), it); index_vector.pu...
63,631,956
63,631,996
Refer to an overlapping function with "using namespace std"
I am well aware of pitfalls by doing this. For example: #include <iostream> #include <tuple> using namespace std; //a simple function that returns the index of max and max value of a parameter pack template <typename...T> tuple<int, int> max(T... args) { const int size = sizeof...(args); int list[size] = {args.....
You can invoke your particular max overload using the scope resolution operator :: to ensure qualified name lookup is performed instead of unqualified one: ::max(10, 20, 30); in which case overload resolution will consider your own max function overload as a better viable function than that that of the overload in the...
63,632,193
65,921,532
error: unable to handle compilation, expected exactly one compiler job in '' [clang-diagnostic-error]
Build fails without much helpful information after I've added this into my CmakeLists.txt to enable clang-tidy checks: if(ENABLE_CLANG_TIDY) find_program(CLANGTIDY clang-tidy) if(CLANGTIDY) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_CXX_CLANG_TIDY "${CLANGTIDY};-extra-arg=-Wno-unknown-warning-option;-h...
I got the same problem and solution is simple - remove the last semicolon in your CMAKE_CXX_CLANG_TIDY string: Your line: set(CMAKE_CXX_CLANG_TIDY "${CLANGTIDY};-extra-arg=-Wno-unknown-warning-option;-header-filter=${CMAKE_SOURCE_DIR}/src/*;") To be replaced with: set(CMAKE_CXX_CLANG_TIDY "${CLANGTIDY};-extra-arg=-Wno...
63,632,255
63,632,572
How can I get line number and column from v8 script compile error?
When embedding the V8 Javascript engine in a C++ project, I haven't found any way to get the line number for compilation failure of a script. I have tried the following: //Given that v8 is initialized, isolate, context and script_source is setup. v8::TryCatch try_catch{isolate}; //Compile the script from source v8::Lo...
It seems the line number is stored in a v8::Message associated with the exception. I found the following in an example in the v8 repo: void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) { v8::HandleScope handle_scope(isolate); v8::String::Utf8Value exception(isolate, try_catch->Exception()); cons...
63,632,391
63,632,488
other results when declaring in main method vs. outside from main method
I am currently doing a simple problem on codeforce. Basically you are given a string (e.g. "1+3+2") and you have to return it sorted (e.g. "1+2+3"). Only 1,2 and 3 will be used. I started with: #include <iostream> using namespace std; int main() { string str; int arr[4]; cin >>str; for(int i =...
Automatic storage duration with no initializer: default initialization applies: an array of fundamental non-class type will remain with uninitialized values In your first example, arr has automatic storage duration and is uninitialized, as a result of default initialization: int main() { // default initialization ...
63,632,425
63,633,001
Is there a way to check the maximum method length in C++?
I'm searching a tool that can check if there is a method in my C++ code thats line length is larger than a maximum I can define. I would like to define a threshold of e.g. 50 lines and if there is a function with e.g. 60 lines, the tool should warn me after analyzing. I know that there is a functionality like that in c...
The readability-function-size check of Clang-Tidy does exactly what you are asking for (and more).
63,632,805
63,632,970
Segmentation fault while trying to implement fixed size queue in C++
I wanted to implement a fixed size queue, I could have easily done with a struct having a queue as one of the data members and a member function that takes care of the push part of the queue, but rather wanted to try it out by inheriting queue like this. template<typename T> struct f_queue : public queue<T>{ int n;...
Your push function always recurses into itself: void push(T data){ if(this->size() < this->n){ this->push(data);//HERE f_queue::push is called }else{ prev = this->front(); this->pop(); this->push(data);//HERE f_queue::push is called } } You pr...
63,633,004
63,633,290
Template-defined number of template parameters (very meta)
template<int Degree> using curve = // some definition template<int MaxDegree> using curve_variant = std::variant<curve<1>, curve<2>, .. curve<MaxDegree>>; In the above example, the number of parameters passed to std::variant's template would change depending on curve_variant's parameters: For example, curve_variant<4>...
With std::integer_sequence helper, you might do: template <typename Seq> struct curve_variant_impl; template <int ... Is> struct curve_variant_impl<std::integer_sequence<int, Is...>> { using type = std::variant<curve<1 + Is>...>; }; template <int MaxDegree> using curve_variant = typename curve_variant_impl<std::...
63,633,437
63,633,813
Sampling conditional distribution OpenMP
I have a function which draws a random sample: Sample sample(); I have a function which checks weather a sample is valid: bool is_valid(Sample s); This simulates a conditional distribution. Now I want a lot of valid samples (most samples will not be valid). So I want to parallelize this code with openMP vector<Sample...
You may employ OpenMP task parallelism. The simplest solution would be to define a task as a single sample insertion: vector<Sample> valid_samples(n); // need to be resized to allow access in parallel void insert_ith(size_t i) { do { valid_samples[i] = sample(); } while (!is_valid(valid_samples[i])); } #pragm...
63,633,656
63,660,540
solving linear equationsystem in cpp using lapacke_dgesv
I am trying to solve a very simple equationsystem of the form M*Z=V, where M is a 2x2 Matrix, V and Z are Vectors with 2 entries. If i use Z = linsolve( M, V ); in Matlab the result is correct. I need to implement this in C++ somehow so I am trying to use the INTEL MKL Math library. Z should be calculated to be about [...
You should print V vector instead of z, z is just the pivot information.
63,633,937
63,646,482
std::invoke substitution failure for member function pointer
I'm working with webview (found here: https://github.com/webview/webview) to create a c++ program with a html/js gui. In order to call c++ functions from js, they must be in the form std::string function(std::string). This is fairly trivial for free functions, however it seems not so trivial if you want to pass a point...
With auto b1 = binder(w, tc, &testclass::num, "num"); // This compiles auto b2 = binder(w, tc, &testclass::add, "add"); // This doesn't You use CTAD (C++17), but from: template <class Obj, class F, class ...Args> class binder{ public: binder(webview::webview &w, Obj& obj, F func, std::string name); // ... }; ...
63,634,367
63,634,618
Linking an external pre-built library in CMake
I am building a project that utilizes a library that is outside of the scope of the project. I am relatively new to CMake and I can't seem to get this library to build. my code is below: cmake_minimum_version(VERSION 3.1) project(cameraCode VERSION 1.0.0) add_library(camControl SHARED IMPORTED ...
add_library would mean that you are building the library. I don't think add_library is what you want, if this is the prebuilt library as you say. It looks like you just need link_directories and include_directories for the client to be able to find library and header files.
63,634,470
63,634,597
How to understand this result when using std::sort?
I'm trying to implement a PP class. Please first help check the following imcomplete code: template <typename E> class PP{ public: struct Point2D { static int used_count; E _x; E _y; Point2D() : _x(0), _y(0) { used_count++; std::cout << "Point2D(), used_count ...
You are not measuring the copy constructors that are invoked. You can do that by adding: Point2D(Point2D const & p) : _x(p._x), _y(p._y) { used_count++; std::cout << "Point2D(), used_count = " << used_count << "\n"; } If you do that, you get the expected used_count. Here's a demo. The extra copies are made i...
63,634,525
63,637,663
CreateHwndRenderTarget throwing exception: read access violation. **this** was nullptr
I have been recently been learning Win32 API using this tutorial. I have been trying to create a window which displays a circle using Direct2D based on it. However, the program keeps throwing an exception: Exception thrown: read access violation. **this** was nullptr. VS 2019 then opens d2d1.h to this section: CreateH...
You pFactory reference is null. But you do initialize it, so why is it null? Because your code is broken, it does this: LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { ... some code case WM_SIZE: { ... some code } ...
63,634,917
63,635,154
FreeRTOS Task should not return - ESP32
I'm using multi-threading on my ESP32. I have created two tasks and pinned them to core 1. With one of them, I get the following error: E (20426) FreeRTOS: FreeRTOS Task "MeasurementTask" should not return, Aborting now! abort() was called at PC 0x4008b8f3 on core 1 Backtrace: 0x4008f34c:0x3ffd0a40 0x4008f57d:0x3ffd0a...
In FreeRTOS, tasks are started with xTaskCreate... and ended with vTaskDelete. A task function may not simply "end", this is not allowed. Put vTaskDelete(NULL); at the end of the function to gracefully end the task: void takeMeasurement(void *pvParameters) { // . . . task code . . . vTaskDelete(NULL); } Having sai...
63,635,285
63,635,353
reinterpret_cast - An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type
https://en.cppreference.com/w/cpp/language/reinterpret_cast An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11) Why should I be interested in converting something to its own type? This re...
Because maybe you don't know if it is "its own type". Maybe you're in a template function, where you're calling some function whose return value you require to be reinterpret_castable to a template parameter T. So it's OK for that function to return a value of type T. For a more useful example, let's say you're given s...
63,636,781
63,636,927
Dividing by 0 is a compiler error or a runtime error
I'm new to C++. I heard that dividing by 0 leads to a run time error, but when I tried it, it threw me a compiler error C2124 and didn't create an object file, so does the compiler automatically run the code to see whether it's executable before creating an object file? (I'm using Visual studio community btw) int main(...
This depends on the context in which you do a division by 0. If you do it in a context that only needs the expression to be evaluated at run-time, then it's undefined behavior: void f() { int a = 9 / 0; // UB } Note that UB means anything can happen, including the compiler noticing that the code is buggy, and refus...
63,637,002
63,640,010
Get compressed image from camera in ROS using image_transport
I'm using ROS version 1 on a turtlebot and I would like to write a C++ program that captures an image in JPEG format, so I can provide the image to a service that needs it to be in that format. I'm trying to use image_transport and compressed_image_transport to achieve this. It looks like the basic structure should b...
So after some research, I figured out the problem. Basically, when you want to capture compressed image data, you need to run: rosmake compressed_image_transport as indicated above, to make compressed images available from your camera. The camera will now publish compressed image topics, as you can determine by runn...
63,637,020
63,637,122
Garbage-collect declared struct after using
{ //i want remove it after using struct pTemporary001 { string name; }; pTemporary001 *pTemporary001_var = new pTemporary001; ConsoleQuestioner<pTemporary001>("TEST TEXT", pTemporary001_var, [](string *name, pTemporary001 *temp) { temp->name = *name; }); cout << "test : " << ...
C++ doesn't have garbage collection. And (unlike in dynamic languages) types do not consume memory in C++1, so there is no garbage to collect. 1 At least, not all types. Polymorphic types may require some amount of memory for RTTI and virtual dispatch. The shown class is not polymorphic. There is no way to release such...
63,637,403
63,637,585
Multithread for loop function not working correctly
I tried to implement simple for loop running on custom number of threads like this: #include <thread> template<typename func, typename... args> void threadFor(int numOfThreads, int repeats, func f, args... a) { auto forPart = [&](int repeats){ for (int i = 0; i < repeats; ++i) f(i, a...); }; i...
You need to synchronize your threads' access to the shared variable. std::atomic? This gets 1,000,000: #include <thread> #include <vector> #include <atomic> #include <iostream> template<typename func, typename... args> void threadFor(int numOfThreads, int repeats, func f, args... a) { auto forPart = [&](int repeats)...
63,637,443
63,637,573
Can I make expressions constexpr?
I recently wrote some code which prints a function result to cout. The result could have been evaluated at compile time, but it wasn't: #include <algorithm> #include <iostream> constexpr unsigned int gcd(unsigned int u, unsigned int v) { // ... } int main() { std::cout << gcd(5, 3) << std::endl; } For whatev...
How about an immediately invoked lambda expression? #define CONSTEVAL(...) []{ constexpr auto result = __VA_ARGS__; return result; }() This is effectively a way to produce a constexpr variable to hold the result and evaluate to the variable's value. This can also be done macro-less via a template, but only if the val...
63,637,623
63,638,031
C++ Find in a vector of <int, pair>
So previously I only had 1 key I needed to look up, so I was able to use a map: std::map <int, double> freqMap; But now I need to look up 2 different keys. I was thinking of using a vector with std::pair i.e.: std::vector <int, std::pair<int, double>> freqMap; Eventually I need to look up both keys to find the correc...
The blanket answer to "which is faster" is generally "you have to benchmark it". But besides that, you have a number of options. A std::map is more efficient than other data structures on paper, but not necessarily in practice. If you truly are in a situation where this is performance critical (i.e. avoid premature opt...
63,637,762
63,637,856
What happens when a string literal is passed to a function accepting a const std::string & in C++?
as you can probably guess from the title, I want to understand what exactly happens when a std::string is passed to a function as a const reference, because earlier today I ran into a few situations I didn't quite understand entirely. Here's some code: #include <string> #include <stdio.h> struct Interface { virtua...
When you pass a string literal to a function that accepts const std::string&, the following events occur: The string literal is converted to const char* A temporary std::string object is created. Its internal buffer is allocated, and initialized by copying the data from the const char* until the terminating null is se...
63,637,904
63,638,190
Regex replace names of methods
I'm trying to replace all occurrences of names within a given string. I'm using regex, since a simple substring match won't work in this case and I need to match full words. My problem is that I can only match words before and after blanks. But for example I cannot replace a string when it's followed by a blank, like: ...
You need to Escape all special characters in the regex pattern with std::regex_replace(search, std::regex(R"([.^$|{}()[\]*+?/\\])"), std::string(R"(\$&)")) Escape all special chars in the replacement pattern with std::regex_replace(replace, std::regex("[$]"), std::string("$$$$")) (that is in case you replace with lite...
63,637,911
63,638,257
How can I throw errors with custom error messages?
I have a function that allocates a text font on the heap from a filename. It looks like this: std::unique_ptr<sf::Font> newFont(std::string&& fileName) { auto font = std::make_unique<sf::Font>(); if (!font->loadFromFile(fileName)) { exit(0); } return font; } Someone on Stack Exchange - Cod...
Exceptions are what you are looking for: std::unique_ptr<sf::Font> newFont(std::string&& fileName) noexcept(false) { auto font = std::make_unique<sf::Font>(); if (!font->loadFromFile(fileName)) { throw std::runtime_error("Unable to allocate font: " + fileName); } return font; } Now we can p...
63,638,955
63,639,021
C++ why does new keyword works and malloc does not?
I'm learning about pointers and structures and I ran into this hard to understand the problem for me. I have created this simple program for testing purpose: #include <iostream> struct testStructure { int a = 0; int b = 0; int c = 400; }; int main() { struct testStructure* testStruct; testStruct =...
new initializes the allocated memory with the class' constructor (which is implicit in this this case). malloc performs no initialization, it just allocates a portion of memory. Reading uninitiazlied memory will have undefined behavior.
63,639,034
63,639,157
Why does -Wfatal-errors turn off notes about the error, and how do I turn notes back on?
I often build with -Wfatal-errors because I don't need an extra 100 meaningless errors while the compiler heroically tries to parse the rest of a source file after a typo that renders it meaningless. However, I've noticed that this also turns off diagnostic notes about the fatal error itself. For instance, with -Wfata...
You're looking for -fmax-errors=1. This will terminate compilation after the first error, but still show the notes for that error. Here's a demo to compare the effects of these flags.
63,639,291
63,639,678
Question 1: execution time of calling the function
If most of the calls to function foo() below pass one of 10 particular values, which method will significantly reduce the execution time of calling the function? which choices are correct? I think Choice D but I am uncertain. Experts. Thoughts? A. Replace * with an if-else block testing for the 10 values, assigning r a...
B will not have any effect. inline only suppresses the one-definition rule; it does not force the compiler to inline the function. C is unlikely to have any impact; if the compiler determines that the function is a good candidate to be inlined, it will do so. Manually inlining it could make performance worse. The oth...
63,639,655
63,639,904
Visual Studio 2019 "C1001 internal compiler error" only in Release
I'm getting a C1001 error while attempting to build in Visual Studio 2019 Version 16.7.2. This is a C++ project that has previously built fine until a change set I am attempting to build today. The exact error is as follows: (with project specific path redacted) 1>d:\work\[...](82): fatal error C1001: An internal error...
SUGGESTIONS Please: Update your post with exact error text (if available) Post your question to https://developercommunity.visualstudio.com/ as well See if any of these links are applicable: https://developercommunity.visualstudio.com/content/problem/710576/visual-studio-2019-1622-fatal-error-c1001-in-32-bi.html ...
63,639,725
63,640,600
Emitting parameterized _Pragma statements?
It's often undesirable but sometimes unavoidable to emit #pragma directives to suppress and restore warnings. Some compilers support _Pragma as a way to, among other things, control diagnostics from inside a macro expression. How to concatenate strings in the arguments of _Pragma discusses how to paste a single string ...
Works: // double expand for proper "something \"something\"" #define PRAGMA_DO1(X) _Pragma(#X) #define PRAGMA_DO(X) PRAGMA_DO1(GCC diagnostic ignored #X) #define DISABLE_COMPILER_WARNING(X) \ _Pragma("GCC diagnostic push") \ PRAGMA_DO(-W##X) #define RESTORE_COMPILER_WARNING() \ _Pragma("GCC diagnostic po...
63,639,805
63,642,295
Call member function of std::map value object on insertion
I have an std::map of type std::map<key, value>. I want to define a function f on types key void f(key k){ // stuff } that does the following: If there is no value v in map with an equivalent key, k`==k, then insert std::make_pair(k, values(k)) into map. If there is a value v in map with the equivalent key, k'==k, th...
You can do it in C++17 efficient: auto [iter, success] = myMap.try_emplace(k, k); if (!success){ (iter -> second).g(k); } According to the manual it inserts in-place if the key does not exist, does nothing if the key exists. std::map<Key,T,Compare,Allocator>::try_emplace
63,641,010
63,644,871
How do developers handle large Git repositories with code dependencies not trackable by Git?
My company has a repository for a large CPP client-server application. We have an extra drive within our network containing the latest compiled projects for the entire app so every developer only has to build his own changes ( Building the entire application takes a few hours ). These precompild projects are updated e...
So dependeny.cpp uses Project 1's interface.h . Now we have two developers and Developer 1 makes a change to interface.h and expands a struct and pushes it to the upstream repository. Developer 2 DOES NOT pull the changes but DOES get the latest compiled projects from the network drive. So now Visual Studio uses your ...
63,641,095
63,641,631
How to abstract code which calls various other code
I’m doing a bunch of projects in CLion, each of which has two pieces of code: Solution and TestConductor. The Solution is the solution to a code kata, and the TestConductor uses Catch2 to run the tests (which are stored in input_n.txt and output_n.txt files). TestConductor has to call Solution, of course. Solution chan...
You can make TestConductor generic in terms of its Solution class, simply change the class declaration like so: template <class Solution> class TestConductor { ... }; The declaration can then go into a header file that you can include across projects. In each project you can then supply your testcase as: TEST_CASE() {...
63,641,440
63,662,844
Output for directory_entry conflicts with overloaded ostream operator<< for class with variant
I have a project where I print std::filesystem::directory_entry from directory_iterator. On the other side, I have a completely independent class with overload std::ostream& operator<<, that has a templated constructor, which initializes a std::variant member. #include <variant> #include <iostream> #include <filesystem...
With Mansoor's hints, I think I found out. C-tor This code is dangerous. class Var { public: template<typename T> Var(T value) { } }; Avoid this. The compiler will try to substitute such c-tor in any implicit conversion where Var is visible and may be suitable. Mark c-tor as explicit is the most straightforwa...
63,641,505
63,641,738
Using std::enable_if with out-of-line member functions and templated static member conditions
I want to use SFINAE to create a templated member function which takes a Consumer functor. Whether something is a consumer depends on a templated static constexpr bool isConsumer member variable. I have simplified my code down to the following example: #include <type_traits> template <typename T> struct Container { ...
It seems that there really is no way to make an out-of-line definition given the current declaration (gcc complains that the declaration uses an "anonymous type") Possible workarounds: Use a static_assert instead of SFINAE: #include <type_traits> template <typename T> struct Container { template <typename Consumer...
63,641,766
63,643,046
How can I multiply an Armadillo matrix with a NumericVector obtained from qnorm()?
When I try to multiply an arma::mat and a NumericVector in Rcpp using operator*, I get the following error: no match for operator* Here is an example of what I'm trying to multiply: NumericVector exampleNumericVector(L-1); arma::mat exampleMatrix(L-1,L-1); exampleMatrix*(Rcpp::qnorm(exampleNumericVector,0,1,true,false...
Your example is neither complete, nor minimal, nor reproducible. So in an attempt to approve on this, a full example. You feed is vector of p values to obtain quantile values for, it creates a (nonsense) matrix of suitable dimension, creates an arma vector from the Rcpp vector (key: they all convert to/from SEXP) and ...
63,641,958
63,641,983
How to populate and edit a std::array of maps
I have an array of maps: std::array<std::map<double, double>, 8> freqMap; When populating this I need to add entries to the map at different array indices. I know I can create 8 different maps, populate them, and then add them to the array, but is it possible to keep appending entries to the maps directly in the array...
You can simply do: while (fin >> arrayIdx >> key>> val) freqMaps[arrayIdx][key] = val; For example, how would I go about adding a map entries of key 5.0, val 3.3 to array index 2 freqMaps[2][5.0] = 3.3; Here's a demo. Also, note that using double as keys in a std::map is not a good idea.
63,641,985
63,642,010
Prevent infinite recursion in c++
So, I'm triying to learn c++ (coming from python), and I wanted to make a program just to see if i could do it with what i've learned, here's the code #include <iostream> using namespace std; int response(string i) { if (i == "yes" or i == "Yes") { cout << "\nHello, sad, I'm dad\n"; return(0); ...
This can be solved by eliminating recursion ad it involves moving the input routine inside of a function that's more self-contained: int getResponse(string i) { for(;;) { string i; cout << "Are you sad?"; cin >> i; if (i == "yes" or i == "Yes") { cout << "\nHello, sad, I'm dad\n"; ret...
63,642,011
63,688,967
Raytracer help - Background color writing over some colors?
I'm implementing Peter Shirley's "Raytracer in a Weekend: The next week" and I'm having some trouble with rendering a scene with a light. I'm not sure if the issue is the background color or the light itself but the raytracer seems to be working fine in any scenes that have no lights. The image rendered is supposed to ...
I found my answer here :https://computergraphics.stackexchange.com/questions/10160/raytracer-help-background-color-writing-over-some-colors @PaulHK helped me realize that there was a bug in my Lambertian class and once I realized this, the image rendered perfectly This was his answer: " just had a quick browse through ...
63,642,169
63,642,185
Why is this error on using strtok function showing when I use a different version of GCC?
I have this piece of C++ code: const char *Delim = "some text"; char *token; ... token = strtok('\0', Delim); // error here The error is as follows: invalid conversion from 'char' to 'char*' [-fpermissive] I tested this in GCC 5.3 and it worked. But in GCC 8.1 it fails and gives me the error. I understand I hard-code...
It's because the char expression '\0' is no longer a null pointer constant (and thus no longer convertible to a pointer), since C++11. Your newer compiler uses a new version of C++ by default. You're supposed to pass an actual null pointer (i.e. nullptr, or NULL in the old days) to that argument, not '\0'. In the past ...
63,642,472
63,642,500
Copy the struct to new one
I am trying to copy the members of struct to new one and making some adjustment to them. I am trying to print the value of the member but it is printing the address instead. I have commented on the parts. #include <iostream> using namespace std; struct MyStruct { char *name; int * countSize; }; MyStruct * stCp...
cout <<"printing the size of newStruct" << Strtptr -> countSize; // why is this printing the address instead? Because you're printing the pointer value of Strptr->countSize. What you want to print is the value which coutSize is pointing. cout <<"printing the size of newStruct" << (*Strtptr -> countSize);
63,642,647
63,642,657
Add a set of numbers in C++
I know I can store the numbers in an array first like arr[] = {1,2,3}; then call a sum function to add all the numbers like sum(arr); But what if I want to not use the arr[] and just call sum(1,2,3)? The values will be determined by the user so it can be sum(1,2), sum(1,2,3,4,5) or sum(1,2,5) #include <iostream> #inclu...
You can write the function like this: template<typename ...Ts> auto sum(Ts ...ts) { int arr[]{ ts... }; addition(arr); } which stores the variadic arguments into an array, and the calls addition on that array. Here's a demo. However, you can also simply write sum like this: template<typename ...Ts> auto sum(T...
63,642,709
63,644,977
How do I convert vectors of various types to std::string?
I am coming to C++ from haskell and python where there are built-in ways of converting data types to strings. For example, in Haskell there is the polymorphic function show. I am interested in creating some template functions in C++ that would do something similar. For instance, we could convert vector<int> to a string...
What if I wanted to create a polymorphic toString that works with vector<class A> and vector<vector<class A>? How would I go about this? Yes it is possible in c++17, by the cobination of if constexpr feature and a recursive function template (i.e. making the toString as recursive function template). Before jumping in...
63,642,761
63,642,824
SDL2 not creating triangle
I tried to make a triangle, but it wont render when i compile and run the program. Here is the code: #include <iostream> #include <gl/GL.h> #include <SDL.h> #include <SDL_opengl.h> const int windowWidth = 1280, windowHeight = 720; int main(int argc, char* argv[]) { // Create window // SDL_Window* window = SDL...
Multiple issues: Call SDL_GL_SetAttribute()s before SDL_CreateWindow(). Create a GL context with SDL_GL_CreateContext() before trying to call any GL functions. If you do end up using SDL_GL_CONTEXT_PROFILE_CORE you'll need to completely re-write the rest of your GL code to not use all those removed functions like glBe...
63,643,025
63,648,397
Lua 5.2 Sandboxing in different objects with C API
Consider the following C++ code using the Lua C API: #include <string> #include <cassert> #include <lua/lua.hpp> class AwesomeThing { lua_State* _lua; std::string _name; public: AwesomeThing(lua_State* L, const std::string& name, const std::string& luafile) : _lua{ L }, _name{ name } ...
After messing around with the code myself, I was able to fix it and the errors seem to come from just a few errors. lua_pcall pops the called function from the stack, but in both cases in your code you assume the function is still on the stack after lua_pcall. This results in bad stack manipulation. In the constructo...
63,643,780
63,643,868
try and except, but in c++
Suppose I want to compute the binary value of a series of numbers entered by a user but I don't want to set a limit to how many numbers the user can enter, so I do this in Python 3: try: lst = list() while True: n = int(input("Enter the number: ")) b = binary_of(n) // Functi...
An exception is a problem that arises during the execution of a program. Allowing the user to stop giving more input is not a problem. Your logic should handle. There are multiple ways to do it. Try..catch is always there for you. One way could be parsing the input to check if the input is an int. If not, break the whi...
63,643,984
63,644,051
Getting same output everytime
This a simple number guessing game. If you guessed the number right, it outputs "You win!!!", but if the number of tries (numberofguesses) is exceeded, it should output "You lose", but it is showing "You win!!!" even though I checked the values of numberofguesses, secretnum and guess after the while loop. Answer in sim...
You have mistaken the assignment operator = with the comparison operator ==. In this line here: if (secretnum = guess && numberofguesses != 0) cout << "You win!!!"; Change it to: if (secretnum == guess && numberofguesses != 0) { cout << "You win!!!";
63,644,018
63,644,091
What is the benefit of moving a range of elements in a vector vs. copying?
Consider the following snippet (saw something analogous to this in a large simulation code) std::vector<int> v1{1,2,3,4,5,6,7}; std::vector<int> v2; std::move(v1.begin() + 2, v1.end(), back_inserter(v2)); Here, I am moving a range of elements from v1 to v2, but is there any particular advantage to doing this vs. copy...
Here, I am moving a range of elements from v1 to v2, but is there any particular advantage to doing this vs. copying? No. Here is all happened just a range coping, because your usage of std::move for primitive types just do coping. Therefore it does the same as simple if you would have: std::vector<int> v2{v1.begin()...
63,644,052
63,725,647
I don't understand why my code for binary search displays a segmentation error
I have tested the code for the vector a = {1,5,8,12,13} and x = 23, it sent me a segmentation error, and I don't understand why : #include <iostream> #include <cassert> #include <vector> #include <cmath> using std::vector; int binary_search(const vector<int> &a, int x) { int left = 0, right = (int)a.size(); ...
We can have indexes start and end which can point to the subarray where you want to do the binary search, this way we don't have to explicitly create a subarray. int binary_search(vector<int> &a, int start, int end, int x) { if(start > end) return -1; int mid = floor((double)(start + end)/2); if(a[m...
63,644,227
63,644,342
Warning on using std::remove_if on std::wstring (msvc c++20)
I have a function when takes a winapi HWND and returns wstring. std::wstring utility::winapi::window_class(HWND hwnd) { int title_length = 20; std::wstring class_name; class_name.resize(title_length, '\0'); GetClassName(hwnd, const_cast<LPWSTR>(class_name.c_str()), title_length); class_name.erase(st...
class_name is declared as a std::wstring. This is a string of wchar_t values, but your lambda argument is of type const char & which is more narrow. The warning is telling you that the value might be truncated. This could cause the test x == '\0' to evaluate as true when it should note. This is what the compiler is t...
63,644,324
63,644,341
STL list - What does [intNumber] do?
I have got a piece of code which defines a list from the STL. However, there is this "[256]" at the end that looks a bit like an array-declaration: std::list<myStruct*> foo[256]; I already googled it and the whole thing does not seem to be a list of arrays (That does not work in C++) limit the numbers of elements of ...
So what kind of container is this whole construct and what does this [256] do in this context? std::list<myStruct*> foo[256]; foo is an array of 256 elements, each of which is a list of pointers to myStruct. Think of it just like normal built-in type int bar[256]; and just replacing int with std::list<myStruct*>
63,644,552
63,644,652
Error , "include/Trading_GenericTemplate.h:37: error: expected constructor, destructor, or type conversion before â=â token"
I have a strange problem ,I am implementing Run Time polymorphism in my project which is a Trading Project(Server), here I am getting an error of instance initialization, I tried my best but couldn't get any solution. This is the code which shows compilation error which is "include/Trading_GenericTemplate.h:37: error: ...
The assignment statement startTrading[0] = new B(); is possible only in a function body, not allowed in the global scope. You may do STRAT_TEMPLATE* startTrading[20] = { new B() };
63,645,064
63,657,399
C++ wxWidgets Iterate through pixels in desktop screenshot
I'm new to C++ and am trying to take a screenshot of the desktop and store it to a file. Then I want to open the image and loop through each pixel in the image and access its RGB values. I accomplished this in Python fairly easily as i found some easy-to-use libraries to accomplish this task, but in C++ i'm having trou...
If you don't care about performance (e.g. you just do it once), you should indeed convert wxBitmap to wxImage and then use the methods of this class to access its data. If you do care about performance, you should use raw pixel data access and while this is less convenient (its API is lower level in order to allow it t...
63,645,356
63,645,620
How does auto decide the type of variable?
#include <iostream> int main() { auto n {42}; cout << "The n has value of " << n << " and a size of " << sizeof(n) << endl; // Works as expected } #include <iostream> int main() { auto n = {42}; cout << "The n has value of " << n << " and a size of " << sizeof(n) << endl; // Does not work! } ...
This is governed by the rules of [dcl.type.auto.deduct], particularly [dcl.type.auto.deduct]/1 and [dcl.type.auto.deduct]/4 [emphasis mine]: [dcl.type.auto.deduct]/1 Placeholder type deduction is the process by which a type containing a placeholder type is replaced by a deduced type. [dcl.type.auto.deduct]/4 If the pl...
63,645,568
63,645,769
Opengl reduce usage of uniforms
I have near 10000 vertex buffers (different sizes) and corresponding integer data for each buffer. So when i render i do something like this: Bind shader For each vertex buffer: Set uniform Bind vertex buffer Draw call This many uniform changes really slow down the program. So i was thinking of using a uni...
In general, OpenGL does not count the draw calls. You would have to manage a uniform counter yourself or you can generate an SSBO for each mesh and bind the SSBO belonging to the mesh before the draw call. A possibility I can see is using Multi-Draw (see glMultiDrawArrays ). But then you have to store the data for all ...