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
70,117,628
70,117,678
How to pass array of arrays to a template class with non-type parameters
I would assume the below code would work to initialize the Matrix class, but for Matrix C I get the following: error C2440: 'initializing': cannot convert from 'initializer list' to 'Math::Linear::Matrix<int,2,2>' template<class T, unsigned int Rows, unsigned int Cols> class Matrix { pub...
To use initializer list initialization, you need one more { }. std::array<std::array<int, 2>, 2> A = {{ {{1,1}} , {{1,1}} }} ; Matrix<int, 2, 2> C = { {{ {{1,1}} , {{1,1}} }} };
70,117,629
70,123,392
is_base_of SFINAE toggle on class
I'm working on a template toolkit for declarative UI building. I have the templates compiling on Windows as expected but the GCC/clang compilers are taking issue with my SFINAE work. I'm using Qt as the base, and I'm hoping to include QLayout and QWidget items in the wrapper structure while toggling on/off functions of...
In your example, the behavior of style function body is not dependent on its template parameters and a compiler can check the correctness. I guess this is allowed by the standard in [temp.res#general]: The program is ill-formed, no diagnostic required, if: ... — a hypothetical instantiation of a template immediately...
70,117,664
70,117,810
How to Link .csv Files With the Release version of my Qt App?
My Qt Project uses .csv(not my choice) files to save and load data from ,as i am looking to deploy the app , how do i add these files into the release version and what changes to my code should i do ? right now i am using QFile and giving it the full path to each file like so : QFile Fich1("C:/Users/ahmed/Desktop/MyWor...
If you're looking to ship CSV files as part of your application, one good way to do it is to use Qt's resource-file system; then they will be compiled into your app so there's no chance of them getting lost/modified/moved. OTOH if you want to ship CSV files with your app but as separate files (e.g. so that the user can...
70,117,724
70,117,766
When deleting array: "Process returned -1073740940 (0xC0000374)" Only with certain numbers
The program returns the user N number of odd squares starting from 1. From numbers 5-10 and then 20, (I didn't go further) when deleting array A it crashes with the error message: "Process returned -1073740940 (0xC0000374)". Which is apparently a memory violation? #include <iostream> using namespace std; int main(){ ...
From the NTSTATUS reference: 0xC0000374 STATUS_HEAP_CORRUPTION - A heap has been corrupted You appear to access A (a heap allocated object) out of bounds - A[0] through A[size-1] are valid elements to access but counter goes as high as 2*size. Any attempts to write to values past A[size-1] can corrupt the heap leadin...
70,117,922
70,118,293
Passing a C-style array to `span<T>`
C++20 introduced std::span, which is a view-like object that can take in a continuous sequence, such as a C-style array, std::array, and std::vector. A common problem with a C-style array is it will decay to a pointer when passing to a function. Such a problem can be solved by using std::span: size_t size(std::span<int...
The question is not why this fails for int[], but why it works for all the other types! Unfortunately, you have fallen prey to ADL which is actually calling std::size instead of the size function you have written. This is because all overloads of your function fail, and so it looks in the namespace of the first argumen...
70,118,298
70,118,341
Does cout treat bool as integer or integer as bool?
Why does this program int a = 8; cout << a && true ; cout << typeid(a && true).name(); output 8bool Frankly, I expected "truebool" or "8int". Is operator << of cout object involved in this or is it a precedence issue? Does it convert true to 1 as in the case when we cout << true;? typeid(a && true) gives us bool, t...
Indeed it is an operator precedence issue. << has a higher precedence than &&. One shorthand trick you can use to interpret an integer value to bool is to double-NOT it: cout << !!a; This is a matter of style, which may be divisive within the C++ community. So, if you don't want to be controversial, then the followi...
70,118,823
70,128,134
format wstring with fmt fails: no matching function for call to 'format(const wchar_t [17], int)'
I am using fmt 8.0.1 with code blocks 20.03 and gcc 8.1.0 in windows 10, and when trying to compile this code #include <fmt/format.h> int main(){ std::wstring a = fmt::format(L"The answer is {}", 42); } I get the following errors main.cpp: In function 'int main()': main.cpp:4:57: error: no matching function for c...
Per documentation you should include fmt/xchar.h for wchar_t support: #include <fmt/xchar.h> int main() { std::wstring a = fmt::format(L"The answer is {}", 42); } godbolt
70,119,353
70,119,374
Please explain the significance of []() in C++
I am building some HTML forms handlers using ESP32 in Arduino. In a lot of tutorials I see something like the following... update_server.on("/", HTTP_GET, []() { blah; blah; }); And here is another.. update_server.on("/update", HTTP_POST, []() { blah; blah; }, []() { more blah; etc... }); Ca...
Those are lambda functions. They are functions without a name basically. You can read more about it here: https://www.tutorialspoint.com/lambda-expression-in-cplusplus
70,119,551
70,119,561
Problem accessing member of struct inside a class
I am making a battleship board game in c++ and have issues accessing the struct that I have declated inside one of my classes. class Ship { typedef struct { int x; int y; }Start; typedef struct { int x; int y; }End; bool isAfloat; Start _start; End _end; ...
You need to initialize the whole object directly, not their members separately. E.g. Ship::Ship(int start_x, int start_y, int end_x, int end_y): isAfloat ( ...true_or_false... ), // better to initialize it too _start {start_x, start_y}, _end {end_x, end_y} {} BTW: Since C++20 you can use designated in...
70,120,158
70,124,104
Mongocxx accessing Error from different cpp file
I have created a header mongo.h it contain mongocxx::instance inst{}; mongocxx::uri uri{ "link*****" }; mongocxx::client client{ uri }; i accessed the mongodb from main.cpp by including this mongo.h but when including this header to other cpp file it return error. Documents saying that the instance must create once . ...
This is a good example of where a singleton could help. In mongo.h, put a single function declaration: mongocxx::client& get_client(); In a single cpp file, define the function as follows: mongocxx::instance inst{}; mongocxx::client& get_client() { static mongocxx::client client{mongocxx::uri{ "link*****" };}; ret...
70,120,165
70,122,996
In the constructor of WebRTC VideoSendStreamParameters, why is the config argument not passed by a reference?
In the constructor of WebRTC VideoSendStreamParameters, config argument is passed by a value(thus introducing a copy overhead), but options argument is passed by a reference. Also the config member is initialized by std::move(config). I want to know why they designed like this. The followings are scraped from Chromium ...
Because the config is modified during the lifetime of the stream. Already in the stream constructor you have: parameters_.config.rtp.max_packet_size = std::min<size_t>(parameters_.config.rtp.max_packet_size, kVideoMtu); And in SetSendParameters, for example: parameters_.config.rtp.rtcp_mode = *params.rtcp_mode; W...
70,120,176
70,122,584
Weird character when displaying data from .dat file in c++
I have an ipk.dat file containing student name and their GPA separated by semicolon. I'm trying to display the names of students who have a GPA greater than 3, but I get output with strange characters like this in the console. Hidayat Sari 3.60 Susila Buana 3.27 Krisna Sari 3.66 ...
The non-breaking space might be unwanted input, but if you have names with non-ASCII characters, you will have the same problem. Part of the problem here is that your terminal doesn't know that you are sending UTF-8 encoded characters. If you are on Windows you can refer to this question. The basic idea is to set the t...
70,120,733
70,121,052
Show error in function if some other function has not run before it
I have two functions in C library that I am making. One is a setup function, other is a function that does some operations. I want the second operations function to print an error if the setup function has not run before it. What would be the best way to do this? Here is what I have in my mind, but I am not sure if tha...
#ifndef only checks whether this function was defined somewhere for the compiler and won't affect runtime. best way to do this is through use of a global variable that changes value once the setup function is executed. if you're defining these functions in classes you could use static data member and setup function
70,121,308
70,124,647
Sending msg from RSU to vehicles in veins
I'm trying to implement a small example in veins: the RSU broadcasts its own ID and other information, and the vehicle receives the RSU'S ID and records it. I have created a new msg file named BeaconRSU.msg, and the application layer's cc files of RSU and vehicle are shown below: //MyVeinsAppRSU.cc #include "veins/modu...
You seem to be running your simulation in "release" mode, not "debug" mode. While this will let your simulation run much faster, it omits a lot of sanity checks and prints only minimal information about what is happening in your simulation. For all of these reasons, it is highly recommended to only run a simulation in ...
70,121,565
70,121,652
Pointer to const object with emplace_back
I don't understand when we can use const variables/objects in collections (particularly with emplace). The below code works with const objects directly but not when using pointers to const objects. #include <list> class MyData { }; int main() { std::list<std::pair<int, MyData>> collection1{}; std::list<std::...
const MyData* can't be converted to MyData* implicitly. That means std::pair<int, MyData*> can't be constructed from {1, someDataPtr} while someDataPtr is a const MyData*. Under the same logic, MyData* p = someDataPtr; // fails MyData m = someData; // fine As the workaround, you can change someDataPtr to MyData*, ...
70,122,041
70,122,352
Check if a struct is empty
I have an old piece of code with a big struct that looks like this: typedef struct { long test1; char test2[10] … } teststruct; This struct gets initialized like this: memset(teststruct, 0, sizeof(teststruct0)); I must not change this code in any way. How do I efficiently check if the struct is empty, or has been ...
It sounds like what you want is to find out if this struct has any non-zero values. As you can see in the comments, there are a couple exceptions you may want to consider, but for the simple solution we can copy this previous answer. // Checks if all bytes in a teststruct are zero bool is_empty(teststruct *data) { ...
70,122,232
70,123,194
Change the display of integer output
I am trying to create a maze and robot with vector of vector. However, I also want to use bool to display the wall so the robot cannot walk through it. And my vector display with 0 and 1 only. I want to change from 0 to . without using char or changing any element in vector to another type. I remember there is a guy wh...
If you gave us some more context it would be easier for us to help you, but in theory you should be able to display a '.' or ' ' character conditionally based on the boolean value. For instance, if the bool you want to print is in the variable cellIsWall then printing the expression (cellIsWall ? '.' : ' ') will print ...
70,122,423
70,122,447
what is `typename...` syntax in C++ template?
Just found this piece of code in a Program(C++) file: template <typename blah, typename... Args> const <some-type> bof(<some-parameters>, Args&&... args) const { return breck(std::forward<Args>(args)...); } I am wondering: what is the three dots after the typename? Intuitively looks like in this way we can pass m...
It is called parameter pack, you can read more here: https://en.cppreference.com/w/cpp/language/parameter_pack Indeed, you can use Args... for unpacking multiple arguments in function or class templates, when you don't know ahead of time how many templated parameters there is going to be.
70,122,761
70,124,133
Catch2 compile error (no such file or directory)
I've already used Catch2 for testing sucessfully, but this time a problem occurred. I am pushing Catch2 submodule to me project (this is not a -v2.x branch) and include "../Catch2/src/catch2/catch_all.hpp" to my test files. The problem is that in catch_all.hpp all of the included .hpp files (like <catch2/benchmark/catc...
You are including test_main.cpp and test.cpp in mainApp. Which means that files in mainApp try to #include"Catch2/src/catch2/catch_all.hpp" without linking to the Catch2 library and includes. Remove the test files from the mainApp sources and try again.
70,122,920
70,123,113
Maximum allowed value of the precision format specifier in the {fmt} library
Consider the following snippet1 (which is testable here): #include <fmt/core.h> #include <iomanip> #include <iostream> #include <sstream> #include <string> // Let's see how many digits we can print void test(auto value, char const* fmt_str, auto std_manip, int precision) { std::ostringstream oss; oss << std_ma...
You're not far off, there is a hardcoded limit of 767 in the format-inl.h file (see here): // Limit precision to the maximum possible number of significant digits in // an IEEE754 double because we don't need to generate zeros. const int max_double_digits = 767; if (precision > max_double_digits) precision = max_double...
70,123,352
70,123,454
c++ Using class member as a parameter in constructor
I have a class where I need to use one of the members as a constructor parameter to initialize another const member of the same class. class A { private: M1Type m1; const M2Type m2; public: A(x) : m1(x), m2(m1){} }; is this a correct way to initialize m2? m1's construction is complete in the list initializati...
Yes, "m1's construction is complete" when it's used to initialize m2 and if an M2Type can be constructed from an M1Type, this is fine - but x needs a type in A(x). The order of initialization is the order in which you've defined the member variables in the class, not the order in which you use them in the member initia...
70,123,558
70,123,745
How to convert unsigned char to unsigned int in c++?
I have the following piece of code: const unsigned char *a = (const unsigned char *) input_items; input_items is basically the contents of a binary file. Now a[0] = 7, and i want to convert this value to unsigned int. But when I do the following: unsigned int b = (unsigned int) a[0]; and print both of these values, I...
I think I see the problem now: You print the value of the character as a character: unsigned char a = '7'; std::cout << a << '\n'; That will print the character '7', with the ASCII value 55. If you want to get the corresponding integer value for the digit character, you can rely on that all digit characters must be co...
70,123,672
70,123,981
Optimize estimating Pi function C++
I've wrote a program, that approximates Pi using the Monte-Carlo method. It is working fine, but I wonder if I can make it work better and faster, because when inserting something like ~n = 100000000 and bigger from that point, it takes some time to do the calculations and print the result. I've imagined how I could tr...
An obvious (small) speedup is to get rid of the square root operation. sqrt(x*x + y*y) is exactly smaller than 1, when x*x + y*y is also smaller than 1. So you can just write: double distance2 = x*x + y*y; if (distance2 <= 1) { ... } That might gain something, as computing the square root is an expensive operation...
70,123,742
70,123,780
My Quicksort does not sort the input array
I tried to write quicksort by myself and faced with problem that my algorithm doesn't work. This is my code: #include <iostream> #include <vector> using namespace std; void swap(int a, int b) { int tmp = a; a = b; b = tmp; } void qsort(vector <int> a, int first, int last) { int f = first, l = last; ...
You don't pass qsort the array you want to sort, you pass it the value of that array. It modifies the value that was passed to it, but that has no effect on the array. Imagine if you had this code: void foo(int a) { a = a + 1; } Do you think if I call this like this foo(4); that foo is somehow going to turn th...
70,124,023
70,124,056
In C++, is it good to pass a const long double by reference?
I am facing my colleague writing a function definition like this: typedef long double Real; void func(const Real& x, const Real &y); I know it is somewhat bad to use pass-by-ref for primitive types, but what about long double? Its length is 80 bits, longer than a pointer of 64 bits on a regular machine nowaday...
I'm hoping that your colleague has written it for another reason, that being that it stops any implicit conversions being made at the function calling site. It also prevents the parameter from being modified in the function body, which can help in the attainment of program stability, but that can be achieved by passing...
70,124,226
70,124,387
Reference list element then popping it, is it undefined behaviour?
I have this piece of code and I wonder if it is valid or can cause undefined behaviour: #include <list> #include <utility> void myFunction(std::list<std::pair<int, int>> foo) { while (foo.size()) { std::pair<int, int> const &bar = foo.front(); //work with bar foo.pop_front(); } } ...
So long as you don't attempt to use the bar reference after the foo.pop_front(); statement, then you won't get undefined behaviour, because that reference remains valid until the referred-to element is removed from the container. In your case, the pop appears to be the very last statement in the scope of the reference ...
70,125,011
70,125,077
Error: terminate called after throwing an instance of 'std::out_of_range
When I typed this code #include <iostream> #include <string> class binary { std::string s; public: void read(); void check_format(); }; void binary::read() { std::cout << "Enter a number\n"; std::cin >> s; } void binary ::check_format() { for (int i = 1; i <= s.length(); i++) { if ...
C++ strings indexes are zero-based. That means if a string has a size of n. its indexes are from 0 to n - 1. For example: #include <iostream> #include <string> int main() { std::string s {"Hello World!"} // s has a size of 12. std::cout << s.size() << '\n'; // as shown std::cout << s.at(0); << '\n' // prin...
70,125,640
70,125,752
Why does a for loop invoke a warning when using identical code?
I think that following two codes are identical. but upper one has C4715 "not all control paths return a value" problem and other doesn't. Why this warning happens? int func(int n){ for(int i=0; i<1; i++){ if(n == 0){ return 0; } else { return -1; } } } in...
The compiler is trying to be helpful, and failing. Pretend for a moment that the code inside the loop was just if (n == 0) return 0;. Clearly, when n is not 0, the loop will execute once and then execution will move on to the next statement after the loop. There's no return statement there, and that's what the compiler...
70,125,684
70,125,887
Static_cast and templated conversion function
I have a class that wraps some type and attaches a Dimension. It should be convertible to the underlying type, but only if Dim=0. The conversion operator should not be callable in other cases (so a static_assert in the function would not work for me). The following code works, if the enable_if-construction is deleted, ...
As I understand, you want: template <class T, int Dim> class Unit { public: explicit Unit(T const& value): _value(value) {} template <typename U, int D = Dim, std::enable_if_t<D == 0 && std::is_convertible_v<T, U>, int> = 0> operator U() { return _value; } private: T _value; }; Demo And ...
70,125,891
70,125,948
prevent multi-thread application from termination when one of its thread performs an illegal operation
Is it possible to prevent a multi-thread application from getting terminated when one of its thread performs an illegal operation like integer divide by zero operation. This is a sample code: #include <iostream> #include <thread> #include <chrono> void thread1() { std::this_thread::sleep_for(std::chrono::seconds(2...
No, in general that isn't possible; all threads in a process share the same memory space, which means that a fatal error in any one thread might have corrupted the data structures of anything else in the process, therefore the whole process is terminated. If you really need your program to be able to survive a fatal er...
70,126,043
70,126,400
Writing results to multiple txt files in C++
I have the following code: #include <fstream> #include <iostream> using namespace std; int main() { ofstream os; char fileName[] = "0.txt"; for(int i = '1'; i <= '5'; i++) { fileName[0] = i; os.open(fileName); os << "Hello" << "\n"; os.close(); } return 0; } The aim is to write my co...
I believe the reason you receive that warning is because you're attempting to assign two chars into one slot of the char array: fileName[0] = i; because when i = 10;, it's no longer a single character. #include <fstream> #include <iostream> #include <string>//I included string so that we can use std::to_string using ...
70,126,065
70,127,088
C++ OOP Abstract Class - Access violation writing location
I have an UserAcount class that has an abstract class ContBancar, and other class Banca which reads some users from a file (with method void Banca::citire_conturi()). When it reads the users, I get an error "Access violation writing location" in ContBancar at void setBal(double bal) { _balanta = bal; }. Thx for help ! ...
Based on available informationyou should fix your code like this: class UserAccount { ..... void setCodUs(std::string cod) { _cod_us = cod; setContBancar(); } void setContBal(double balanta) { if (!_cont) setContBancar(); // lazy initialization _cont->setBal(balanta); ...
70,126,172
70,127,386
Translating a function from Python to C++
Im struggling with a certain function in Python, it's nothing complicated but i need to "translate" it to C++ with very limited prior knowledge. def BuildCommandList(commands : list, filepath : str): commands.clear() try: file = open(filepath, 'r') except FileNotFoundError: return False ...
The natural equivalent to Python's len is std::size, or equivalently the size member of std::string. However you might prefer the empty member of std::string for your condition. You then need to split your string. This can be done with a std::stringstream and std::istream_iterator to construct a std::vector<std::string...
70,126,319
70,126,600
C++20 Member Initialization List Clang++ vs G++
Currently using Clang++ 13.0.0 and GCC G++ 11.2.0. The code below has been simplified for context. When I run the code using g++, it runs without any warnings or errors. When I run the code using Clang, I get the following error: field 'cat' is uninitialized when used here [-Werror,-Wuninitialized] Is there any way to ...
One possible approach: class Test { private: explicit Test(Object* ptr) : animal{ptr, {ptr, 0}} {} public: Test() : Test(generateObject()) {} };
70,126,350
70,134,444
OpenMP incredibly slow when another process is running
When trying to use OpenMP in a C++ application I ran into severe performance issues where the multi-threaded performance could be up to 1000x worse compared to single threaded. This only happens if at least one core is maxed out by another process. After some digging I could isolate the issue to a small example, I hope...
So here is what I could figure out: Run the program with OMP_DISPLAY_ENV=verbose (see https://www.openmp.org/spec-html/5.0/openmpch6.html for a list of environment variables) The verbose setting will show you OMP_WAIT_POLICY = 'PASSIVE' and GOMP_SPINCOUNT = '300000'. In other words, when a thread has to wait, it will s...
70,126,417
70,130,563
Z3: using comparison operators (<,<=,...) on z3::expr
I store numbers as z3::expr and want to compare them. I tried the following: z3::context c; z3::expr a = c.real_val("0"); z3::expr b = c.real_val("1"); z3::expr comp = (a < b); std::cout << comp.is_bool() << std::endl; std::cout << comp.bool_value() << std::endl; I am a bit confused, why is comp.bool_value() false? If...
The < operator (and pretty much all other operators) simply pushes the decision to the solver: That is, it is a symbolic-expression that does not "evaluate" while it runs, but rather creates the expression that will do the comparison when the solver is invoked, over arbitrary expressions. Having said that, you can use ...
70,126,442
70,126,537
Random syntax error on SQLite3 INSERT query
I'm doing an insertion query using SQLite3 with Spatialite on Qt and sometimes it just fails returning random syntax errors. If I run the queries on SpatialiteGUI it never fails. I'm using SQLite3 version 3.27.2. The method that builds and runs the query: bool DatabaseManager::insertPolygons(QList<QList<QGeoCoordinate>...
strQuery.toLatin1() is a temporary value, and .data() grabs a pointer within that value. This is effectively a dangling pointer. Add an intermediate holding variable: (and use UTF8 instead of Latin1 while you're at it) auto queryBA = strQuery.toUtf8(); int status = sqlite3_prepare_v2(database, queryBA.data(), queryBA.s...
70,126,517
70,126,965
Can't find qml module related to vlc
I cloned the vlc repository and I'm trying to modify the qt interface. I stumbled upon this file MainInterface.qml which has a particular line: import org.videolan.vlc 0.1 I can't help finding this module. I understood it's related to some other qmldir file but I don't understand where it might be. Qt Creator doesn't ...
the module is defined in on the C++ side, it contains type registration for various models and types used in the QML interface the module definition is here: https://code.videolan.org/videolan/vlc/-/blob/4955734f1c3559a2a1315fc674a1d094c04d9692/modules/gui/qt/maininterface/mainui.cpp#L173
70,126,690
70,161,818
Write binary file to disk super fast in MEX
I need to write a large array of data to disk as fast as possible. From MATLAB I can do that with fwrite: function writeBinaryFileMatlab(data) fid = fopen('file_matlab.bin', 'w'); fwrite(fid, data, class(data)); fclose(fid); end Now I have to do the same, but from a MEX file called by MATLAB. So I setup a ...
As indicated in some posts very large buffers tend to decrease performance. So the buffer is written to the file part by part. For me 8 MiB gives the best performance. void writeBinFilePartByPart(int16_t *int_data, size_t size) { size_t part = 8 * 1024 * 1024; size = size * sizeof(int16_t); char *data...
70,126,763
70,126,904
Change a bunch of numbers into corresponding alphabets
There are five types of bit encoding: 11, 10, 01, 001, 000.The corresponding message for each bit encoding is 11 -> A 10 -> B 01 -> C 001 -> D 000 -> E The compile result will look like this: Enter a sequence of bits: 01100001100110 CBEADB I've wrote this but it can't work. #include<iostream> #include<string> using na...
Your input is a String not numbers, therefore you have to check for characters. Instead of using something like == 0, you should be using something like == '0'. Also, you may want to make sure that the input has the right format and you don't run into an infinite loop (by running the while forever without updating i) o...
70,126,882
70,128,752
C++ header dependency propagation - how to limit it?
I have a repeating dilemma while constructing a class in C++. I'd like to construct the class without propagating its internal dependencies outside. I know I have options like: Use pimpl idiom Use forward declaration and only reference or smart pointers in header // header class Forwarded; // I don't want to incl...
The underlying issue is that the consumers of MyNewClass need to know how big it is (e.g. if it needs to be allocated on the stack), so all members need to be known to be able to correctly calculate the size. I'll not address the patterns you already described. There are a few more that could be helpful, depending on y...
70,127,129
70,133,868
What should I install to use namespace Windows::Devices in c++?
Now I am going to connect to device using bluetooth, so I have got some source code. It uses namespace Windows::Devices, but my visual studio gives me compile error. using namespace Windows::Devices; I guess I have to install some packages additionally, but I am not sure what I have to install. If anyone knows, please...
Since the question is tagged c++ I'm going to assume that that's the programming language you are using. The most convenient way to consume Windows Runtime types from C++ is through C++/WinRT. It consists of both a base library as well as a code generator. The code generator is responsible for providing the "projected ...
70,127,146
70,127,399
warning C5246: the initialization of a subobject should be wrapped in braces
The latest Visual Studio 2019 compiling the following code with /Wall command-line switch (which enables all warnings): struct A{}; void f( const std::array<A, 2> & ) {} int main() { A x, y; f( { x, y } ); } prints the warning: warning C5246: 'std::array<A,2>::_Elems': the initialization of a subobject shoul...
Visual Studio 2019 has the CWG defect #1270 and offers the old initialization behaviour. std::array is defined as an aggregate that contains another aggregate. C++ 17 Standard (11.6.1 Aggregates) 12 Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succe...
70,127,777
70,128,103
Creating unordered map in C++ for counting the pairs
So let's say I have an array, 1 2 1 2 3 4 2 1 and I want to store all the (arr[i], arr[i-1) such that arr[i] != arr[i-1] as a pair in unordered_map for counting these pairs. For e.g. (1, 2) -> 2 (2, 3) -> 1 (3, 4) -> 1 (4, 2) -> 1 (2, 1) -> 1 So the syntax I tried, unordered_map<pair<int, int>, int> umap; int temp;...
You can't just use unordered_map with a pair because there is no default hash implemented. You can however use map which should work fine for your purpose because pair does implement <. See Why can't I compile an unordered_map with a pair as key? when you really want unordered_map. You can construct pair with curly bra...
70,127,899
70,185,303
librdkafka custom logger, function signature
I'm using the librdkafka c++ API and I would like to change the default behavior of the logger. In the c API there is this function rd_kafka_conf_set_log_cb() to set the log callback. It takes a function with the signature: void(*)(const rd_kafka_t *rk, int level, const char *fac, const char *buf) However I can't figu...
The facility string is a semi-unique name for the context where the log is emitted. It is mainly there to help librdkafka maintainers identify the source of a log line, but can also be used for filtering purposes. It was originally inspired by Cisco IOS like system logs which came in the form of: FAC-LVL-SUBFAC: Messag...
70,128,344
70,128,443
Can multiple parameter packs be expanded in a single expression?
I want to get a matrix from two parameter packs like the following: template < typename T1, typename T2 > struct Multi{}; template < int ... n > struct N{}; void Print( int n ){ std::cout << n << std::endl; } template < int ... n1, int ... n2 > struct Multi< N<n1...>, N<n2...>> { Multi() { using...
No need to use the dummy arrays when you have fold expressions. The naive (Print(n1 * n2), ...); wouldn't work (it expects the packs to have the same size, and would print N numbers instead of N2). You need two nested fold expressions. In the inner one, you can prevent one of the packs from being expanded by passing it...
70,128,458
70,136,444
Using shared C++ library in Idris
I want to FFI to a third-party C++ library from Idris but I'm getting "undefined symbol". I'm new to C/C++ compilation. I'm doing this by wrapping the C++ in a pure C layer which I call from Idris. The C++ code is provided as a bunch of .h headers and a single .so shared library. At the moment I only have one C file, b...
This command: g++ -shared -Iinclude -Llib -lfoo_ext -o libfoo.so wrapper.cpp is incorrect. Assuming libfoo_ext is the 3rd party library which implements mynamespace::Foo::Foo(), the link command should be: g++ -shared -Iinclude -Llib -o libfoo.so wrapper.cpp -lfoo_ext The order of libraries and sources on the link l...
70,129,810
70,129,873
Is changing the std::string value through it's address is valid?
I was wondering if we can modify std::string value through a pointer to it. Please consider the following example. #include <iostream> void func(std::string *ptr) { *ptr = "modified_string_in_func"; } int main() { std::string str = "Original string"; func(&str); std::cout << "str = " << str << std::end...
That is legal. You are assigning a new value to the string but are using a pointer to refer to the original string; this is no more illegal then not using a pointer to refer to the original string i.e. std::string foo = "foo"; foo = "bar"; // is pretty much the same thing as std::string* foo_ptr = &foo; *foo_ptr = "b...
70,129,833
70,129,874
Cpp/C++ Assign Default value to default constructor
This seems like a really easy question but I can't find a working solution(maybe it is the rest of the code too). So basically how do you assign a value to an object created with the default constructor, when the custom constructor has that variable as a parameter? (hopefully this is understandable) Maybe clearer: The ...
This record foo ex2(); is not an object declaration of the class foo. It is a function declaration that has the return type foo and no parameters. You need to write foo ex2; or foo ( ex2 ); or foo ex2 {}; or foo ex2 = {};
70,129,964
70,133,294
Choosing collisions of hash functions
According to the condition of the problem, it is necessary to "break" the standard hash "gcc". It is necessary for the program to run for more than 1.5 seconds according to the input data. 15000 string with up to 15 characters 0-9A-Za-z_ is appended to unordered_set. If I understand correctly, it is necessary to choose...
In order to make the program slow, you'd need to find 15000 strings (15 chars or less) with an identical hash. That will degrade the performance of insertion on unordered_set to be equivalent to searching within a linked list for a duplicate and appending the new string at the end. If your code is running in the 32-bi...
70,130,300
70,134,389
Antlr4: Can't understand why breaking something out into a subrule doesn't work
I'm still new at Antlr4, and I have what is probably a really stupid problem. Here's a fragment from my .g4 file: assignStatement : VariableName '=' expression ';' ; expression : (value | VariableName) | bin_op='(' expression ')' | expression UNARY_PRE_OR_POST | (UNARY_PRE_OR_POST...
Do not use literal tokens inside parser rules (unless you know what you're doing). For the grammar: expression : '+' expression | ... ; ADD_SUB : '+' | '-' ; ANTLR will create a lexer rules for the literal '+', making the grammar really look like this: expression : T__0 expression |...
70,130,328
70,131,057
overflow when attempting to push_back randomly generated numbers in a vector
my code is shown here: #include <iostream> #include <vector> #include <string> #include <stdlib.h> using std::string; using std::endl; using std::cout; using std::cin; struct funcs { std::vector<int> values; int sum; void createVectorValues(){ while(values.size() < 100) { int x ...
You didn't define a constructor for funcs, so you get the default constructor, which invokes the default constructor of each member. This means the int member sum is left with an indeterminate value. See Does the default constructor initialize built-in types?. You probably want to write a constructor that initializ...
70,130,468
70,130,686
How can I create different types from uint32_t that are statically different?
I want to create different types that are uint32_t but are different from compilers perspective -- they can only be compared and assigned to a value of the exact same type. Here is a sample code that I want to achieve: TextureResourceId t1 = 1000, t2 = 2000; PipelineResourceId p1 = 1000, p2 = 2000; BufferResourceId b1 ...
Since you only seem to need to check identity, an enum should be the natural choice and as you mention, enum class can be used to ensure the underlying type is uint32_t: enum class TextureResourceId: uint32_t { id1 = 1000, id2 = 2000 }; enum class PipelineResource: uint32_t { id1 = 1000, id2 = 2000 }; ...
70,130,644
70,130,677
QTCreator 5.0.2, parallel run of two window, C++
I went throught suggested "questions" about my problem. However neither does not solve it. I program two windows. The second window is opening from first window. I need active the both windows, however to start the first window(MainWindow) I use: int main(int argc, char *argv[]) { QApplication a(argc, argv); ...
Graphics gr; defines a local variable, so the object is destructed as soon as it goes out of scope (at the end of your function). In Qt, the typical approach is to work with pointers to Qt widgets (and, more generally, QObjects), but have a parent for each – the parent will clean it up. Try this instead: auto gr = new ...
70,130,735
70,130,881
C++ concept to check for derived from template specialization
In this SO answer and this proposal we can see an implementation (included below for convenience) for std::is_specialization_of, which can detect if a type is a specialization of a given template. template< class T, template<class...> class Primary > struct is_specialization_of : std::false_type {}; template< template...
De-_Ugly-fied rom MSVCSTL: template <template <class...> class Template, class... Args> void derived_from_specialization_impl(const Template<Args...>&); template <class T, template <class...> class Template> concept derived_from_specialization_of = requires(const T& t) { derived_from_specialization_impl<Template>(...
70,130,786
70,130,814
How do I consicely express the templated dereferenced Iterator type as a template parameter
Lets say I'm rewriting std::min_element for c++17. https://en.cppreference.com/w/cpp/algorithm/min_element I'm unhappy with all the overloads. I'd very much like it if (1) and (3) could be expressed in terms of default arguments. So (3) could replace (1) with template< class ForwardIt, class Compare = typename std::les...
std::less<void> does work for any type, because its operator() is a template and the actual type to be compared is deduced when the operator is called. It was introduced in C++14.
70,130,824
70,131,242
With std::optional, what does it mean to "remove the move constructor from overload resolution"?
I'm creating an implementation of std::optional in C++14. However, I'm slightly confused with how the move constructor is specified. Here's what I'm referring to (emphasis mine): The expression inside noexcept is equivalent to is_nothrow_move_constructible_v<T>. This constructor shall not participate in overload resol...
Yes, SFINAE does not work for constructors, use base classes forcing the compiler to do the right thing. It means it is not defined and the class cannot be move constructed. More interesting question is why is it needed? I am not 100% sure I have the right answer to that. TL;DR Returning std::optional<NonMoveable> gene...
70,131,467
70,132,547
How to compute hash of std::weak_ptr?
So I have code that uses std::weak_ptr and maintains them in an std::set, and that works just fine -- and has worked for the last 5 or 7 years. Recently I thought I'd fiddle with using them in an std::unordered_set (well, actually in an f14::F14ValueSet) and for that, I would need a hash of it. As of now, there is no s...
Make your own augmented weak ptr. It stores a hash value, and supports == based off owner_before(). You must make these from shared_ptrs, as a weak ptr with no strong references cannot be hashed to match its owner; this could create two augmented weak ptrs that compare equal but hash differently. template<class T> stru...
70,131,609
70,131,961
OpenGL: glVertexAttribFormat.attribindex vs GLSL vertex shader location
Does the attribindex in glVertexAttribFormat correspond with the layout location in my GLSL vertex shader? i.e. if I write glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, offsetof(Vertex, position)); That 0 would correspond with this line in my shader? layout (location = 0) in vec3 inPos;
Yup. Otherwise without a location specifier you have to query the attribute location via glGetAttribLocation() after program linking or set it before program linking via glBindAttribLocation().
70,131,610
70,131,630
Can't display the entire string when translating CHAR to INT
In my intro class, I'm tasked with translating a phone number that may have letters in it, back to a pre-determined list of numbers (like 1-800-COLLECT would display as 1-800-2655328) and currently, I can translate the letters to numbers but for whatever reason, the non-letters in the phone numbers arent being translat...
This: if (original[i] < 0 || original[i] > 9) Is comparing against the ASCII codes 0 and 9, not the actual characters. It should be: if (original[i] < '0' || original[i] > '9')
70,131,705
70,131,744
OpenGL: What's the point of the "named" buffer functions if you have to bind a target anyway?
e.g. when I do glBindBuffer(GL_ARRAY_BUFFER, _id); glNamedBufferData(_id, size, data, static_cast<GLenum>(usage)); then program works as expected. But if I delete that first line, my program crashes and prints: ERROR 1282 in glNamedBufferData Likewise, if I do glBindVertexArray(_id); GLuint attribIndex = 0; GLuint ...
The glGen* functions create a integer name representing an object, but they don't create the object state itself (well, most of them don't). It is only when you bind those objects do they gain their state, and only after they have state can any function be called which requires them to have state. In particular, the di...
70,131,727
70,136,816
LLD undefined symbol when attempting to link glfw
I've been trying to get an LLVM toolchain setup on my Windows 10 machine. I gave up on building from source and have the MSYS2 mingw-w64-clang-x86_64-toolchain package installed (clang version 13.0.0). I can compile simple code that uses the C++ standard library. I'm using clang to compile, lld to link, and I should ...
Well, it seems I have a lot to learn about command line compiling/linking. I fixed it by adding -lgdi32 to the compile tags: clang++ -Iinclude\ -Llib\ -lglfw3 -lgdi32 -v .\main.cpp Got the idea from this thread: https://github.com/ziglang/zig/issues/3319 From the thread, near the bottom, there is some good advice: W...
70,132,122
70,140,174
Merge Sort on Doubly Linked List
How do I merge 2 given DLists without having to sort them first? My Sort function doesn't seem to work (it doesn't merge items) when I display on screen DoublyLinkedList MergeSort(DoublyLinkedList &ls1, DoublyLinkedList &ls2) { DoublyLinkedList ls; Initial(ls); if(isEmpty(ls1)) return ls2; if(is...
After consulting the comments I've fixed the function. Reusing QSort to sort the given lists DoublyLinkedList MergeSort(DoublyLinkedList &ls1, DoublyLinkedList &ls2) { DoublyLinkedList ls; Initial(ls); if(isEmpty(ls1)) return ls2; else if(isEmpty(ls2)) return ls1; QuickSort(ls1); ...
70,132,700
70,132,794
Is it possible that we can call the parent's class method through a child class in main method?
I have created a program in which there are two classes i.e., mother and daughter. Daughter class have inherited from mother class. Both classes has same method name but they print different data. Now in main method I have created an object of daughter class and called the display() through daughter's object and it is ...
You were very close. rita.mother::display(); https://ideone.com/WZ7j8C
70,132,769
70,132,928
when I build and execute code the console is shutting immediately on codeblock C++
I tried some solves that system("pause") / adding getcha() but none of them worked. #include <iostream> using namespace std; int main() { cout << "hello world" << endl; return 0; } What should I do?
Your code is most definitely valid. The reason it's shutting down is just the way Code::Blocks is set up. You can follow the instructions here to make the console stay open after executing the program.
70,133,089
70,133,151
Why do we have to use int a[][10] when passing 2d arrays to functions?
I want to pass a 2d array to a function, and I know how to do it int function(int a[][10]) The problem is, I dont like working with stuff I dont understand, so I would like to understand why do we have to use "int a[][10]" instead of "int a[10][10]".
First the function parameter a is a pointer to an array of size 10 having elements of type int. That is, the parameter a is not an array as you might be thinking. This is called type decay as quoted below: Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to init...
70,133,131
70,133,219
How to read a single character from stdin
I need to make a program that will write A+B if the symbol is +, A-B if the symbol is -, but I dont know how to declare a variable that is + or -. Thanks in advance!
strangely enough I can't find a proper duplicate. #include <iostream> int main(int argc, char **argv) { char c; std::cin >> c; std::cout << "this is the char I got: " << c << "\n"; return 0; } compile your program with $ g++ main.cpp -o main and then run it: $ ./main + this is the char I got: +
70,133,171
70,133,218
When I am pass the array as arguments then I am faceing this error invalid types 'int[int]' in c++
I am new to c++. can anyone guide me on how I can pass the array in functions? basically, I am trying to find a number with a linear search and print the index of that number in c++ // linear search #include <iostream> using namespace std; int search(int arr, int n, int x) { int i=0; ...
For starters variable length arrays like this int arr[size]; is not a standard C++ feature. Instead it would be much better to use the standard container std::vector<int> in a C++ program. Secondly the function declaration is incorrect. The first parameter is declared as having the type int. int search(int arr, int n...
70,133,448
70,134,605
Reference to a Structure
I read this portion from a book called C++ Primer Plus (Page no. 400. Chapter:8 - Adventures in Functions) A second method is to use new to create new storage. You've already seen examples in which new creates space for a string and the function returns a pointer to that space. Here's how you chould do something simil...
As far as I know for best practices you should never dereference a pointer without initializing it That's not just a "best practice", but it's absolutely mandatory to not do so. You must never indirect through an uninitiliased pointer. How the new operator is automatically called when calling the function ? new ope...
70,133,575
70,133,883
OpenMP nested loop task parallelism, counter not giving correct result
I am pretty new in openMP. I am trying to parallelize the nested loop using tasking but it didn't give me the correct counter output. Sequential output is "Total pixel = 100000000". Can anyone help me with that? Note: I have done this using #pragma omp parallel for reduction (+:pixels_inside) private(i,j). This works f...
First of all you need to declare for OpenMP what variables you are using and what protection do they have. Generally speaking your code has default(shared) as you didn't specified otherwise. This makes all variables accessible with same memory location for all threads. You should use something like this: #pragma omp pa...
70,133,808
70,134,381
SFML slow when drawing more than 500 shapes
I am new to SFML and I would like to implement a fluid boids simulation. However, I realized that when more than 500 shapes are drawn at the same time, the fps drop quickly. How can I improve the code below to make it much faster to run? #include <SFML/Graphics.hpp> #include <vector> #include <iostream> sf::ConvexShape...
The problems are a lot of draw calls. That is slow part of this program. In order to fix this, we can put all triangles into single vertex array and call draw upon only that array. That way we will speed up program. Problem with it is that you must implement your own rotate method. I implemented the method below and ed...
70,133,836
70,133,972
Why doesn't Code::Blocks build my .exe file?
I have just installed a fresh Code::Blocks instance, however the build button doesn't work: I have pressed it many time to build the .exe file, but when I try to run it asks me to build it again. The "Yes" button on the pop-up dialog that asks me to build doesn't do anything. My complier's installation directory is C:\...
If you have a version of GCC as compiler (such as MingW for Windows), chances are it will come with support for the most recent version of C++ disabled by default. This can be explicitly enabled by going to Settings->Compiler Example And here, within Global compiler settings, in Compiler settings tab, check the box Hav...
70,134,773
70,135,161
Custom stream manipulator that passes a character to operator overload
I'm toying around with shift/io stream operator overloads and I was wondering if there is a way to pass additional arguments to the function, while still defining a default value for simpler syntax? Considering the simple example: #include <vector> #include <iostream> inline std::ostream& operator<<(std::ostream& ostr...
Minor improvements of the current design What you are doing is possible and can't be simplified much further. If you want to stick to your current implementation, I recommend fixing the following issues: Unnecessary copy of entire string Use return std::move(out).str(); to prevent copying the entire string in the stri...
70,134,955
70,135,239
Get SDL2 Mouse Position
How would I get the position of the mouse in c++ SDL2? I found this wiki however I'm not really sure what it means and how would I get the x and y in int form? https://wiki.libsdl.org/SDL_GetMouseState
Call the function described at the link you found; with pointers to the two int variables which you want to receive the coordinates. Simplified, the function works like this one: void SetXto5(int* x) {*x = 5;} i.e. the variable which your parameter points to will receive a value. (This skips the check for NULL pointer...
70,135,118
70,162,787
How to rotate a QGraphicsPixmap around a point according to mouseMoveEvent?
I want rotate a QGraphicsPixmapItem around a point according to mouse position. So i tried this: void Game::mouseMoveEvent(QMouseEvent* e){ setMouseTracking(true); QPoint midPos((sceneRect().width() / 2), 0), currPos; currPos = QPoint(mapToScene(e->pos()).x(), mapToScene(e->pos()).y()); QPoint itemPos((midPos.x() ...
Besides the mixup of degrees and radians that @rafix07 pointed out there is a bug in the angle calculation. You basically need the angle of the line from midPos to currPos which you calculate by double angle = atan2(currPos.y() - midPos.y(), currPos.x() - midPos.x()); Additionally the calculation of the transformation...
70,135,192
70,135,370
C++ macro time arithmetic
I'm working on a wgl loader and typedef'd each openGL function that I use like this: /*Let's say I'm defining n functions*/ typedef return_t (*f1)(params) f1 _glFunc1; #define glFunc1(params) _glFunc1(params) ... typedef return_t (*fn)(params) fn _glFuncn; #define glFuncn(params) _glFuncn(params) Then to get the defi...
Similar to C Preprocessor output int at Build first you have to implement operations: typedef return_t (*f1)(params) typedef return_t (*f2)(params) void *GetProcAddress(charr *); #define SUB_10_0 10 #define SUB_10_1 9 #define SUB_10_2 8 // etc. for each each possible combination, 1000 of lines ... #define SUB_21...
70,135,306
70,135,397
Problem about c++ pointers assigning values
I have a confusion about the pointers. as the code shows below, CreditCard is a class defined in the head file, and we're defining a vector that contains 10 CreditCard pointers. After defining, we assign 3 new cards to the vector. It is clear that the vector's elements should be type pointer to CreditCard, however we a...
After defining, we assign 3 new cards to the vector. It is clear that the vector's elements should be type pointer to CreditCard, however we actually assign CredicCard objects rather than pointers to it. No we are not assigning 3 new cards to the vector. Instead we are assigning the pointers to CreditCard objects cre...
70,135,490
70,142,236
How can i combine multiple variadic templates or split parameter pack?
I am currently trying to define a generic multiplication operator for std::functions. I want to do this using multiple variadic templates. The partial specializations look as follows: template <typename... _Type> using op_Type = typename std::function<u64(u64, _Type...)>; inline auto operator*(const op_Type<>& f, cons...
In hope I got your wishes... template< typename PACK1, typename PACK2 > struct Combined; template < typename ... PACK1, typename ... PACK2 > struct Combined< std::function< uint64_t( uint64_t, PACK1... )>, std::function< uint64_t(uint64_t, PACK2...) > > { using OP_TYPE1 = std::function< uint64_t( uint64_t, PACK1....
70,135,569
70,136,598
c++ std::unordered_map singleton access violation error
template <typename T> class singleton { public: static T* ms_singleton; singleton() { assert(!ms_singleton); long offset = (long)(T*)1 - (long)(singleton <T>*) (T*) 1; ms_singleton = (T*)((long)this + offset); } virtual ~singleton() { assert(ms_singleton); ...
by changing the Singleton code as follows. I solved the problem. template <typename T> class singleton { public: singleton() {} ~singleton() {} static T& Instance() { static T instance; return instance; } singleton(const singleton&) = delete; singleton& operator=(const sing...
70,135,737
70,136,095
visual studio can't apply clang-format 13
I'm expecting to use AlignArrayOfStructures, however it's only available in clang-format 13. So I set Custom clang-format.exe to C:/Program Files/LLVM/bin/clang-format.exe. PS C:\Program Files\LLVM\bin> .\clang-format.exe --version clang-format version 13.0.0 But I still got a error, it says
Reading the manual carefully. AIAS_Right (in configuration: Right) AIAS_Right is the enum value, corresponding name in the config is Right. Use AlignArrayOfStructures: Right
70,136,031
70,136,105
C++ call a member function of an anonymous object instance?
I have the following piece of code: map<int, set<int>> my_map; int my_int1, my_int2; // some code set<int> temp; temp.insert(my_int2); my_map.insert(make_pair(my_int1, temp)); Is there some way to avoid using the temp (at least just for the code to look nicer, not necessarily for performance) and use an anonymous obje...
Not tested but try something like this: my_map.insert({my_int1, {my_int2}}); Ok, let's sumarize. There is an important thing to know about insert: the insert doesn't insert if key already exists. //create and initialise inline a map with int keys and string values map<int, string> x { {10, "hello...
70,136,487
70,136,860
Instantiate an object and pass its name to constructor using c++ macro
Let's say class A { A(string name) { //.... } } So when the object is created: A* objectNumber324 = new A("objectNumber324"); A* objectNumber325 = new A("objectNumber325"); In my case as the object names are pretty long, I am looking for macro to simplify that code to: CreateA(objectNumber325); There is...
#include <string> #include <iostream> #define CreateA(name) \ A* name = new A(#name) // With type #define CREATE_WITH_TYPE(type, name) \ type* name = new type(#name) // With name decoration #define CREATE_WITH_DECO(type, name) \ type* my_##name = new type(#name) class A { public: A(std::s...
70,136,586
70,407,297
Will std::sort always compare equal values?
I am doing the following problem on leetcode: https://leetcode.com/problems/contains-duplicate/ Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. The solution I came up to the problem is the following: class Solution { public: ...
Will std::sort always compare equal values or sometimes it can skip comparing them and therefore duplicate values will not be found? Yes, some equal value elements will always be compared if duplicates do exist. Let us assume the opposite: initial array of elements {e} for sorting contains a subset of elements having...
70,136,614
73,967,696
FrameBuffer.insert() will result in a access violation during loading of EXR image
I have the following function to load a OpenEXR image, which is basically just copied from their examples: void HDrRenderer::ReadExrImage( const char fileName[], Imf::Array2D<half>& rPixels, Imf::Array2D<half>& gPixels, Imf::Array2D<float>& zPixels, int& width, int& height) { Imf::InputFile file...
I had the same problem - and I keep stumbling on it every time I come back to C++ after a break. In visual studio, you cannot run an application in debug mode while using dlls compiled in release mode. Other way is okay. Compile the OpenEXR library in debug mode, debug your app, then compile both in release. Hope t...
70,136,711
70,484,103
GSL ODE solver returns -nan although same ODE with same parameters is being solved in python
I use python to solve ODEs using scipy.integrate.odeint. Currently, I am working on a small project where I am using gsl in C++ to solve ODEs. I am trying to solve an ODE but the solver is returning -nan for each time point. Following is my code: #include <stdio.h> #include <math.h> #include <iostream> #include <gsl/gs...
Your problem is here: f[0] = m*k*pow(s,n)*pow((y[0]/(k*pow(s,n))),(m-1)/m); As the solver proceeds, it may want to sample negative values of y[0]. In Python this makes no problem, in C++ it produces NANs. To handle this, you can mimic Python's behavior: auto sign = (y[0] < 0) ? -1.0 : 1.0; f[0] = sign*m*k*pow(s,n...
70,136,904
70,143,344
How to use curl_blob in libcurl/ c++?
I am trying to use libcurl with c++ and to make requests with mTLS (mutual TLS/ Two Way TLS). Passing the certificates as file paths works. But I would like to use embeded certificates in the source code and not external files. I discovered BLOB options in the curl lib website (example) There is also an example on the ...
I have found the solution. stdblob.data requires a char* with the file/string content. stblob.len requires the length of the string/char array. This is a simple example: char* str_to_char_arr(string str) { const int n = str.length() + 1; char* char_array = new char[n + 1]; for (int i =...
70,136,940
70,137,641
can you help me with the copy c'tor for derived class?
I have this base class: class LevelPlayer { protected: int level; int id; public: LevelPlayer():id(-1){} LevelPlayer(int level,int id):level(level),id(id){} virtual ~LevelPlayer()=default; LevelPlayer(const LevelPlayer&)=default; LevelPlayer& operator=(const LevelPlayer&)=default; }; and thi...
I am not sure if it's correct ... should I also add LevelPlayer(player) ? Yes, the derived class copy constructor needs to call the base class copy constructor explicitly: GroupPlayer::GroupPlayer(const GroupPlayer& player) : LevelPlayer(player), ptr(new IdPlayer(*(player.ptr))) { } Since you have implemented th...
70,137,010
70,137,114
How to make zero's appear on left side?
I am writing this program, in which we need to convert the input from the user from digits into words. I've written the whole program. The only error I am facing is that when I write e.g. 4200, the zeros aren't appearing. I am a beginner at C++. while (num > 0) { rem = num % 10; sum = sum * 10 + rem; num = ...
Your solution is not optimal. So, I have written a new solution. Solution int num; cin >> num; vector<string> v; while (num > 0) { switch (num % 10) { case 1: v.push_back("One"); break; case 2: v.push_back("Two"); break; case 3: v....
70,137,027
70,137,320
RSA-Implementation isn't decrypting correctly
I like to learn and today I decided to finally implement RSA on my own. Basically from what I can tell my Code should work and it actually does to a certain extent. However, even though (according to Internet learning sources) the correct keys are calculated and correctly used I get weird outputs. I checked but couldn'...
As @President James K. Polk correctly guessed the Problem was a silent Integer-Overflow. Also to anyone stuck on this: too high encryption-data-integers can cause problems on small primes easily. I used this to replace pow(a, b) % c in the encrypt & decrypt Method with a call to modularPow(a, b, c): unsigned long long ...
70,137,216
70,137,386
C++ Stream Extraction Operator>> Declared But Not Defined Even Though It Is Defined
So I have in stockType.h #include <iostream> class stockType { public: //... static friend std::ostream& operator<<(std::ostream& out, const stockType& stock); static friend std::istream& operator>>(std::istream& in, stockType& stock); private: //... } and in stockType.cpp std::ostream& operator<<(std:...
Marking a free function (friend functions aren't methods in a class) as static indicates that it will be defined in the current translation unit. Putting a static function in a header means that all translation units including that header must have their own definition of that function. You should remove static from yo...
70,137,779
70,143,080
Using eigen objects in C
I want to wrap part of Eigen's feature in C, but I am curious how would the automatic storage duration works in such case. For example: /* eigenwrapper.h */ #ifdef __cplusplus extern "C" { #endif void* create_matrix(int r, int c); //and other declarations like addition, multiplication, delete ... .... #ifdef __cplus...
As others have noted, C++ does not keep track of references. If you want a C API, you have to deal with this yourself. Opaque pointers As far as wrapping Eigen functions into C API, I would go with opaque pointers instead of void* so that you have at least some type safety. Here is a suitable header: #pragma once #inc...
70,137,780
70,137,822
Adding/Removing headers has no effect
I have used std::invalid_argument exception class in my code. So I also had included the header <exception> in the precompiled header (pch.h in my case). But then I removed <exception> from pch.h and the code compiled successfully on GCC 11.2 and I was surprised. Here are some examples: #include <exception> // removing...
But then I removed from pch.h and the code compiled successfully on GCC 11.2 and I was surprised. This isn't unusual. You'll get used to it. How is this possible? This can happen when one of the headers that you still include happens to also include those headers that you don't directly include. Is it safe to rem...
70,137,934
70,138,077
Programming principles and practice 2nd ed. signed char overflow
I've finished C++ primer 5th edition and now I'm reading C++ programming principles and practice 2nd edition by Strostrup. However the author seems to depend on some UBs in many cases like this one: int x = 2.9; char c = 1066; Here x will get the value 2 rather than 2.9 , because x is an int and ints don’t have val...
But char x = 1066; is overflowing a signed char so the behavior is undefined That's not true. Overflow happens as a result of an arithmetic operation. What happens here is conversion. Converting an unrepresentable integer to another integer type does not have undefined behaviour even if the type is signed. P.S. char ...
70,138,063
70,138,122
Why do cin and getline exhibit different reading behavior?
For reference I have already looked at Why does std::getline() skip input after a formatted extraction? I want to understand cin and getline behavior. I am imagining cin and getline to be implemented with a loop over the input buffer, each iteration incrementing a cursor. Once the current element of the input buffer eq...
reading behavior of cin and getline. cin does not "read" anything. cin is an input stream. cin is getting read from. getline reads from an input stream. The formatted extraction operator, >>, reads from an input stream. What's doing the reading is >> and std::getline. std::cin does no reading of its own. It's what's ...
70,138,115
70,146,027
How to get Tflite model output in c++?
I have a tflite model for mask detection with a sigmoid layer that outputs values between 0[mask] and 1[no_mask] I examined the input and output node using netron and here's what I got: I tested the model for inference in python and it works great. # A simple inference pipline import numpy as np import tensorflow as...
The code now works fine with these changes : memcpy(input,img.data,32*32*sizeof(float)); instead of input = inputImg.ptr<float>(0); and using index 0 for output float* output = interpreter->typed_output_tensor<float>(0); The index here indicates the order of the output tensor not it's location
70,138,546
70,138,631
How is it possible to safely copy an int into a byte array unaligned?
I created a byte array, uint8_t data[256], and I would like to read and write data to it at arbitrary positions. The position offset could be any number, so it could result in an unaligned access. For example if sizeof(int32_t) == 4 then position % sizeof(int32_t) != 0 It works now but, as far as I know, some platforms...
I see no placement new in your code, making both reinterpret_casts undefined behaviour. The returned pointer can only be dereferenced if at the given address exists an object of the specified type. With exception of char, std::byte, unsigned char which can always be dereferenced. The safe way how to serialize and deser...
70,138,817
70,139,112
How to get an Eigen vector from an Eigen matrix column/row?
The thing I want to do is this: MatrixXd M; // Whatever assigned to `X` VectorXd V = M(1); Eigen does not support this. Is there a way to retrieve an Eigen vector from an Eigen matrix?
Eigen Slicing and Indexing is of much use here. To retrieve an i-th row vector: VectorXd V = M(i, all); To retrieve an i-th column vector: VectorXd V = M(all, i);
70,139,058
70,139,170
Only one variable is working at a time, and it is dependent on which order I declare them in
I really didn't know what to put as the title for this so ignore that. I also don't know how to describe the question so here is my issue. #include <iostream> #include <vector> class ClassB { public: //LOOK AT THIS PART int value; char letter; ClassB(char t, int v) { letter = t; value = v; } }; clas...
The problem lies here: ClassA(ClassB n) { ptr = &n; } ClassB is a temporary variable that gets destructed at the end of the function. The pointer becomes invalid and the program goes nuts. A simple and safe way to go about this, is to use an std::unique_ptr and pass parameters. unique_ptr will automatically del...
70,139,225
70,139,257
My positive double value is printed as a negative output like -6.27744e+66
I get a negative output to a positive double variable. My object is: Fahrzeug fr("BMW",200.45); class Fahrzeug { private: string p_sName; double p_dMaxGeschwindigkeit; public: Fahrzeug(string p_sName, double p_dMaxgeschwindigkeit) { this->p_sName = p_sName; this->p_...
this->p_dMaxGeschwindigkeit = p_dMaxGeschwindigkeit; this assigns the (uninitialised) member variable to itself. You also have a parameter called p_dMaxgeschwindigkeit which you probably meant to use but note that its not the same spelling - it has a lowercase G and C++ is case sensitive.
70,139,520
70,178,232
gdb debugger quits prematurely on popen(), 'signal SIGTRAP, Trace/breakpoint trap'?
The following code works in stand alone (non-debugging) mode. However gdb debugging stops when I tried to step over popen(), meaning a breakpoint at the fgets() can never be reached. #include <stdio.h> int main() { char buff[10]; FILE *f = popen("echo blah", "r"); // program and debugger exit before this l...
Turned out to be a kernel issue, at least when I reverted back from 5.15.x to 5.14.x, the issue went away. I thought kernel update were never meant to break userspace.