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
64,335,650
64,337,433
Read Serial Input into Char Array
So i've managed to wire up an ESP-01 module to my arduino, now im attempting to parse the +IPD responses the chip gives over a serial connection. Im not really all that handy with C++ but this is what i've managed to come up with after researching a bunch online: #include <SoftwareSerial.h> SoftwareSerial ESP8266(2, 3)...
Ended up going with a different way of doing things: Managed to read about readStringUntil(''); in some dark corner of the web. So i came up with a super dirty implementation - but it works: Assume your input string is: +IPD,0,14:%<255,128,0% Then do: if (ESP8266.available()) // check if the esp is sending a message ...
64,335,722
64,336,091
Arduino, understanding invalid conversion warning, unsigned char to char*
Edit: Resolved, can't accept my answer for two days I'm using PlatformIO to program a Arduino Nano to write a message to an OLED display. I'm calling a function printWeight: void printWeight( float weight, uint8_t scale=3, uint8_t numbd=3, uint8_t numad=2, bool kg=false, ...
Missing parameter... Thanks to the ones commenting.
64,335,766
64,345,755
Name resolution when a structure declaration is hidden by a variable
Let's consider the following demonstrative program. #include <iostream> struct A { struct B { int b = 10; }; int B = 20; }; template <class T> struct C { void f() const { typename /*struct*/ T::B b; int x = b.b; std::cout << "x == " << x << '\n'; } }; int ...
It should be a bug of the compiler gcc 8.3. Because the standard rule that typename T::B shall be resolved to variable rather than struct B, these rules are listed in the following: A class name or enumeration name can be hidden by the name of a variable, data member, function, or enumerator declared in the same scop...
64,335,949
64,336,012
Expression: vector erase iterator outside range when using vector.erase()
I am new to C++ and was trying to write a program that takes the lowest and the highest numbers in a vector, takes them away from the vector and proceeds to calculate an average with the rest of the numbers. Now while I understand that I could do it after the numbers have been entered, I wanted to challenge myself and ...
Inside your while loop, you are taking iterators to scoreVector. However, every time you do a push_back on a vector, all iterators to it are invalidated. This means that when you exit your while loop, at least one if not both iterators are dangling. Passing those iterators to .erase then invokes undefined behavior. Ins...
64,336,050
64,336,790
ProtoEnum attribute usage for renaming conflicting default values
I am attempting to generate c++ protobuf classes from a large c# .net codebase. The enumeration 'NotSet' is used as a default value in many enum declarations throughout, so I have used the ProtoEnum attribute to provide a different name for exporting where conflicts have arisen. However I have found that where my expor...
That's a bug in protobuf-net; I've fixed in in this commit, which not yet available in nuget - but note that this will apply in v3 only (I haven't back-ported the fix to the v2 branch).
64,336,192
64,354,664
Parallelization for three loops of a C++ code?
How can i parallelize this code using openmp: xp, yp, zp, gpx, gpy, and gpz are known 1D vectors. for (ies = 0; ies < 1000000; ies++){ for (jes = ies+1; jes < 1000000; jes++){ double dxp = xp[ies] - xp[jes]; double dyp = yp[ies] - yp[jes]; double dzp = zp[ies] - zp[jes]; double dist...
Here is a possibility (not tested) #pragma omp parallel for reduction(+: E1) private(jes, kes) schedule(dynamic) for (ies = 0; ies < 1000000; ies++){ for (jes = ies+1; jes < 1000000; jes++){ double dxp = xp[ies] - xp[jes]; double dyp = yp[ies] - yp[jes]; double dzp = zp[ies] - zp[jes]; ...
64,336,460
64,336,617
Is it possible to define 'step' size when iterating over a C++ container?
I know of the simple way to iterate, for instance, over every character of a string as so: std::string some_string("Hello World"); for(auto character : some_string) std::cout << character << std::endl; But is there a way to use this construction to also tell it to take steps, or take specific lengths of the contai...
This range based for loop (from cppreference): for ( init-statement(optional)range_declaration : range_expression ) loop_statement is equivalent to: { init-statement auto && __range = range_expression ; auto __begin = begin_expr ; auto __end = end_expr ; for ( ; __begin != __end; ++__begin) { ...
64,336,612
64,339,054
Visualize 2D and 3D shapes in code using templates
I remember a library (a single header I think) based on templates and operators overloading that allowed to visualize 2D and 3D shapes in code, with expressions like: assert( (I-----o | | o-----I).area() == (I---o | | | | ...
Thanks to Story Teller, the link is: http://www.eelis.net/C++/analogliterals.xhtml With a fork here: https://github.com/Quuxplusone/analog-literals Some actual code examples: unsigned int c = ( o-----o | ! ! ! ! ! o-----o ...
64,337,641
64,339,013
Draw and Rotate an Arrow
I am trying to draw an arrow using the style below but this arrow should be also rotated according to a condition (need to pass the degree for each condition). I can draw the rectangle and a triangle but I cannot draw the triangle as an arrowhead. Also, how can I include the rotation degree into the code? Is there any ...
You accidentally add angle_offsetR to the angle for the triangle vectors. Furthermore you've to restart a GL_TRIANGLE_FAN primitiv when you draw an new shape (see Triangle primitives). If you want to rotate the model, then set the add a rotation around the z axis to the model view matrix by glRotatef. Do not translate ...
64,337,871
64,338,115
Botan/C++ - Encrypting with AES using a key size larger than 32 bytes
I need to encrypt with AES-256, but I ALSO need a key size LARGER than 32 bytes. I have a function that takes text, a key, and an IV, and returns the encrypted text. It works with everything smaller than 32 bytes, but anything larger gives me an error. So essentially, how can I implement a way to use keys larger than 3...
With AES-256 the key size is always 32 bytes long (256/8 = 32). When the input secret is not exactly 32 bytes and/or of poor quality, a key derivation function is used. With keys of sufficient entropy a simple hashing function such as SHA-256, is sufficient. In other words, just feed your input key through SHA-256 and ...
64,338,030
64,338,633
Heap-Allocated QApplication Getting Deleted
In a basic C++ Qt Widgets application, creating a QApplication on the stack or heap-allocating it directly in the main function works, but calling a function the heap-allocates a QApplication and using the returned pointer gives a segmentation fault: #include <QtWidgets> QApplication* create_application(int argc, char...
The problem is not that you create your QApplication with dynamic storage duration, but that the constructor of QApplication is QApplication::QApplication(int &argc, char **argv) taking argc as reference. And these two notes/warnings: Note: argc and argv might be changed as Qt removes command line arguments that it re...
64,338,401
64,419,857
Setting a class function to a pointer in constructor C++
I have a class that I want to have a default function to be pointed to when constructing without parameters, but I want that functionality to change when a function is passed in with one of the parameters. I'm getting the error "a value of type "int (MyClass::*)(int myVar)" cannot be assigned to an entity of type "MyCl...
I tried what felt like every combination of function pointer typedefs and using but in the end I think that lambda is what worked. Thanks everyone for the help. --MyClass.h-- class MyClass{ private: std::function<int(int)> func; int defaultFunc(int myVar); public: MyClass(std::function<b...
64,338,697
64,339,119
Debug Assertion Failed caused by CreateDC() function
I have a problem with Debug Assertion Failed (picture) Debug Assertion Failed This problem occur when I push "Print" button on dialog box a second time. (on first time work well) Dialog Box: Dialog Box After debugging code I guess it is caused when I create DC second time. But I can explain why, because ealier I delete...
It looks like you are using MFC's CDC class, evidenced by hDC.CreateDC(DriverName, DeviceName, OutputName, NULL); For symmetry sake, delete it also by that class' method: CDC::DeleteDC hDC.DeleteDC();
64,338,975
64,339,094
operator* of std::complex returns different answer than manual formula of complex number multiplication
I'm running the following code: complex<int16_t> num1 (953, -20068); complex<int16_t> num2 (953, -20068); complex<int32_t> result; result = num1*num2; std::cout << to_string(result.real()) << "+" << to_string(result.imag()) << "i"<< std::endl; I get the following result: -15199+23416i But if I calculate the multipli...
Your complex numbers are of type complex<int16_t>, meaning the real and imaginary parts are both 16 bits. The result of multiplying them must also have real and imaginary parts of 16 bits. This happens before you store the result into a complex<int32_t>. When you do the multiplication yourself, the 16 bit values are fi...
64,339,378
64,340,832
Picking with a physics library (OPENGL & BULLET 3D
I'm trying to use bullet physics to draw a ray to hit a game object in the scene so I can select it, i am using the camera matrix to draw a ray and then pick an object in space and then look through a list of game objects and look for the same location. On Mouse press I have the following code, it seems to be off and o...
This check SceneManagement::getInstance()->gObjects.at(i)->transform.Position.x == position.getOrigin().getX() && SceneManagement::getInstance()->gObjects.at(i)->transform.Position.y == position.getOrigin().getY() && SceneManagement::getInstance()->gObjects.at(i)->transform.Position.z == position.getOrigin().getZ() fa...
64,339,391
64,340,066
VS Code and wxWidgets: fatal error: wx/wx.h: No such file or directory
I built wxWidgets without any errors with make and did make install and now I have the installation in /usr/local/include/wx-3.1/. Both wx/wx.h and wx/setup.h are present in that folder. I'm using the latest VS Code with the latest Ubuntu 20.04. c_cpp_properties.json file: "configurations": [ { "name": "L...
in addition you will need to point the linker to the libraries to use with the -L option and use -l (lowercase L) with every library you will need. Example: -L/usr/local/lib -lwxcore-3.1 -lwxbase-3.1 Check the library names there and use them without lib prefix. Better yet - try to run wx-config --libs and use the outp...
64,339,498
64,339,879
VS 19 - When I initialize a variable it suddenly 'reformats' it, how do I turn it off?
When I type something like: int some_int{3}; VS Immediately changes it to: int some_int{ 3 }; I don't like how that looks and honestly I just want for it to stay the way I've written it in most cases, although I do appreciate the help when it comes to style guides that are best to follow (since I'm still a beginner) ...
To change the formatting in Visual Studio, goto Tools → Options... → Text Editor → C/C++ → Formatting. There, you will see a variety of formatting options. For your issue, you specifically want to un-check the box at ... → Formatting → Spacing → Spacing for braces → Insert space within braces of uniform initialization ...
64,340,094
64,340,348
C++ fstream won't open a text file in windows
I've written a simple program, and I need to read some numbers from a file. vector<unsigned long> readFile() { ifstream dat("primes.txt", ios::in); vector<unsigned long> praSt; unsigned long i = 0; while (dat >> i) praSt.push_back(i); dat.close(); return praSt; } I need to read some primes from a text file and do c...
You can set the working directory for the Visual Studio in the project properties, Debugging tab. The default value is $(ProjectDir). It's a very dangerous practice to assume that the files you need are in the current working directory - it can change depending on how you start your program. You should either use a "we...
64,340,132
64,357,592
MSVC error C2280 (attempting to reference a deleted function) that works with all other compilers
The following code fails to compile with all recent versions of MSVC but succeeds with all recent versions of GCC and Clang: #include <vector> #include <memory> #include <list> using namespace std; struct A { int a; }; int main (int argc, char **argv) { vector<list<unique_ptr<A>>> v; v.emplace_back(); } Wit...
It looks like this is an example of a more general problem that was acknowledged by the primary implementer of the MSVC standard library in this r/cpp thread. The problem applies to all container<container<unique_ptr>> constructs, where the inner container is a node-based container (like list or map). He suggests an un...
64,340,168
64,340,294
Using variables to store custom functions in a class
I'm trying to make a class with some member variables that store or point to functions, or can be assigned a different behaviour which describe how to process other variables in the object. class C { int n; void *data; // buidData: It allocates and stores data using the data pointer avobe to be processed la...
Sounds like you are looking for std::function. You can assign default functions in the same way that you might assign default values to primitive members, but then override the functions in C's constructor if necessary. Alternatively, you could go with the classic OOP solution where C is a base class with default beha...
64,341,004
64,341,352
Verifying a pincode, ATM program
I'm writing a program that simulates an ATM and I'm having problems with the account arrays in the program. The account arrays hold the account number, pin code, and account balance. The very first function in the code allows the user to log in with their pin and account number, but I'm having issues comparing the user...
Here are some examples to get you started. Overload equality comparison class Account { //... public: bool operator==(const Account& a) const { if (accountNum != a.accountNum) return accountNum < a.accountNum; else { if (accountPin != a.accountPin) return accountPin ...
64,341,691
64,341,787
How to pass value to std::optional in a structure?
I am trying to use the std::optional as in the following code. #include <iostream> #include <optional> #include <string> struct Animal { std::string name; }; struct Person { std::string name; std::optional<Animal> pet; }; int main() { Person person; person.name = "John"; if (person.pet) ...
person.pet = "Bru" Your pet field isn't a string, it's an Animal, so you need to pass an Animal instance to this. Try this instead: person.pet = Animal { "Bru" }; Or simply: person.pet = { "Bru" };
64,341,817
64,342,209
Suggestions that could improve my string splitting function
I'm new to C++ and I'm trying to write some basic functions to get the hang of some of it, I decided on making a custom function to split up a string into tokens every time a specific delimiter is reached. I've made it work successfully, but since I'm new, I'd like to hear from more experienced programmers on if there ...
Use std::string::find() to find separators in the string, which is probably much more efficient than your loop that checks for each possible position if the substring at that position matches the separator. Once you have that, you can make use of the fact that if the separator is not found, find() returns std::string::...
64,342,183
64,342,753
How can I read line by line and split every line to words ignoring white space and empty lines
I have a text like this: Eins zwei Polizei Drei vier Grenadier Fünf Sechs Alte Hex and I want to read every word using std::istringstream and in one row print out all the words, but for some reason some words get print out multiple times, can someone tell me why this happens and how should I do the above? My code...
The problem lies in this code: while(iss) { iss >> pom; // ... } After reading the last string from the stream, while(iss) still evaluates true, even though you can't read a string from it. So you enter the while loop, but iss >> pom fails. This leaves the last value of pom unchanged, and it gets printed out. Thi...
64,342,363
64,342,618
How to add a char* inside of a char*?
How do I add, for example, message, inside of this char*? add_message(char* message) { char* json = "{\"message\": \"%%insert message here%%\"}" } I'm really new to C++ and don't know any terms, so forgive me if this is too simple.
Just to concatenate the wisdom presented in the comments, and to ease the transition of the new C++ programmer, here is a tiny (and silly) sample code, #include <iostream> #include <string> std::string add_message(const std::string& body) { std::string json = "{\"message\": \"%%" + body + "%%\"}"; return jso...
64,343,024
64,343,025
Simple lex/yacc converter from pseudo C to pseudo assemlby language
Had to repeat question to provide answer I would like to make some kind of translator from mini C to NASM (assembly) using YACC/LEX (c++) Program should recive part of code and return file with that part in NASM assembly mini C should support code like this one a = v1; b = v2; while(condition){ // Some expressions ...
Because my last question was closed because someone though that I am writing book, I would like to share my solution to this problem. This problem was my homework. lexer.l %option noyywrap %option nounput %option noinput %{ #include <iostream> #include <cstdlib> using namespace std; #inc...
64,343,063
64,343,119
Why is virtual before declaration and override after?
This is a design question, let's have a simple method: virtual void Test() { }; We can override it the same way, or even not specifying virtual at all probably, but then there's this override keyword, which makes the compiler check it is actually overriding something, which is useful, but it needs to be written like t...
virtual was introduced right at the beginning of C++ as a keyword. This means you can't use it as a variable name, a class name, a function name, and so on. override came much later on. In order that its introduction in C++11 didn't break existing code, it doesn't quite attain the status of a keyword; rather it's calle...
64,343,299
64,343,364
C++: how does C++ know to destruct smart pointers inside containers?
In The C++ Programming Language, there is the following example (section 3.2.4). unique_ptr<Shape> read_shape(istream& is); void user() { vector<unique_ptr<Shape>> v; while (cin) v.push_back(read_shape(cin)); draw_all(v); // call draw() for each element rotate_all(v,45); // call rotate(...
Whether the unique_ptr is on the stack or the heap doesn't really matter. What matters is that it will automatically call delete on the target pointer when its destructor runs. When the vector goes out of scope, the vector's destructor runs. That destroys all contained elements (calling their destructors in the proce...
64,343,857
64,344,119
Wreorder How can I resolve this warning?
warning ? char.cpp warning how can i resolve this warning? Information message with warning; char.cpp: In constructor 'switch_channel_info::switch_channel_info()': char.cpp:7370:6: warning: 'switch_channel_info::secs' will be initialized after [-Wreorder] 7370 | int secs; | ^~~~ char.cpp:7369:22: warning: ...
In this section, when I replace the secs variable with the ch variable, the warning disappeared and the problem was solved. DynamicCharacterPtr ch; int secs; long newAddr; WORD newPort; I changed it as follows and the problem was solved. int secs; DynamicCharacterPtr ch; long newAddr; WORD newPort;
64,343,899
64,347,239
Transforming an array of int to integer_sequence
I would like to know if there is a way to transform a std::array into an index sequence? constexpr std::array<int, 5> x = {0, 3, 4, 5, 8}; constexpr auto integer_sequence = ...; // something that lead to integer_sequence<int, 0, 3, 4, 5, 8>; I know that it is impossible to use a function, because it will lead to anot...
While (in C++17) std::array<T> can't be a template parameter type, const std::array<T>& can be. Thus, with the restriction that the array in question have static storage duration, you can write #include<array> #include<utility> #include<type_traits> #include<cstddef> template<const auto &A, class=std::make_i...
64,343,917
64,344,192
Problem with const_iterator being called outside class
I have a classe called Nuage with the implementation: nuage.hpp using namespace std; template <typename T> class Nuage { private: vector<T> v; static vector<T>::const_iterator it; public: Nuage(); void ajouter(T); int size(); T& begin(); ~Nuage(); ...
It looks like you're trying to expose the iterators of the underlying vector with things like Nuage<T>::begin(). If that's the case, I would suggest public using declarations, as well as making sure begin has the appropriate return type: template <typename T> class Nuage { private: std::vector<T> v; ...
64,344,067
64,344,247
Why is std::set allowing me to insert repeated (non-unique) custom elements?
I need to create a collection of custom items that: Are ordered by priority Can't have repeated names. In this example, I am using std::set with an overloaded operator<( ).As far as I know, std::set uses the operator<( ) both for ordering and for uniqueness check. But my code is failing, as I am able to insert items ...
What am I doing wrong? Your comparison function fails to impose a strict weak ordering. That is a requirement of Compare concept that is a requirement of the standard set. Violating that requirement results in undefined behaviour. A strict weak ordering relation must transitive (For all x, y, z in S, if x < y and y <...
64,344,656
64,344,670
C++ bug uninitialized variable
I am instructed to write a program where the user inputs two values, can be with decimals. Then create a void function that changes the precision to 4 digits. I created a program and it runs the first value (x) just fine but for some reason, it's giving me an error saying the second variable is uninitialized (h) any ad...
This line: cin >> x, h; is not reading in 2 values from cin. It's actually only reading in 1 value, after which the expression h that's after the , is evaluated (which does nothing). So the warning/error about h being uninitialized is correct. The correct way to read 2 values is: cin >> x >> h;
64,344,999
64,345,385
How to change the default language standard for all projects in Visual Studio. C++
I am still learning the language, and I cannot seem to find an easy explanation here or otherwise how to change the default language standard in Visual Studio for all projects. Is there an easy way to change the C++ Language Standard so that when creating new projects, it defaults to that standard? I would think that t...
I believe there's a way to create templates, similar to like "console project" etc, that you could control this in, something like templates – Tas
64,345,016
64,345,058
Returning a vector from a function
So I wrote a class in a header file called: main.h and I want to return the vector after calling the function. So here is the code for the header file: //main.h #include <iostream> #include <vector> #include <string> template <typename T1> class LSR { public: std::vector<T1> arr; LSR(std::vector<...
replace() can't return the entire arr. For one thing, the syntax you are using is wrong, return std::vector<T1> arr; would need to be return arr; instead. But replace() returns a T1, and arr is not a T1 but a std::vector<T1> instead, so return'ing arr won't work. In any case, there is no need to have replace() return...
64,345,329
64,347,566
Are default arguments of object type constructed every time they aren't specified?
I've seen some code where there is a method with some default arguments which are of object type and it got me wondering what happens when the default arguments aren't specified by a caller. In "The C++ Programming Language" Stroustrup says this: A default argument is type checked at the time of the function declarati...
Yes. #include <iostream> struct Object { Object(bool expensive = true) { if (expensive) { std::cout << "Oh, I am so expensive!" << std::endl; } else { std::cout << "Ah, this was cheap." << std::endl; } } }; void foo(Object o = {}) {} int main() { foo(Object(true)); foo(Object(false));...
64,345,419
64,345,493
C++ evaluating an expression it shouldn't
I have overidden the operator| to act as a filter for a given vector and a function, if this function returns a bool. In case it doesn't, it calls for_each on the vector. template<typename T, typename Func> auto operator | (const vector<T> &v, Func f){ bool result = is_same<bool, decltype(f(v[0]))>::value; vector<T...
This lambda: [] ( int x ) { cout << x << " "; } has a void return type, so this line: bool func_return = f(*itr); doesn't compile. Since the value of result depends only on Func and T, you have the necessary information to decide whether to execute the if branch at compile time. You can use a constexpr if instead of ...
64,345,442
64,347,452
CUDA C++ class is mistaken for template
I define a class. I want to add some texture with my ray-tracing code with CUDA. And I use new when call the constructor. #ifndef TEXTURE_H #define TEXTURE_H #include "RTnextweek.h" #include "vec3.h" class texture { public: __device__ virtual vec3 value(float u, float v, const vec3 &p) const = 0; }; class const_...
Although it is not well documented, texture is a templated class for the C++ runtime API (for example here). It is defined in an internal header which is automagically included by nvcc during its pre-processing stage. If you rename your texture type to something else, the problem will disappear. For example: typedef fl...
64,345,473
64,345,524
Is there a better way to invert the value of a boolean on a loop?
I have this loop here that alternates a boolean. Here is what I mean: bool switch = false; while(true) { switch = !switch; std::cout << switch << std::endl; } Every time this code loops, the boolean named switch will alternate between true and false. Something like: bool switch = false; while(true) { std...
std::cout << (switch = !switch) << std::endl; Or std::cout << !switch << std::endl << switch << std::endl;
64,345,949
64,346,673
What lock-free primitives do people actually use to do lock-free audio processing in c++?
Anyone who has done a bit of low level audio programming has been cautioned about locking the audio thread. Here's a nice article on the subject. But it's very unclear to me how to actually go about making a multithreaded audio processing application in c++ while strictly following this rule and ensuring thread safety....
I've heard that it most cases it isn't. You heard wrong. std::atomic<bool> is lock_free on all "normal" C++ implementations, e.g. for ARM, x86, PowerPC, etc. Use it if atomic_flag's restrictive API sucks too much. Or std::atomic<int>, also pretty universally lock_free on targets that have lock-free anything. (The o...
64,346,031
64,347,463
How to connect Qt signals and slots using QT Designer and Visual Studio
I am using Qt Designer for the design of my application which contains a "Load File" QPushButton (which has been promoted to a custom loadfile.h) as well as an QOpenGLWidget (which has been promoted to a custom OGLWidget.h). I wanted to have it so that when I click my "Load File" button it sends a signal to a slot in m...
you have to connect them manually.. connect(ui->button, &QPushButton::clicked, yourGlPointer, &OGLWidget::populate_mesh_from_obj);
64,346,184
64,347,623
C++| BST reference-to-node-pointer vs. a node-pointer
Suppose I have this BST template: template <typename T> class Node { private: public: T data; Node *left; Node *right; Node(T dt) : data{dt}, left{nullptr}, right{nullptr} {} ~Node() { this->data = 0; this->left = nullptr; this->right = nullptr; } }; template <typename T> class BST { private: ...
OPs issue is about call-by-value vs. call-by-reference. The language C (the “anchestor” of C++) provides exclusively call-by-value. The missing call-by-reference can be mimed by using the address of a variable instead of the variable itself. (Of course, the parameter of the resp. function has to become a pointer-to-typ...
64,346,487
64,346,502
C++ “undefined reference to“ in main method
It looks basic and it’s probably due to a beginner mistake but I can’t figure out why... When compiling I get an error like below from int main(): “undefined reference to 'Hello::World::PaintService::PaintService()" paint.cpp using namespace Hello; int main(int argc, char **argv) { World::PaintService service; ...
To declare a method, you need to include the name of the class. namespace Hello { namespace World { void PaintService::start_painting(....) { ... } void PaintService::PaintService() { ... } } // namespace World } // namespace Hello https://repl.it/repls/PunySaneSpools#main.cpp
64,346,715
64,361,428
Cannot cross-compile for arm with c++17
I am trying to cross-compile c++14/c++17 code for my raspberry pi. I am sure it worked on my old PC. However, when I try to compile it on my new pc, it returns me the following error. $ arm-linux-gnueabihf-g++ main.cpp -std=c++17 arm-linux-gnueabihf-g++: error: unrecognized command line option ‘-std=c++17’ I t...
I found the easiest way to solve this issue is to directly install the newest cross-compiler sudo apt-get install g++-9-arm-linux-gnueabihf and use the compiler as (just an example of using c++17) arm-linux-gnueabihf-g++-9 main.cpp -std=c++17
64,346,765
64,346,836
Write a program that takes in a line of text as input, and outputs that line of text in reverse. C++
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text. Ex: If the input is: Hello there Hey quit Then the output is: ereht olleH yeH I tried this, but for some reason, it is giving me ...
Your input statement cin >> userInput; happens only at the end of your main. Try moving it at the start of your main. Read this C++ reference website. Consider reading the C++11 standard n3337. Read first some good C++ programming book, the documentation of your C++ compiler (e.g. GCC, invoked as g++ -Wall -Wextra -g)...
64,347,010
64,347,223
Why is clang dereferencing a parameter on every use?
I have been performing performance optimisations on some code at work, and stumbled upon some strange behaviour, which I've boiled down to the simple snippet of C++ code below: #include <stdint.h> void Foo(uint8_t*& out) { out[0] = 1; out[1] = 2; out[2] = 3; out[3] = 4; } I then compile it with clang ...
The compiler cannot do such optimization simply due to strict aliasing as uint8_t is always* defined as unsigned char. Therefore it can point to any memory location, which means it can also point to itself and because you pass it as a reference, the writes can have side-effects inside the function. Here is obscure, yet...
64,347,640
64,347,670
ANTLR4 CPP14 Grammar not able to identify decimal numbers
I am using the below ANTLR grammar for parsing my code. https://github.com/antlr/grammars-v4/tree/master/cpp The following code gives error while parsing. Here "08" is not identifying as an integer literal. TEST_F(suite_name_test_p, 08) { //... } I have made the following changes to fix this error: Decimalliteral ...
Integers starting with 0 are in octal, base 8, hence are allowed only the digits 0-7, every digit representing 3 bits. So in your case 08 contains an illegal digit, 8. As you seem to be aware of this, but may be want to remove octal numbers altogether from a non-C++ compliant grammar: I did not read the grammar, but s...
64,347,824
64,347,917
string is not printing in c++ outside the a for loop
I've tried to separate A-Z character in a given string using c++ but the separated string is not printing in the output but if I shift the "cout" statement inside the for loop it printing the characters. I don't know why its happen. please let me know if I've done any mistake. my code #include<iostream> using namespa...
String a is empty after initialization (i.e. it has length 0). So you can't access/write any character using a[j], because this writes beyound the string's current bounds and yields undefined behaviour. use... a.push_back(s[i]); to append a character at the end of the string.
64,348,149
64,348,598
Is there a better way to only run an action once on a loop?
I have a while loop here and I am running a method called "action" once when a key is pressed. I need to know if there is a less messy way of doing this. Here is my current code: bool actionRun = false; bool keyPress = someCodeForKeyPress; while(true) { if(keyPress) { if(!actionRun) { action();...
(I'm assuming the snippet you present is run whenever the key is pressed, and you don't really want the loop to run for ever.) There is a one-liner: std::call_once, and it's thread-safe too (your code is vulnerable to data races on the bool control variables): See https://en.cppreference.com/w/cpp/thread/call_once
64,348,676
64,348,780
How to get HWND with GLFWwindow pointer?
I have the pointer of a GLFWwindow(It is a struct defined in glfw3.h, seems to be a openGL struct?). How can I use the pointer to get the HWND?
GLFW has a section about native access there you can find this function that allows you to retrieve the HWND: HWND glfwGetWin32Window ( GLFWwindow * window): Returns The HWND of the specified window, or NULL if an error occurred. Thread safety This function may be called from any thread. Access is not synchronized. Si...
64,348,908
64,820,797
ChemPy: clang: error: unsupported option '-fopenmp'
I am trying to fix the following problem. When I was trying to run the following line in this ntb, I am getting: native = get_native(rsys, odesys, 'cvode') INFO:pyodesys.native._base:Cythonizing /Users/user/Library/Caches/python3.8-pyodesys-0.13.1/_cvode_wrapper.pyx to ./_cvode_wrapper.cpp INFO:pyodesys.native._base:I...
It took me a very long time, eventually there were two main issues which I think might be useful for others. ChemPy is only supported on Linux so even when I made my compilers working, I did not make it run on Mac nor on Windows. For more see this issue on Github. The compilers were a mess. At the end what worked was...
64,348,944
64,349,116
Java vs C++ speed on simple for loop
Why in simple for loop the same code in Java works 4 times faster than in C++? i.e. in Java this code completes in 700-800 ms and in C++ 4-5 SECONDS. Although C++ usually considered much faster than Java, especially with CPU-bound workloads. Have i lost sight of some important moment ??? Java: import java.time.Duration...
C++ can be fast when you turn on optimizations. The default is compiling without optimizations because compiling C++ takes time. You need to use the -O flag, -O2 should be ok. The loop you measure is a common pattern and has a direct solution: int sum = 0; for (int i=0;i < n; ++i) sum += i // this will give the same re...
64,349,383
64,470,971
How can I tell whether I'm forwarding to a copy constructor?
If I'm writing a generic function that forwards arguments to a constructor, is there a way to tell whether that is a copy constructor? Essentially I want to do: template <typename T, typename... Args> void CreateTAndDoSomething(Args&&... args) { // Special case: if this is copy construction, do something different. ...
You can use remove_cv_t: #include <type_traits> template <typename T, typename... Args> void CreateTAndDoSomething(Args&&... args) { // Special case: if this is copy construction, do something different. if constexpr (sizeof...(Args) == 1 && is_same_v<T&, remove_cv_t<Args...> >) { ... } // Otherwise do somethin...
64,349,477
64,349,801
How to save each string in a text file C++
I have a txt file, named mytext.txt, from which I want to read and save every line in C++. When I run the binary, I do ./file <mytext.txt I'd like to do something std::string line; while(std::getline(std::cin,line)){ //here I want to save each line I scan} but I have no clue on how to do that.
You can use a std::vector<string> to save the lines as so: ///your includes here #include <vector> std::vector<std::string> lines; std::string line; while(std::getline(std::cin,line)) lines.push_back(line);
64,349,490
64,352,583
Is there a way to serialize a heterogenous vector with nlohmann_json lib?
Hi Stack Overflow Community ! I am working on a project that heavily uses the interesting nlohmann_json library and it appears that I need to add an inheritance link on a specific class, which objects are serialized at one moment. I tried different advice found on the github Issues page of the library, but can't make i...
nlohmann.json does not include polymorphic serializing, but you can implement it yourself in a specialized adl_serializer. Here we're storing and checking an additional _type JSON field, used as a key to map to pairs of type-erased from/to functions for each derived type. namespace PolymorphicJsonSerializer_impl { ...
64,349,510
64,349,678
Adding two doubles in C++
I have a problem with summing two doubles double a = 1e+020; double b = -4000; double res = a + b; //result = 1e+020 Why res is equal to a?
double has not infinite number of significant digits. You can query number of digits in base 10 with std::numeric_limits: #include <iostream> #include <limits> int main(){ std::cout << std::numeric_limits<double>::digits10; } Typical output is 15 but you are requesting 16 significant digits.
64,349,552
64,355,797
Custom stack data structure error in c++?
I am implementing a custom stack class and I have a issue, my code shows this issue in a constructor part: error: qualified reference to 'Stack' is a constructor name rather than a type in this context Stack::Stack(int size) ^ lab5.cpp:182:18: error: expected '(' for function-style cast or type construction Stac...
I changed the type of arr from char* to int*, then the code can be built with Visual Studio 2019. class Stack { private: int* arr; int t; enum { stack_size = 100 }; int capacity; public: Stack(int size = stack_size); ~Stack(){}; void push(char){}; char pop() { return '0'; ...
64,350,571
64,350,705
if statement is not executing correctly
When i make the initial input age = 10, then the if-else statement should print out first "You are young" and then after age is incremented by 3, it should print out "You are teenager".However, it prints out "You are old" executing the wrong if-else statement.There would be a problem with my amIOld() function.The range...
The j loop runs three times. Each time through, it calls p.yearPasses(), which adds 3 to age. So the end age is 10 + 3 + 3 + 3 = 19, which is "old" according to p.amIOld().
64,350,747
64,552,406
How can we query the already create " LogGroup" and "StreamName" in cloudwatch with AWS SDK C++?
I am working on a project on which I need to query the "Log Group" and "Log Stream" to know that it is already present there or not using the language c++. Thanks in Advance.
During working on that I have found the answer for that is: when we create the "Log Group" and "Log Stream" using AWS SDK then at that time in the response we get error message with all the details and reason to not to created the "Log Group" and "Log Stream". So from the Error message we are able to get the message ...
64,350,816
70,015,400
Undefined reference errors in RTI DDS when using modern c++ API
I generated RTI code using: /opt/rti_connext_dds-6.0.0/bin/rtiddsgen -d GENERATED_CODE_DIR -language C++11 -replace IDL_DIR My CMake file: link_libraries(gsl gslcblas nnz12 occi clntsh dl nddsc nddscpp2 pthread) add_definitions(-DRTI -DRTI_64BIT -DRTI_LINUX -DRTI_UNIX -D_GLIBCXX_DEBUG) include_directories(-isystem /op...
The problem was due to the difference in ABIs of RTI libraries and the occi.so. Solved the problem by using occi_gcc53.so instead of occi.so library.
64,351,187
64,354,270
std::lower_bound on a set with its reverse order
Say I have a std::set<int> and I want to perform lower_bound(x) operations in both ways. That is, get the first element greater than or equal to x get the last element less than or equal to x With std::vector, I could do this using one sorted vector std::vector<int> v({1,2,3, 5,6}); sort(v.begin(), v.end()); auto a =...
Based on rustyx's answer, here is a bit more elegant implementation: using namespace std; template<typename T> typename set<T>::reverse_iterator rlower_bound(set<T>& s, const T x) { if(s.empty()) return s.rend(); auto it = s.upper_bound(x); return make_reverse_iterator(it); } template<typename T> typename se...
64,351,637
64,351,938
Issues with a char stack implementation in c++?
I want to make a char stack implementation, but i think something is wrong with it because when i try to use it for my other function it does not word and library stack works. Can you help to find an issue: using namespace std; Stack::Stack(int size) { arr = new char[size]; capacity = size; t = -1; } in...
I think you need to make some changes to the push and pop function for your Stack to work In push, you should put arr[++t]=x; outside the if statement instead of inside as you want to add value to arr if the current size is less than its capacity instead of when it is equal In pop, you should put arr[--t]; outside th...
64,351,659
64,352,089
Can't determine if two squares/rectangles are intersecting each other
As a online graphical I used: https://www.khanacademy.org/computer-programming/spin-off-of-rectx-y-width-height-radius/4975791745220608 The rectangle coordinates: rectangle 1: x: 180 y: 30 rectangle 2: x: 160 y: 30 What I noticed is that the render begins from a point and is increased on X axis by width and Y axis by h...
You're only checking if a is above above b, and then checking if a is left of b. You need to check if the x intervals of a and b overlap, and then check if the y intervals overlap. Here is a way of doing that: bool doOverlap(A a, B b) { if (a.x1 > b.x2 || b.x1 > a.x2) return false; if (a.y1 > b.y2 || b...
64,351,832
64,605,784
Issues caused in unrelated files when using #import to add msado28.tlb library
Im having issues adding the MS ADO type libraries into a large established MFC C++ project. Im using MS VS2015 for this project and the import directive im using is as follows: #import "C:\Program Files\Common Files\System\ado\msado28.tlb" rename_namespace("ADO_CG") rename("EOF","EndOfFile") Originally I made a blank t...
Solved this issue. Turns out it was an issue with #include ordering in the larger code base which was causing the import to be run mutiple times even from places like stdafk. After some re-organising its all working fine.
64,352,274
64,352,589
Object rvalue propagation for member function calls
I have a struct F with a function foo that has different implementation whether F is a temporary or not struct F{ void foo() & { std::cout << "F::foo() &" << std::endl; } void foo() && { std::cout << "F::foo() &&" << std::endl; } }; Another struct A has a copy of F and in its function bar calls F::foo. I want to...
You can use a non-member function template: struct B{ template<typename TB> friend void bar(TB&& self) { std::forward<TB>(self).f.foo(); } F f; }; Depending on other function parameters, you might want to restrict the type of TB such that is_base_of_v<B, remove_const_t<remove_reference_t<TB>>>.
64,352,614
64,353,985
Clock timing changes on different computers
I'm working on an implementation for the DMG-01 (A.K.A gameboy 1989) on my github. I've already implemented both the APU and the PPU, with (almost) perfect timing on my pc (and the pc of my friends). However, when I run the emulator on one of my friend's pc, it runs twice as fast as mine or the rest of my friends. The ...
I think you may be running into overflow under the hood of <chrono>. The expression: clock::now() + one_clock_period is problematic. clock is high_resolution_clock, and it is common for this to have nanoseconds resolution. one_clock_period has units of 1/4'194'304. The resultant expression will be a time_point with...
64,353,635
64,353,747
How to pass condition to function?
I want to reduce repeated code. Below is a snippet of code void f1(string arg) { std::map <string,string> topicAndClientIdMap; for(auto topicAndClientId : topicAndClientIdMap) { if(topicAndClientId.second == arg1) { //inset in other map } ...
You could pass a std::function, e.g. void f(const std::function<bool(string, string)>& doInclude) { for (const auto& [key, value] : topicAndClientIdMap) if (doInclude(key, value)) ; // do stuff... } which could be called as f([&arg](const auto&, const auto& value) { return value == arg; }); f(...
64,353,731
64,354,835
Defining multiple functions with the same name using custom types
I've been playing around with C++ and I've noticed something that I don't quite understand: typedef float degrees; typedef float radians; void my_func(degrees n); void my_func(radians m); Declaring a function like this, I get a warning that the function is re-declared as if they are identical. Does this mean, when lo...
Another possibility is to define Radian and Degree classes to have an explicit conversion from floats and an implicit conversion to them. class Radian{ float m_value; public: explicit Radian(float t_value) : m_value(t_value) { } operator float() const { return m_value; } }; class Degree{ float m_value;...
64,353,743
64,353,885
How can I use bitset in map?
I am trying to store 0 to 25 numbers along with its 5 bit representation using bitset. Here is the code : int main() { map<int, bitset<5> > myMap; myMap[0] = 00000; myMap[1] = 00001; myMap[2] = 00010; myMap[3] = 00011; // Like this I have stored 0 to 25 numbers. auto pos = myMap.find...
In this line: myMap[2] = 00010; The int literal is converted to a bitset. The octal literal 00010 is decimal 8, which prints the output 01000. Similarly, the literal 00011 is decimal 9, which prints 01001. You seem to want: myMap[0] = 0; myMap[1] = 1; myMap[2] = 2; myMap[3] = 3; // etc. // or simply for(int i = 0; i ...
64,354,456
64,355,095
How to dynamically allocate and deallocate a 2D array using pointers in c++?
I'd like to dynamically allocate and then deallocate a 2D array using pointers. My idea is to create a pointer to an array of pointers, where each pointer points to an int and that's how I would like to do it. The functions are type of bool as I want to return a boolean whether the action was successful or not. The pro...
When you need to pass reference or by pointer, when given the opportunity, it's better to pass by reference. A pointer can take null arguments, a reference can't, it's safer to use, unless, for some reason, you specifically need to pass null arguments which I believe is not the case. Note that you're accessing uniniti...
64,354,665
64,356,502
Regarding C++ Libraries Installation in Red Hat Linux WITHOUT INTERNET
I have been trying to install Codeblocks and C++ libraries in the Red Hat Linux. It's been 1 week that I am trying to find a way to install them, specifically OpenCV. Is there any way to install them without internet? If not, which are the best in-built libraries which can be used in C++?
Without having software packages/repositories installed (or built on your own from another computer that has internet access) or on a network fileshare/external harddrive no. The yum repos download their files through mirror URLs, where these package repositories are stored and require internet access to communicate to...
64,354,722
64,354,895
c++ doubly linked list error C2664 'object1::object1(object1 &&)': cannot convert argument 1 from 'int' to 'const object1 &'
As i mentioned before am trying to implement in c++ doubly linked list and i have an problem with add at Head function that pops this error whenever i try to add anything to this (tho there might be another errors in this program but for now i wanted to test at least adding an element), am c++ rookie kind of so yeah i ...
Pasting your code into Coliru (after removing the stray ` character and adding #includes) yields a more informative message: main.cpp: In instantiation of 'constexpr Node<object1>::Node()': main.cpp:63:25: required from 'void list<T>::addAtHead(T) [with T = object1]' main.cpp:147:20: required from here main.cpp:20:...
64,355,015
64,355,097
Diffrent typeid between platforms
I don't understand why this programs produces differents outputs between Linux and Windows using the same compiler. In Windows it outputs float and in Linux it outputs f. #include <typeinfo> #include <iostream> int main() { std::cout << typeid(float).name() << std::endl; return 0; }
The typeid operator returns the name from the std::type_info, which is described as The class type_info holds implementation-specific information about a type, including the name of the type and means to compare two types for equality or collating order. This is the class returned by the typeid operator. So it is imp...
64,355,467
64,356,013
Creating an X amount of rectangles which are not intersecting each other on a specified screen size
I managed with some help to know how when two rectangles are intersecting each other, from there it should be easy to make what i just said in the title but ... So, short story of what i just did below: Created a for loop from 1 to Number_of_Obstacles In that for an random obstacle (rectangle/square) is created and it ...
Restart selection when collision occurs, something like: bool Has_Overlap(const Obstacles& obj, const Obstacles* Objs, int Size) { B Rectangle_2; Rectangle_2.x1 = obs.X; Rectangle_2.x2 = obs.X + 40; Rectangle_2.y1 = obs.Y; Rectangle_2.y2 = obs.Y + 40; for (int i = 0; i != Size; ++i) { A ...
64,355,857
64,356,065
What should hash for a custom datatype return in C++?
I want to use a data type of mine in an unordered_set. It didn't work but this SO question helped to understand what I needed to do. This answer however confused me to what exactly I should put in the hash struct. Should my hash now return x.name.size() or rather x.hash? My data type: struct State { std::string name;...
The primary function of a hash function is to be a good proxy whether two objects are possibly the same or definitely different. If you return x.name.size(), State objects with the same amount of letters will have the same hash code. This will result in lots of collisions if you stick these objects in an unordered_set....
64,356,628
64,356,735
Const reference vs inline getter - C++
I have a class with a private field. This field is written only inside the class, but must be readable from outside. Which option is preferable and why? First, with const reference class Test { public: const int &field; // can read outside inline Test() noexcept: field(_field) {} void someMethod()...
There are a whole bunch of reasons to avoid the reference-typed data member: It bloats the object size All assignment operators default to deleted The default copy-constructor becomes wrong, tying the lifetime of the new copy to that of the copied-from object. The object is no longer standard-layout nor trivially copy...
64,356,896
64,357,903
c++ varargs/variadic function with two types of arguments that repeat together (alternating)
I can find examples of how to write variadic functions with one type that repeats like StringFormat() but I need to write one where two different types repeat alternating. The usage needs to look like this: MyFunc(stringVar, intVar1, doubleVar1); MyFunc(stringVar, intVar1, doubleVar1, intVar2, doubleVar2, intVar3, doub...
If I understand what you're trying to do, you can write the following function: template<typename ...Ts> void MyFunc(std::string Var, Ts ...ts) { // simple structure to store each pair of arguments struct Arg { int i; double d; }; // checks narrowing conversions, // and incorrect type/number of argum...
64,357,356
64,357,870
no crash if I reset the same shared_ptr in multi-threads
I just want to confirm it's safe to reset to the same smart pointer with lock in multi-threads? if there is no lock_guard, it's not safe due to it is not a thread-safe method? I suppose reset is not threadsafe, however, no crash is observed if I removed the lock. class foo { public: foo() { std::cout << "f...
The shared_ptr object is not thread-safe, nor is the pointed-to object. Only the reference count is thread-safe. So yes, you need to use a guard. In C++20, there is std::atomic<std::shared_ptr<T>>.
64,357,434
64,363,223
Is it scons don't support LDFLAGS?
I am new in scons. I am trying to build a program with gRPC by scons. I use grpc_lib = commands.getoutput('pkg-config --libs protobuf grpc++') to get LDFLAGS. The grpc_lib is a string -L/home/zty/.local/lib -lprotobuf -lpthread -lgrpc++ -labsl_raw_hash_set -labsl_hashtablez_sampler -labsl_exponential_biased -labsl_hash...
It's easier if you use mainEnv.ParseConfig, it can split out the results on running pkg-config directly into the correct construction variables. As to gRPC... there's at least some experimental work on the internet about using protobufs smoothly with scons. This is one of them, not sure if it's the "best" version or n...
64,357,468
64,390,139
Third party library throwing compilation errors when being included in project
I am trying to write a plugin for a program, and I am using protobuf for communication. I had to install the protobuf libraries from source, and this was done without any compilation errors. However, after I link and include the appropriate libraries and headers, respectively, I get errors coming from the protobuf head...
Thanks to everyone for your answers. The issue was that I had two installs of the library, and only one was working. So after removing the messed up one and fixing my cmake variables, I was able to compile my plugin.
64,357,943
64,358,203
I can't use spdlog loggers in a loop
I want to create log over a loop. Here is a simple exampe: #include <iostream> #include "logging.hpp" int main(int argc,char* argv[]){ for(int i=1; i<argc; i++) Logger l(argv[i]); return 0; } And this is logging.hpp file content : #include "spdlog/spdlog.h" #include "spdlog/sinks/std...
The very quick and dirty fix is to do: static auto console = spdlog::stdout_color_mt("console"); This will ensure there is only ever one instance, as the initializer is executed exactly once.
64,358,041
64,358,135
Link restbed with Cmake
In trying to link restbed with CMake I get the usual undefined function error. However, trying the exact same code linked with g++ test.cpp -o test -lrestbed works fine. Furthermore, when I first implemented the CMakeLists.txt it also worked fine and as I added to the project it started facing issues. Now even a single...
Do not use CMAKE_CXX_FLAGS, or rather use it as a "last resort" when configuring the build system as a user. Prefer to use object model in place of global variables. The modern cmake way would most probably be something along: cmake_minimum_required(VERSION 3.11) project(vcar-server) add_subdirectory(vcar-embedded) fin...
64,358,240
64,358,375
Program that does not compile without using namespace std;
I have a compiler error: g++ main.cpp -o exec -Wall -std=c++17 -Wextra -pedantic -O2 -Wshadow -fsanitize=undefined main.cpp: In instantiation of ‘std::__cxx11::string to_string(A) [with A = int; std::__cxx11::string = std::__cxx11::basic_string<char>]’: main.cpp:68:25: required from ‘void debug_out(Head, Tail ...) [w...
template <typename A> std::string to_string(A v) will match all types, not only containers which can be iterated. That includes to_string(13). The reason that it seems to work when you're using namespace std; is because then std::to_string for int arguments will be a better match and will be used instead of your flawed...
64,358,280
64,358,651
too many initializer values c++
Could someone explain why i'm getting the following compiler error: error: too many initializers for ‘std::array<std::array<State, 2>, 8> #include <iostream> #include <array> using namespace std; enum State { NONE, WHITE, BLACK }; int main() { array<array<State, 2>, 8> initial = { { State::NONE, State:...
You can either use a normal array like so : State ini[8][2] = { { State::NONE, State::NONE }, { State::WHITE, State::WHITE }, { State::NONE, State::NONE }, { State::NONE, State::NONE }, { State::NONE, State::NONE }, { State::NONE, State::NONE }, { State::BLACK, State::BLACK }, { State::NONE, State::NON...
64,358,359
64,613,790
libmodsecurity as a library to process my own web requests
Is it possible to use libmodsecurity as a library and process requests on my own? I was messing with the examples in the repo ModSecurity examples, but I cant figure out how to make it take my request. I tried with simple_example_using_c.c but with no success. Is anyone have idea if this is possible? #include <stdio.h>...
I think you have to understand how ModSecurity works. There are five phases of all transaction: parse request headers parse request body parse response headers parse response body make logs (and check transaction variables, eg. anomaly scores (in case of CRS)) (And plus the phase 0: process the connection itself.) In...
64,358,369
64,358,589
Does PHP only work with Apache, or can I make it work with my own c ++ server?
Does PHP only work with Apache, or can I make it work with my own c ++ server? For example, can I send a request from my c ++ program to php, so that php runs "file.php" and then returns the result to my c ++ program?
PHP is an interpreted language. Besides using it through Apache mod_php, it supports CGI and FastCGI calls setup. So you can either: call it's interpreter in CGI mode to execute a PHP script file; or run php-fpm server in the background then call it to run any PHP file with the FastCGI protocol. I believe multiple li...
64,358,400
64,358,500
I can compile the same c++ code on different linux?
I have a question about c ++, I am developing a server code in c ++ for linux systems, but a question arises, I am developing on a debian system since for convenience it is the one I like the most to work with, but a Once it is launched into production, it will be done in a centos, so the following question arises. Can...
As long as you don't use debian specific code it will compile just fine on centos.
64,358,444
64,358,726
Insert a node in BST with global root
struct node{ int data; struct node*left,*right; }; node* root; //global root node* getNode(int item) { node* new_node = new node; new_node->data = item; new_node->left=new_node->right=NULL; return new_node; } node* insert(node* localroot, int item) { if(localroot == NULL){ loca...
The way you wrote insert requires that it always returns the node it modified or created. This ensures that insert on a node that has no children sets the correct member (left or right). You can rewrite root to be purely imperative by passing in a reference to a pointer to be set: void insert(int item, node*& localroot...
64,358,454
64,359,183
Redirecting thread to another function
Here is what I started with, but I am getting an execute violation at some random address from a memory region I cannot view in the disassembly (Not from within the allocated page) // ThreadCallbackParameter = void* // ThreadCallback = void __stdcall (void*) // suspend thread SuspendThread(Thread->Handle); // get the ...
OpCode 0xE8 is the relative version of the x86 CALL instruction. You are passing it the absolute memory address of the callback function you want to jump into, but you need to instead give it a relative offset to that function, where that offset is relative to the instruction that follows the CALL instruction itself. ...
64,359,089
64,359,140
How does the glVertexAttribPointer stride parameter work?
How does the stride parameter of the glVertexAttribPointer function work? Lets say I have a buffer which is 64 bytes large. I want to store 2 vertices which are 32 bytes large each. If the vertices start one after another, does the stride parameter need to be 0 or 32? What I'm trying to say is does the stride parameter...
It counts from the start of the previous vertex. But stride == 0 is a special case, it means that your attributes are tightly packed. So e.g. if you're passing a dvec4 (vector of 4 doubles) per vertex, it doesn't matter if you use 0 or 32 (if sizeof(double) * 4 == 32).
64,359,537
64,359,754
Power set code showing segmentation fault
A recursive code to find power set of string is showing error and out of memory. void recur(string a,string b,int i=0) // Recursive fun { int n=a.size(); if(i==n) //returns if becomes equal to the size of array { cout<<b<<endl; return ; } recur(a,b,i++); //calls without append recur(a,b+a...
i++ doesn't do what you want it to do in this context, it increments the variable i and returns the value before the increment. For example int i = 0; cout << i++; // prints 0 cout << i; // prints 1 You could use pre-increment like ++i, which evaluates to the value after the increment. Also for recur(a, b + a[i], +...
64,359,577
64,359,919
problem with SIGNAL SLOT new notation for QAbstractButton
I am writing a small utility composed by : 1) 4 QToolBar 2) 1 QToolBox 3) 1 QMenu 4) 1 QGraphicsView I have some buttons on the QToolBox, each button represents a grid with different spacing. Everytime a user clicks a button on the QToolBox the spacing on the QGraphicsScene` changes. I use daily the new notation and ne...
You have the following errors: QButtonGroup does not have the clicked signal but buttonClicked. You must not use (). The syntax in general is: obj, & Class_of_obj, in your case backgroundButtonGroup is QButtonGroup and this is MainWindow so preliminarily the syntax is: QObject::connect(backgroundButtonGroup, &QButton...
64,360,092
64,362,600
how to accessing/Updating a map in some header file from another file/class
I have a few classes and would like to access/update a map in one of the classes. I am a novice to c++ and am having a hard time to figure out how to achieve this... Basically, it's adding the work (here it's just a string, but it's actually like I am creating an object using the data from the string (like tokenizing) ...
A possible solution (untested code). In PaintService add void Add(string key, string value) { d_frames[key] = value; } In the call to start_painting add a reference to the owning instance. PaintDistributer paint_distributer(*this); // constructor needs a reference owner And in distribute add if (work_type == "frami...
64,360,136
64,360,170
How to convert char to wchar_t*?
As the title states I have a simple char that retrieves a full path name of a file I am looking for and I need to convert it to const wchar_t. How can I achieve this? Here is an example of the code: int main() { char filename[] = "poc.png"; char fullFilename[MAX_PATH]; GetFullPathName(filename, MAX_PATH, fu...
Your code doesn't show any need to convert between char and wchar_t. Most likely you don't actually need to convert the character types. If you want to use the wchar_t-friendly GetFullPathNameW, then just use wchar_t instead of char. int main() { wchar_t fullFilename[MAX_PATH]; GetFullPathNameW(L"poc.png", MAX_...
64,360,160
64,360,287
What does Clang-Tidy "suppressed X warnings" mean?
Here's my scan command (using .clang-tidy config): clang-tidy <source_file> -- <a_bunch_of_include_files> <a_bunch_of_libraries> I see the output for the source code, which is fine. At the very bottom I see: Suppressed 30000 (30000 in non-user code). warnings The source code uses multiple headers, and the source file...
What does Clang-Tidy “suppressed X warnings” mean? It means that there were X warnings that weren't shown because those warnings were produced from non-user sources. Does clang-tidy scan the include files Yes. Clang-tidy pre-processes the source, and operates on the processed source which thus includes all the code...
64,360,280
64,360,859
C++ Visual Studio Windows: how to declare but not define extern function in dll
I have a project that is compiled into a library and declares a certain function to be implemented by the user of the library: //To be defined by user Application* CreateApplication(); When compiling the code into a shared library on Linux this works perfectly. Any user of the library can define an implementation for ...
What you are attempting to do only works in a static library, it cannot work in a dynamic library like a DLL. For that, you will have to change the code to use a function pointer instead. The application that is using the DLL can pass in the address of the desired function from its own code, and the DLL can then assi...
64,360,496
64,360,787
Output window shows thrown exceptions
So I am working on exception handling and I used a try-catch to solve an issue with converting strings to integers. The project runs fine, but if I look in the output window, multiple messages like this one show up: Exception thrown at 0x00007FFB7ACE3B29 in CPP-eindopdracht.exe: Microsoft C++ exception: std::invalid_a...
Your exception handling is working properly. From my tests, it looks like the Debug Output window in Visual Studio always shows the exceptions.
64,361,793
64,363,382
Is clang wrong, gcc wrong, or both wrong in this case - casting away constness with member pointers
In C++, the concept of casting away constness is rigorously defined by the standard. Casts such as static_cast and reinterpret_cast are not allowed to cast away constness in the explicit conversion. The definition of casting away constness heavily relies on the qualification conversion definition, which says that two t...
I had a discussion with Richard Smith (the creator of clang) and I reached the conclusion that all three cases should fail to compile if we pass in -pedantic and that MSVC indeed is the one with the error. This is because there exists a single cv-decomposition in each of the examples in which reinterpret_cast<> would c...
64,362,100
64,362,154
Invalid Comparator with object sorting
I've overloaded the std::greater_equal<>() operator so it sorts my objects by a specific member in the struct. bool operator >= (const Copys& c) const { return (relevence >= c.relevence); } (Did I even do that right?) And it's just hitting me with the Invalid Comparator every time. It worked once, then I ran it a...
std::sort requires a strict weak ordering, where one of the requirements is compare(x, x) == false (No element is ordered-before itself). That is not satisfied since std::greater_equal<Copys>()(x, x) == true for all x. You probably want std::greater<Copys>() (And an operator>)
64,362,123
64,362,492
multi array: find the sum of all numbers under minor diagonal
I cannot find a way to sum all the numbers that are under antidiagonal. (Right top to left bottom) 1 1 0 1 0 2 0 2 2 Here is an example of an array, I want to find the sum of all the numbers 2, but unfortunately I can't think of how. At the moment I can find sum the numbers 1. How to find the sum of numbers 2. Regardl...
From your example, you may notice that for every i, you have to sum from j = last 1 to j = last i. 1 1 0 <-- i=0: nothing 1 0 2 <-- i=1: j = last 1 0 2 2 <-- i=2: j = last 1, last 2 If you didn't, try to use more examples to help understanding: 1 1 1 0 <-- i=0: nothing 1 1 0 2 <-- i=1: j = last 1 1 0 2 2 <-- i=2: j = ...