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
67,763,460
67,763,626
Displaying a bitmap in 13h graphics mode, with use of C++
I'm trying to display a 320x200x8 bitmap. I got the palette working just fine, but when i try to display the bits, the image is upside down. What should be changed here? void display_image_data(char *file_name) { bitmap_file = fopen(file_name, "rb"); fread(&bmfh, sizeof(bmfh), 1, bitmap_file); fread(&bmih, sizeo...
BMP files originate from OS/2 which uses standard graphing axes — the origin is at the lower left of the display and positive y moves up the screen. Data that is stored in OS/2 order and then displayed in raster order will appear to be upside down. So you just need to read the data line by line and store those lines in...
67,763,620
67,763,781
Return char[256] from an accessor of a char[256] attribute
class A{ char info[256]; public: char* getInfo(); A(char i[256]); //A.cpp #include "A.h" char * A::getInfo(){ return(&info[256]); } A::A(char i[256]){ info[256]=i[256]; } I'm struggling with the accessor. When I try to use getInfo(), I get a char*, and thus with char test[256] ...
The problem is, your constructor is not initializing the contents of the info array correctly, and your accessor is returning a bad pointer. In the constructor, info[256]=i[256] does not do what you think it does. You are trying to copy the 257th element of i into the 257th element of info, which is Undefined Behavior...
67,763,754
67,764,087
C++20: boost::algorithm::to_lower( std::u8string )
This C++20 program #include <iostream> #include <string> #include <boost/algorithm/string/case_conv.hpp> int main() { std::u8string s8 = u8"ABC"; boost::algorithm::to_lower( s8 ); std::cout << std::string( s8.begin(), s8.end() ); } Works fine in Visual Studio 2019 (prints "abc") Throws std::bad_cast in g...
UTF-based strings don't work with locale-aware constructs like pretty much all of Boost.Algorithm's text conversion stuff. And even if they did work, they would be unable to perform Unicode-based case conversion. You need a library that is both Unicode-aware and knowledgeable about char8_t.
67,763,803
67,763,909
std::string::insert doesn't work with to_string(). CPP
I am writing a code to insert an integer at an index of the string, but after providing the integer to add as string, insert function is not giving the correct output. It is giving the error that : no matching member function to call for insert string This is my code: #include <iostream> using namespace std; int mai...
Looking at the documentation for std::string::insert() shows that it takes a char or an iterator range, not a std::string, which std::to_string() naturally returns. At least, this is the case for the overloads that take an iterator for the first argument. #include <iostream> #include <string> // CHANGED: Include what ...
67,764,546
67,765,074
How can I successfully Build gRPC in C++?
I am trying to build gRPC in C++ by following c++ gRPC installation. My OS is Ubuntu20.4 LTS installed on Raspberry Pi 4. When I typed this command "make -j" $ cd grpc $ mkdir -p cmake/build $ pushd cmake/build $ cmake -DgRPC_INSTALL=ON \ -DgRPC_BUILD_TESTS=OFF \ -DCMAKE_INSTALL_PREFIX=$MY_INSTALL_DIR \ ...
Can you show what value the gRPC_SSL_PROVIDER variable has? If has module than you just init submodules and build with BoringSSL (see and see). Another option, you can build with OpenSSL, just set -DgPRC_SSL_PROVIDER=package.
67,764,605
67,764,751
Why Boost.Asio SSL request returns 405 Not Allowed?
I am trying to send HTTPS request to a server and receive the page contents by only using Boost.Asio(not Network.Ts or Beast or others) by these code : #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <iostream> int main() { boost::system::error_code ec; using namespace boost::asio; // wha...
... "GET /index.html HTTP/1.1\r\n\r\n" This is not a valid HTTP/1.1 request. It must at least also contain a Host field and the value of the field must match the servers expectation, i.e. "GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n" In general, HTTP might look easy but is actually complex and has seve...
67,764,621
67,764,997
Returning full array C++?
I'm trying to print/return the array listum in code below, but receive error messages about invalid conversions. After a little research it seems that printing arrays all at once is not possible in C++, but must be printed in a for loop of individual letters. I would simply do that but I also read that one return comma...
In C/C++ one does not simply return an array from a function. When you allocate an array inside a function, you cannot return a pointer to the first element in that array, since when the function returns, all local variables allocated inside that function are wiped clean. int* printLetters() { int listum[]; re...
67,764,720
67,764,765
CRTP: use static constexpr from derived class
My CRTP derived class has some compile-time fixed dimension that I define using a static constexpr. Now I want to use it as a static variable from the base class. How do I do this? Example: #include <array> template <class D> class Base { public: void myfunc() { auto n = derived_cast().n; std::...
auto n = derived_cast().n; should be: constexpr auto n = D::n; Demo
67,764,744
67,764,810
Please turn this into a loop
I have been struggling in making this a loop. Any help would be appreciated. I attempted writing a loop in many ways, but the output would always turn out wrong, unlike how it works in this code. Thanks in advance. std::string findConfPass(std::string link) { if (link.length() == 64) { std::string foundConfPass =...
Using size_t len your cases are if (link.length() == len) { std::string foundConfPass = link.substr(len-32, 33); return foundConfPass; } Now you can see that all cases for 64 <= len <= 75 are identical when written like above. Only the else is different. Hence the whole function could be written as: std::stri...
67,764,780
67,764,925
Vector of classes containing pointers not working
I have this C++ code: #include <vector> using namespace std; struct Test { int* member = 0; Test() {} Test(const Test& o) { member = new int(*o.member); } ~Test() { delete member; } }; int main() { vector<Test> vecTest = { Test(), Test(), Test() }; vecTest.erase(vecTest.begin());...
-1073741819 is hex 0xC0000005. That is the exit code for an uncaught Access Violation exception. Which means your code is accessing invalid memory. Your vector is initialized with Test objects that are holding null pointers. When you erase the 1st object, the remaining objects have to be moved down in the vector. But,...
67,764,823
67,764,824
How to explicitly capture a macro inside a lambda capture?
I have a lambda and want to print the name of the function the lambda is defined in. If I use __FUNCTION__ inside the lambda, it'll just print operator(), which is reasonable since that's the function the macro is in. However, Clang-Tidy warns about this and mentions the following: Clang-Tidy: Inside a lambda, '__FUNC...
Yes, since C++14 it's possible to use lambda capture initializers which allows arbitrary expressions to be captured by name. So a solution is: #include <iostream> int main() { [function_name=__FUNCTION__](){ std::cout << function_name << std::endl; // Prints "main". }(); return 0; }
67,765,128
67,765,211
Is it possible to swap std::array in constant time?
From what I understand, swapping a std::vector is a constant time operation because the only pointers are being swapped, but in the case of an std::array the swapping is element-wise. Is it possible to swap the pointers of an std::array? Apologies if this has been asked to death already. If so kindly point me in the ri...
You can think of std::vector as something along these lines template<typename T> struct vector { T * pointer; int N; // well, not really int // the several constructors allocate memory, set N, and do other stuff if necessary // Other stuff }; so there's the pointer you refer to, the one which is swappe...
67,765,288
67,790,100
What does `⟨library⟩` mean in [defns.prog.def.spec]?
3.42 program-defined specialization [defns.prog.def.spec] ⟨library⟩ explicit template specialization or partial specialization that is not part of the C++ standard library and not defined by the implementation.
Definition context tags (non-normative / from draft .tex source) The ⟨library⟩ definition context tags were added when moving [definitions] from [library] (C++20) into [intro.defs] (current draft). The ⟨library⟩ definition context tag in the particular change you are quoting was added when [defns.prog.def.spec] in [def...
67,765,327
67,765,566
C++ pointer vs object
Could you please clear up a question for me regarding pointer vs object in C++. I have the below code that has a class called "person" and a list that allows for 100 objects of that class type. class person {...} int main { person* mylist; mylist = new person[100]; mylist[0].set_name("John") // ... } ...
T* represents a pointer type, which represents a variable that contains a "reference" (usually a memory address) to some instance of type T. Using a real world comparison, a T* pointer stands to T like a street address stands to a building. Pointers allow you to refer to some instance owned by some other variable, and ...
67,765,640
67,766,167
What makes an overloaded function prefered to another?
I have implemented a simple BooleanVariable class, where I get the boolean value from template parameter V, and it's comparison function operator==: #include <iostream> template<bool V> struct BooleanVariable { BooleanVariable() = default; constexpr bool operator()() const { return V; } }; templa...
A good rule of thumb for overload resolutions where templates are involved is that more specialized candidates are preferred over more generic candidates. For example: void foo(int); template <class T> void foo(T); If you call foo like foo(42), the non-templated version will be called since it is more specialized. If...
67,765,649
67,769,690
How to convert the ancestor class to the parent class and after back correctly?
I convert an object of class B to class A, after which I try to convert class A back to B, but an error occurs. How to do it correctly? #include <iostream> using namespace std; class A { public: int a = 0; }; class B : public A { public: int a = 1; }; int main() { B b; A a = (A)b; B b = (B)a; //...
this is not the correct approach to handle class inheritance in c++. Doing this can be dangerous and result in object slicing when you copy your subclass object to superclass object. Maybe what you are trying to achieve can be done through pointers: B b; A* aa = &b; B* bb = static_cast<B*>(aa);
67,765,848
67,778,934
Troubles with CMake and Assimp
I have the latest assimp source code (5.0.1 release), I have built it with CMake and installed using cmake --install. Now I am trying to add it to my CMake project: find_package(Assimp REQUIRED Assimp) - at this moment it configures fine. The problems started when I tried to add target_link_libraries( MyProj PRIVAT...
Without having any knowledge of assimp, I think what you want is this: target_link_libraries(MyProj PRIVATE assimp::assimp) As far as I know, CMake target names are case sensitive and the assimp::assimp alias target is created here with lowercase a.
67,765,898
67,766,242
Aliasing accesses through a std::bit_cast()ed pointer
Violating strict-aliasing rules yields undefined behavior, e.g. when sending a struct over the network into a char buffer, and then that char pointer is C-style/std::reinterpret_cast() casted to a struct pointer. The C++ std::bit_cast() function looks like it could be used to cast such pointers in an (implementation?) ...
Converting the pointer value is irrelevant. What matters is the object. You have a pointer to an object of type X, but the pointer's type is Y. Trying to access the object of type X through a pointer/reference to unrelated type Y is where the UB comes from. How you obtained those pointers is mostly irrelevant. So bit_c...
67,766,249
67,779,938
Problems while trying to extract features using SIFT in opencv 4.5.1
I am trying to extract features of an image using SIFT in opencv 4.5.1, but when I try to check the result by using drawKeypoints() I keep getting this cryptic error: OpenCV(4.5.1) Error: Assertion failed (!fixedType() || ((Mat*)obj)->type() == mtype) in cv::debug_build_guard::_OutputArray::create, file C:\build\master...
You are getting a exception because output argument of drawKeypoints must be 3 channels colored image, and you are initializing output to 1 channel (grayscale) image. When using: Mat output(source.rows, source.cols); or Mat output;, the drawKeypoints function creates a new colored matrix automatically. When using the d...
67,766,362
67,766,431
C++ ifstream XCode / VSCode
I'm a beginner in C++, I'm trying to open and read a file line by line, but it doesn't seem to work in XCode, while working in VSCode: The code: #include <iostream> // Imported to read #include <fstream> // Imported to read #include <string> // Imported to write lines #include <vector> // Imported to store lines #...
Your code assumes that input_text_file.txt is in the current working directory when the program is run. In Xcode, this is evidently not the case. The easiest fix is probably to use a fully qualified pathname, /path/to/your/file.
67,766,694
67,770,321
How to perform stable sort in C++ when using a custom comparator?
I am trying to write a custom comparator in C++ to sort a vector. For the sake of simplicity, I will say my sorting criteria is that all even values should come before all odd values and I am trying to write a custom comparator for this. But I need to make sure that the relative order of all even elements and all odd e...
The comparator for sort and stable_sort must induce a strict weak order. Your comparator does not satisfy this condition. One of the properties of a strict weak order is that for any permitted values of i and j, at most one of mysort(i,j) and mysort(j,i) can return true. Your comparator returns true for both cases when...
67,766,788
67,767,349
Smallest Power of 2 greater than n
This is slightly different than all the other questions asking just for an algorithm. I would like to know whether there is an O(1) algorithm that does this in C++. It seems that since C++ is such a low-level language that works closely with bits, there would be a quick O(1) function that would return the highest bit, ...
The most efficient way in C++20 is std::bit_ceil(n) In older C++ standard use boost::multiprecision::msb() or compiler intrinsics of your compiler like __builtin_clz() or _BitScanReverse()... to get the most significant bit and then return that value return 1 << boost::multiprecision::msb(n); // cross-platfor...
67,766,965
67,768,839
Eigen 3x3 matrix inverse wrong result
problem description I'm using Eigen for some matrix task. Say I have matrix A whose size is 4x3, then its transpose A^T is 3x4 size, then A^T * A is 3x3 size, thus the inverse, (A^T * A)^(-1), is also 3x3 size. I would like to get (A^T * A)^(-1). By using the mentioned formula, and by manually defining A^T * A matrix t...
This is just a matter of numerical accuracy. As pointed out by @Damien in the comment, the matrix is ill-conditioned, and thus a small difference in the input can lead to a large change in the results. By copying from the output only the first five digits and using them to manually define the second matrix, a significa...
67,767,226
67,780,650
Moving an object in the direction of the camera
I'm making a project where I need to move a player in any direction using an analog stick. I'm limited to specific functions and I only have the positions of the camera and the player and the analog stick. The camera is always pointed to the player. vec2 &leftStick = getLeftStick(-1); // results in an x and a y, both r...
My solution, thank you @Borgleader for a majority of it. I found an equation to find the distance and velocity for the x and z online, then I tested a bunch of combinations until it worked properly. Not a good way to do this but it worked out. // this all replaces the last two lines of the previous code snippet float s...
67,767,783
67,778,002
"Drawing" with a totally transparent pen in QT
I am writing a whiteboard application in QT. I am using a double layer approach, so I have a QPixmap that contains the drawing, and another that contains the background. The drawing pixmap is, unsurprisingly, with an alpha channel. Now I wish to implement an eraser tool. This tool should revert, wherever it paints, the...
This is a matter of composition mode of the QPainter in use. Default is QPainter::CompositionMode_SourceOver, which, as current pen is transparent, just leaves the underground as is. By setting to QPainter::CompositionMode_Clear you enforce the painter to erase anything. You shouldn't even have to change the current pe...
67,768,220
67,768,322
I'm getting an error when I use size(vec) to find size of a vector instead of vec.size(). How to fix this?
The error that is being generated is below. error: 'size' was not declared in this scope When I use nums.size(), it is working fine. It could be because of using an older compiler version, but in my system when I check the version it shows 10.3.0, which I think is the latest version. How do I fix this?
The std::size function was added in C++17, therefore, you need to enable its support. With GCC, just add -std=c++17 as a command-line argument to your g++ call. You can also check the libstdc++ source code: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/range_access.h#L236. As you can see, ...
67,768,238
67,772,678
Trying to build a queue using linked list in c++ but got this error:
I just started learning c++ and I am working on an assignment asking us to build queue using linked list, but when I tried my "display function" I got an Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) error, my logic behind this function is that little arrow(->) is to dereference pointers, so in theory it should be abl...
First of all, In else block of add function, I don't understand why are you incrementing front while adding new Node. By doing front = front->next your front pointer always points to second node in the list whenever you call add function and your first node get waste every time which results no nodes in the list. Secon...
67,768,296
67,768,685
How can I use an alias thats defined in a header file, in the return type (signature) of a function in the .cpp file?
I have a class, Tracker, where I declare an alias From Tracker.h: class Tracker { ... using ArgsMap = std::unordered_map<std::string, std::string>; std::shared_ptr<ArgsMap> getArgsMapForTask(std::string task); ... } In the .cpp file, where I define the function: #include Tracker.h ... // ArgsMap here gives error: Use ...
The problem is not that the alias is in the header file, that's totally irrelevant. The problem is that the alias is defined in the scope of the class, so you need to qualify it if you want to use it outside of the class: Tracker::ArgsMap.
67,768,569
67,768,998
Why is it possible to define a reference to a reference using type alias?
Since it is not possible to define a reference to a reference, why is the 8th line of this code not throwing an error? My understanding is that the aforementioned statement is equivalent to double &&ref2 = value; which should throw an error. #include <iostream> using namespace std; int main() { double value = 12.7...
Why is it possible to define a reference to a reference using type alias? is also not producing a compile-time error. Why is this so? why is the 8th line of this code not throwing an error? Because the language allows such expressions to be valid, there is no other explanation... Let's take the nice example from the ...
67,768,645
67,768,900
Segmentation Fault in C++: sorted linked list
I m writing a function to insert a number in a sorted linked list in C++. However, I am getting "Segmentation Fault" when I run it. Can anyone explain why it is so? Node * insertInSorted(Node * head, int data) { Node * curr = head; Node * a = new Node(data); while(curr->next->data < a->data || curr...
while(curr->next->data < a->data || curr->next != NULL) That is obviously wrong. The condition you want is: while(curr->next != NULL && curr->next->data < a->data) The next node must exist and Must have data smaller than the data you are inserting. The function still wouldn't work correctly (you never insert anythi...
67,768,674
67,769,586
How to compare std::vector items with key elements of std::map
I am trying to change items in a vector if they match key values of a map so that e.g. a "2" in the vector is replaced by "two", which is the value of the key "2" of the map. I cannot figure out how to compare these two elements because I cannot do something like: vector[i| == map_iterator->first I know there are other...
Iterate the vector and if the item is numeric, look it up in the map. If found then replace the item with the map value. Repeat until done. for (auto &item : str_v) { int key; std::stringstream ss(item); if (ss >> key) { auto itr = numbers.find(key); if (itr != numbers.end()) ...
67,768,723
67,932,981
Qt6.2 and Multimedia Module
As Qt6.2 released, it seems that the multimedia module will come back and today i download qt6.2 but "qt += multimedia" still doesn't work. How can i use the multimedia module or have an alternative to play a sound effect in c++? p.s. i'm using qt6.1 before.
Well, as far as I know, QMultimedia and QMultimediaWidgets are not present in the Qt 6.1 release. If you look att the following list, there are all the removed modules. (https://doc-snapshots.qt.io/qt6-dev/whatsnew60.html#removed-modules-in-qt-6-0) Also, if you look at the Qt 6.2 available modules, they don't appear ne...
67,768,776
67,769,001
How to create an boost::asio::ip::address_v6 from sockaddr_in6 without making an extra copy?
The problem is that address_v6 class accepts raw data strictly as bytes_type class: typedef array< unsigned char, 16 > bytes_type; but sockaddr_in6 struct doesn't have that, it has C-style arrays, that can't be converted to std::array without copying. So I have to create an std::array, copy data there, and pass that a...
The std::array is required to be struct that contains raw array as its first and only non-static data member. As the raw array contains unsigned chars it is therefore standard layout class. So I can not find a reason from standard why following code would not work: auto& bytearray = reinterpret_cast<std::array<unsigned...
67,770,383
67,834,333
Add days to date in C++
I am trying to add days to a formatted date in C++, but without any success. The date is passed as a SYSTEMTIME type, and days to add in long type. In the following code example i am adding the days in a date converted to long, and this is wrong, i am using this just as an example. long FormatDate(SYSTEMTIME* cStartTim...
After some search and debugging i am using the following code, and it's working. Note that hour, minute, second and millisecond from CustomDate must be set, otherwise it won't work. In this scenario i'm adding seconds, so it could be more generic. So when i need to convert to days i do this: daysToAdd * 24 * 60 * 60. S...
67,770,850
67,771,737
How to overwrite operator in C++ class with a variadic function?
C++ newbie here: I want to create a template class to create tensors of different data types and d dimensions, where d is specified by a shape. For example, a tensor with shape (2, 3, 5) has 3 dimensions holding 24 elements. I store all data elements using a 1d vector and want to access elements using the shape informa...
By providing "shape" as template parameter, you might do: // Helper for folding to specific type template <std::size_t, typename T> using always_type = T; // Your Tensor class template <typename T, std::size_t... Dims> class MultiArray { public: explicit MultiArray(std::vector<T> data) : values(std::move(data)) ...
67,771,250
67,771,574
C++ "else" statement when the preceding line has multiple "if" statements
The following C++ program #include <iostream> int main() { for(int i=0; i<5; i++) for(int j=0; j<5; j++){ if(i==1) if(j==2) std::cout << "A " << i << ' ' << j << std::endl; else std::cout << "B " << i << ' ' << j << std::endl; } return 0; } outputs B 1 0 B 1 1 A 1 2 B 1 3 B 1 4 From this ...
There was an answer that tried to advocate adding braces. We can rearrange your code also without braces to see more clearly what it does (and why it is not doing what you intended): #include <iostream> int main() { for(int i=0; i<5; i++) for(int j=0; j<5; j++){ if(i==1) if(j==2) ...
67,772,230
67,772,763
Installed VS code, there is no builder to build my code, even though I installed MinGW-w64
I have very recently installed VS code and am an absolute newbie. I first had a different problem because I installed the wrong type of MinGW-W64, which I have now uninstalled, then it seemed to fix the problem, until I tried to build the code. A photo of what going to terminal > run build task shows me is shown in thi...
By looking at the error message, you are currently executing the program in C:\Users\{username} directory however your source code file helloworld.cpp is present in C:\Users\{username}\OneDrive\Desktop folder. use cd "C:\Users\{username}\OneDrive\Desktop" in your terminal to navigate to the folder and then run the g++ ...
67,772,724
67,772,797
Items of std::array are changed unintentionally out of context
I'm trying passing the reference of array to class object by constructor, and operating the items in that object. But, I'm afraid that these items in array are changed just after reaching at the beginning of MySort::sort() below. (not changed before entering MySort::sort()) #include <iostream> #include <utility> #inclu...
The constructor MySort(T n) : _n(n) { _s = _n.size(); } Here you set _n to reference a input object which will get destroyed upon leaving the constructor. This is plain UB. To fix it write MySort(T& n) : _n(n) { _s = _n.size(); }
67,772,929
67,773,894
How can I put in a loop the change of a label in QT(c++)
I wrote this code , so I could monitor an ip address. I am using Qt and I want to make it, so when I press the button start it will ping the ip and return a value, like 1, which means that it is the minimum ping or whatever. The problem is that I cant put in a loop the change of a label. I tried QTimer but I couldn't f...
You should connect your timer timeout signal to your lambda function instead of calling timer.callOnTimeout: connect(&timer, &QTimer::timeout, this, [this]() { .... your code } ); also you don't need to start your timer again in your lambda function, because since you start it once, it will run continuously for it...
67,773,015
67,773,766
Is there any method for get current directory other than GetCurrentDirectory on c++?
I used GetCurrentDirectory to get the current directory from c++. However, if it was run by the registry after a reboot, the current directory will appear as c://Windows//System32 instead of the true current directory. my code: wchar_t get_path[MAX_PATH]; GetCurrentDirectoryW(MAX_PATH, get_path);
C++17 provides std::filesystem::current_path(), so the literal answer to your question is: Yes, C++ offers a different way to get the current working directory. More to the point: C++ offers a different interface. Internally, it just calls into GetCurrentDirectoryW, and produces the same value. So if GetCurrentDirector...
67,773,430
67,787,713
C++ program with string data type won't run unless I compile it with -static-libstdc++
For some time I didn't compile/run my programs using g++ in cmd and I only used CodeBlocks where I didn't have any problems so I don't know when this started. So I tried to run a program that I compiled with 'g++ main.cpp' and it either wouldn't run at all, like nothing happened, or this would pop out. From a not so re...
As @n. 'pronouns' m instructed in the comments, I checked my %PATH% and found LyX, a Latex document processor which I don't even remember using, which for some reason also had the libstdc++-6.dll file. I uninstalled it and that fixed it.
67,773,913
67,774,083
How to overload + operator for arrays in C++?
For a C++ exercise for school I need to overload the + operator to concatenate 2 arrays. And I need to do that in a generic class. for ex: a1 = {1, 3, 4} a2 = {2, 3, 5, 6} => a = {1, 3, 4, 2, 3, 5, 6} And I have this code but it's not working. #include <iostream> #include <array> using namespace std; template <class...
T operator+(const T& a1, const T& a2) takes two Ts as parameter and returns a T. That is not what you want. This is how you can concatenate two arrays by using operator+: #include <iostream> #include <array> template <typename T,size_t M,size_t N> std::array<T,M+N> operator+(const std::array<T,M>& a1, const std::...
67,774,249
67,774,301
Pass argument to callback function
I'am working with this library, as you can see setCallback as a protoype like this void Adafruit_ZeroTimer::setCallback(boolean enable, tc_callback cb_type,void (*callback_func)(void)){ I would like to know if it's possible to pass arguments to callback function? Should I change the library to accomplish that by someth...
Adding argument to the type of callback function for the argument like void (*callback_func)(int n) is right way. Calling function in argument instead of passing the function like my_timer.zerotimer.setCallback(true, TC_CALLBACK_CC_CHANNEL0, my_function_callback(10)) is wrong way. You should simply pass the function wi...
67,774,510
67,775,239
The redundancy of forward_iterator concept?
In [iterator.concept.forward], std::forward_iterator is defined as: template<class I> concept forward_­iterator = input_­iterator<I> && derived_­from<ITER_CONCEPT(I), forward_iterator_tag> && incrementable<I> && sentinel_­for<I, I>; and std::sentinel_for<I, I> is defined as: template<class S, class I...
Concepts have explicit syntactical requirements (ie: these expressions have to compile), but they also have implicit semantic concepts. equality_comparable<T> has a semantic requirement that if t == u, then t and u have the same value, however that is defined for T. But sentinel_for requires a more specific meaning for...
67,774,692
67,774,817
Is it possible to upload only parts of texture that has changed in OpenGL ES 2.0?
I display a 2D texture in OpenGL using Qt. Most of the texture is the same from frame to frame but a few horizontal lines may have changed. My first implementation uploaded the whole texture each frame using glTexImage2D. In my current implementation I call glTexStorage2D in the initializeGL() method. Next I upload onl...
You need to initialize the texture before you can use glTexSubImage2D to update parts of it. This can be done by calling either glTexStorage2D or glTexImage2D. If glTexStorage2D is not available, use glTexImage2D, as it has been available since very early versions of OpenGL. As the documentation of glTexSubImage2D says...
67,774,932
67,775,071
C++, checking two txt files via fstream library to concatenate lines with the same ID
I have to make a program which checks two txt files and concatenates the lines which start with the same ID. The results must be in a new file The files are in the following format: ID STRING_UP_TO_30_CHARS Error checking is not necessary but I have been stressing over this for quite a while now. I'm pretty new to prog...
while(getline(file2,line2)) After this inner loop finds the line from the 2nd file that matches the 1st line in the first file, the outer loop runs again to read the 2nd line from the first file. However, afterwards, this inner loop simply continues reading from the 2nd file from the point where it stopped reading on ...
67,774,961
67,775,081
loop terminates program where it shouldn`t
i`m practicing, and for some reason selection == p terminates my program, if the vector has any content. What am i doing wrong? I tried it both with for and while loop, and the results are the same :( do { cout << "Enter your choice: "; cin >> selection; if (selection == 'p' || selection == 'P') { ...
For starters these loops while (i <= numbers.at(i)) { cout << numbers.at(i) << ' '; i++; } and for (int i = 0; i <= numbers.size(); i++) are not equivalent. The condition in the first loop does not make a sense. The condition in the second loop invokes undefined behavior because the index i may not be equal t...
67,775,206
67,775,795
openCV: different results when matrix-multiplication with overloaded operator and without
I have a matrix in openCV like this: cv::Mat matrix = cv::Mat::zeros(5, 5, CV_32FC3); Then, I want to do matrix multiplication in two different ways, first channel-wise and second with overloaded operator. // VERSION 1: for (int row_count = 0; row_count < image.rows; row_count++) { for (int col_count = 0; col_count ...
OpenCV uses cv::saturate_cast<> pretty much everywhere when integral types are involved. You'd think this should only change how overflow and underflow behave, but it also has an impact on how floating point values are coerced. If you want to be binary compatible with the internal opencv code, you need to sprinkle a bu...
67,776,019
67,776,080
get an unknown amount of numbers from the user and get the average of these numbers with using dynamically allocated memory to store the values
I need to write a code that gets an unknown amount of numbers from the user and get the average of these numbers with using dynamically allocated memory to store the values, but I could write it in C++ and it must be C.How can I convert it in C language? #include <bits/stdc++.h> using namespace std; int main() { in...
You should create an array of int, not int*. You should use sizeof to calculate the size to allocate via malloc(). You have to initialize buffer allocated via malloc() before using its value for calculation. Otherwise, undefined behavior is invoked. You should add #include <stdlib.h> to use malloc(). You should derefe...
67,776,093
67,776,689
C++ Function with empty body vs function with no body
I am trying to understand the difference between having no body and having an empty body, as in these two functions: void draw() const override; void rotate(int angle) override {} The complete code is shown below, where Shape is an interface and Circle an implementation of that interface. #include<iostream> #include<...
A function declaration tells the compiler everything it needs to know to call a function. With that information the compiler can generate intermediate files such as "obj" files. Once the code is compiled, the next step is to link it, during linking the linker has to put the actual location for the code into the final e...
67,776,420
67,776,460
Class Initializer list does not work with copy constructor
I have this class A with one variable, initializing variables using initializer list works totally fine, if no copy constructor is present. class A { public: int x; }; int main() { A a = {2}; printf("Hello World"); return 0; } However if I do have a copy constructor inside the class, I am getting...
The user-declared constructor A::A(A&) makes A not an aggregate, then it can't be aggregate-initialized from brace-init-list like {2} again. You can add a constructor taking int, e.g. class A { public: int x; A(int x) : x(x) {} A(const A& v) { printf("Copied"); } }; Then A a = {2}; // l...
67,776,492
67,778,554
Scaling font as window is resized
I'm writing a C++ calculator application in wxWidgets. I want the font of all the buttons and the two wxTextCtrl's to be scaled as I resize the window. How is that done? I'm posting some code if that can help. text_controls.cpp #include "main.h" void Main::AddTextControls() { //creazione font wxFont Expressio...
You could use wxFont::SetPixelSize() to set the font size to, say, one third of the text control height. E.g.: MainText->Bind(wxEVT_SIZE, [this](wxSizeEvent& e) { e.Skip(); MainText->SetFont(wxFontInfo(wxSize(0, MainText->GetSize().y / 3)).Family(wxFONTFAMILY_SWISS).FaceName("Lato").Light()); }); (which also s...
67,776,493
67,777,248
Access outer object from inner object
I have 2 (incomplete) classes, Level and Object, in different files, that look like this Object.h: #pragma once #include "Core.h" class Object { public: Object(const Hitbox &hBox_, const Vector2& position_ = Vector2{0, 0}, const Vector2& velocity_ = Vector2{ 0, 0 }); virtual Hitbox getHitbox(); virtual voi...
Not sure if that's the best solution, but, thanks to @PeteBecker, I've added (and also found out, huh) include guard so now it looks like that: Object.h: #include "Core.h" #ifndef OBJECT_H_ #define OBJECT_H_ #include "Level.h" class Level; class Object { public: Object(Level* level_, const Hitbox &hBox_, const ...
67,776,594
67,776,814
Reference binding to null pointer of type "std::vector<int, std::allocator<int>>"
Hello I have this code here: class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; class Solution { public: vector<vector<int>> levelOrder(Node* roo...
vector<vector<int>> output; This declares a vector, an empty vector. The vector contains absolutely nothing, whatsoever. Its size is 0. This vector then gets passed as a parameter to a function, where the following happens: out[level].push_back(root->val); Since this vector is completely empty, out[level] resul...
67,776,830
67,953,252
C++ directory item iteration without exceptions
In C++17 it became easy to iterate over the items in some directory dir: for ( auto& dirEntry: std::filesystem::directory_iterator(dir) ) { if ( !dirEntry.is_regular_file() ) continue; ... Unfortunately this way may throw exceptions, which I want to avoid in my program. The iteration without throwing exceptions is a...
I think one can create a safe wrapper iterator, which operator ++ will not throw an exception, as follows // object of this struct can be passed to range based for struct safe_directory { std::filesystem::path dir; std::error_code & ec; }; //iterator of directory items that will save any errors in (ec) instead...
67,777,354
67,777,502
Why always produce 4 pictures in my qt opengl program?
Here is my code: modify from qt example: Examples\Qt-5.14.2\quick\scenegraph\openglunderqml void SquircleRenderer::init() { unsigned char* data = (unsigned char*)malloc(1200*4); for(int i=0;i<600;i++) { data[i*4] = 0; data[i*4+1] = 255; data[i*4+2] = 0; data[i*4+3] = 255; ...
Textures are mapped accross the [0, 1] range, and values outside of that range are modulo-looped back into it, which creates a repeating pattern. Interpreting the texture over the [-1, 1] range leads to what you are seeing since you are mapping exactly twice the UV range in both axises. There's a few ways to fix this. ...
67,777,653
67,895,665
OpenCV for Android via Visual Studio to Unity
I tried to compile a .so library using Visual Studio 2019 along with OpenCV Android in order to use this library in Unity. There are some answers on how to configure Visual Studio to use OpenCV Android (here or here) but none of these work for me. Below you can see my configurations. Visual Studio 2019 (running on Wind...
I had the exact same issue as you (though I used c++ 11) with the exact same setup, and struggled for days. I believe the errors you're seeing (like me) are from arm_neon.h. Very oddly, I was able to just build (not run) the .so successfully, even with those errors (I say "errors" because if you look at arm_neon.h, ot...
67,777,993
67,782,187
Query registry values
I'm trying to use C++ to query registry values like the following $ reg query HKLM\SOFTWARE\GitForWindows HKEY_LOCAL_MACHINE\SOFTWARE\GitForWindows CurrentVersion REG_SZ 2.31.1 InstallPath REG_SZ C:\Program Files\Git LibexecPath REG_SZ C:\Program Files\Git\mingw64\libexec\git-core I've f...
According to MSDN:Enumerating Registry Subkeys and RegGetValue, RegGetValue retrieves the type and data for the specified registry value. Code: int main() { long ret; unsigned long reg_index = 0; DWORD dwValSize = MAX_VALUE_NAME; DWORD dwDataSize = MAX_VALUE_NAME; LPTSTR lpValname = new TCHAR[MAX_V...
67,778,097
67,778,403
When/why/how do unqualified names look in dependent base?
For up to C++17 I find this wording in [temp.dep]p3 In the definition of a class or class template, the scope of a dependent base class (17.7.2.1) is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member....
Nothing has changed. The relevant rule is now [class.member.lookup]/4: Calculate the lookup set for N in each direct non-dependent ([temp.dep.type]) base class […] so that there need not be a special override for the name-lookup rules in [temp].
67,778,431
67,778,637
49 + 82 = -190? c++ ceasar shift
I am working on a code that encrypts messages. First of all, I apply Ceasar shift like this: message[i] += offset; In the case i = 40, offset equals 49 and message[40] equals 82. So 82 += 49 should be 131. (I logged every of the values before and after) Instead of 131, message[40] is now -190. This is the whole code: ...
If the type char behaves as the type signed char then the minimum and maximum values that can be stored in an object of the type can be obtained the following way #include <iostream> #include <limits> int main() { std::cout << static_cast<int>( std::numeric_limits<char>::min() ) << '\n'; std::cout << static_c...
67,778,899
67,916,594
Segmentation Fault when using some OpenGL functions
I am having troubles using OpenGL functions in my render loop. Here is my code : // This works, I have glad in an include folder with glad headers in it #include "include/glad/glad.h" #include <GLFW/glfw3.h> #include <iostream> int main(int argc, char *argv[]) { if (!glfwInit()) { std::cerr << "Faile...
I found two ways to "fix" the issue : Using the compatibility profile (not recommended but very easy): // Replace this glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // by this glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); This is not really a fix but it allows the program to run d...
67,779,177
67,779,435
C++ Switch statement to assign struct values
*I am trying to assign one struct object with values from a different struct for whatever bird type was selected using a switch statement. However, I am getting the conflicting decoration error. How can I resolve this? /** temp and humidity control points */ struct chicken_config { char *node_type = "incubator"...
There are several relevant problems in your code The C struct concept seems to be wrong: You can define a single struct type with a specific set of parameters and create several instances of this struct. For your case, you could create a basic animal_config struct and one instance per each animal you want to include i...
67,779,575
67,779,642
Convert a function to local function (lamba)
I want to make FindFirstKey1 function into a lambda function called FindFirstKey2: Here's what I tried: #include <vector> struct Point { int x; int y; }; bool FindFirstKey1(std::vector<Point> &m, Point &FirstKeyFound, int currentKeyIndex, int SearchKey) { if (currentKeyIndex < m.size()) { auto...
There are two problems with your code. Problem 1: bool FindFirstKey2 = [&m, &FirstKeyFound, currentKeyIndex, SearchKey]() The type of a closure, or a lambda, is an anonymous class. It is not a bool, therefore this should be: auto FindFirstKey2 = [&m, &FirstKeyFound, currentKeyIndex, SearchKey]() Problem 2: FindFirstK...
67,779,625
67,780,338
What is the meaning of Note 1 in the C++ class member name lookup rules?
From http://eel.is/c++draft/class.member.lookup#1 : A search in a scope X for a name N from a program point P is a single search in X for N from P unless X is the scope of a class or class template T, in which case the following steps define the result of the search. [Note 1: The result differs only if N is a conversi...
Answer A single search considers only one scope—not an enclosing namespace or even a base class. It’s an unqualified search that considers all enclosing scopes. Single searches and (plain) searches are subroutines of these higher-level procedures. Context It should be said, since there have been a lot of these questi...
67,779,743
67,779,995
Bijection from string to int aka reversible hash
I need to convert a set of strings similar to /azurite/spot00 to integers in order to use in ML libraries. Hand-rolling an enumerating algorithm (assign i++ to each next label) sounds easy enough. But nowhere nearly as elegant as a bidirectional hash between std::string and int (not sure if I need int64 or something el...
There's no general-purpose way to find a bijection from std::string to int for the simple but mundane reason that there are more possible std::strings than there are ints. (Specifically, there's effectively an unbounded number of possible std::strings, and there are only 232 or 264 distinct possible integers). There ar...
67,779,771
67,779,823
Strongest Neighbour question in GeekForGeeks
Input: n = 6 arr[] = {1,2,2,3,4,5} Output: 2 2 3 4 5 Explanation: Maximum of arr[0] and arr[1] is 2, that of arr[1] and arr[2] is 2, ... and so on. For last two elements, maximum is 5. A standard array problem and I know the right solution to it too but I tried using the max() function in the C++ std library and I'm ge...
This might be a dumb answer but it looks like you are missing spaces between the numbers. I see the "" in your string and you might need a " " instead. Without the space, it is one giant number. Does that help?
67,780,738
67,780,842
Strange thing with linked list
So I was doing this exercise on linked list. It's a very easy exercise but I noticed that something strange going on. The exercise asked to create a node with a name, an age and a average variable for a student. All nodes have to be in a linked list. This code works: #include <iostream> using namespace std; class Node...
When you want to append a node to your existing list, you need to: Find the last node in the list, let's call it l. Set l->next to a newly-created instance of Node. The first version of your code does exactly this, whereas the second just creates an orphaned Node. The fact that you assign this to temp doesn't achi...
67,781,000
67,781,034
Error in C++ program (*** Error in `./a.out': free(): invalid pointer: 0x00000000024a1c4f ***)
i'm writing a simple program in C++, however i keep getting the error described in the title. I have searched the internet, but the questions and answers i find usually involve templates. When i run the program on the clang compiler it simply stops without executing the function (marked in the code), but when i ran it ...
There are several bugs in the shown code. for(int i = 0; i < input_c.size(); i++){ if(get_type(input_c[i-1]) == "multi"){ On the first iteration of the loop i will be 0, the beginning value. The if statement's condition will then try to evaluate input_c[-1] which is undefined behavior. std::string get_type(char x)...
67,781,069
67,781,095
If I call operator new directly without a new expression and cast the return pointer type safe?
Hello I am on chapter 19 from C++ primer 5th edition. 'Operator new and delete vs new and delete expression and placement new': AFAIK operator new and operator delete allocate and deallocate memory respectively but don't construct an object there. On the other hand a new-expressioncalls operator new to allocate memory,...
Unless you use placement new (which is basically the other half of the ordinary new), no Foo object exists, so you can't call a member function on it. Moreover, if you do use placement new, you must call the destructor yourself: Foo* pf = new (operator new(sizeof(Foo))) Foo; // no cast needed pf->bar(); pf->~Foo(); o...
67,781,245
67,781,289
Recovering structs sent over a network
My coworker wants to send some data represented by a type T over a network. He does this The traditional way™ by casting the T to char* and sending it using a write(2) call with a socket: auto send_some_t(int sock, T const* p) -> void { auto buffer = reinterpret_cast<char const*>(p); write(sock, buffer, sizeof(...
The dicey part is not so much the memory alignment, but rather the lifetime of the T object. When you reinterpret_cast<> memory as a T pointer, that does not create an instance of the object, and using it as if it was would lead to Undefined Behavior. In C++, all objects have to come into being and stop existing, thus ...
67,781,346
67,813,110
Positioning Windows under WorkerW
I am trying to achieve something and having an unexpected behaviour which after a day of research, I suspect it's related to the difference between client coordinates and screen coordinates. But I come from a web background and have very limited understanding and experience in C++. So below is the code I am trying to h...
After spending a day reading around and trying to make sense of C++ concepts and the functions available from Windows, the code below worked for me POINT pt = {}; pt.x = 0; pt.y = 0; SetParent(hwnd, workerw); ScreenToClient(workerw, &pt); SetWindowPos(hwnd, HWND_TOP, pt.x, pt.y, NULL, NULL...
67,781,358
67,781,371
Expected linking error in C++ but executable builds fine
I have pasted the code below. I was expecting lines Circle {p, radius} and Circle::draw() to cause linking error because Circle constructor as well as the draw functions are merely declarations without definitions. However, the executable gets created properly without any linking errors. Why is there no linking error h...
There are no linker errors because: int main() { return 0; } Your program does not need to link to any method other than main to work, and main doesn't do anything.
67,781,736
67,781,806
C++ 20 chrono: How to compare time_point with month_day?
Is there a modern and elegant way to determine if the month and day in a time_point variable match a given month_day variable? For example, I want to know if today is Christmas. I have the following code: #include <chrono> bool IsTodayChristmas() { using namespace std::chrono; constexpr month_day Christmas = ...
You can convert system_clock::now() to a std::chrono::year_month_day type via a std::chrono::sys_days. In practice this might look something like #include <chrono> bool IsTodayChristmas() { using namespace std::chrono; constexpr month_day Christmas = {December / 25}; auto Now = year_month_day{floor<days>(...
67,782,116
67,784,234
Openmp c++: error: collapsed loops not perfectly nested
I have the following serial code that I would like to make parallel. I understand when using the collapse clause for nested loops, it's important to not have code before and after the for(i) loop since is not allowed. Then how do I parallel a nested for loop with if statements like this: void foo2D(double Lx, double Ly...
As pointed out in the comments by 1201ProgramAlarm, you can get rid of the error by eliminating the if branch that exists between the two loops: #pragma omp parallel for collapse(2) for(int i = 0; i < nx ; i++){ for(int j = 0; j < nyk; j++){ ... } if( i >= nx/2){ <== remove this k...
67,782,332
67,782,383
Function template taking function template
I'm learning concepts and templates. I'm trying to make a function template that will call another function template. Currently it works with lambda but not with a normal function. // This also works with lambda but not the normal function: //void callFunc(std::regular_invocable<T> auto invocable) template<typename T>...
You are under the impression that auto lambda = [](const auto& a){std::cout << a << " CALLED\n";}; is equivalent to template<typename T> void lambda(const T& a) { std::cout << a << " CALLED\n"; } But it's not. It's actually equivalent to: struct SomeType { template<typename T> void operator()(const T& a) const { ...
67,782,403
68,332,061
Arduino - GUISlice - gslc_ElemSetTxtStr not updating the text
I am trying to update the text of a dynamic text field created in GUISlice Builder. The code displays the GUI but does not update the text element on the GUI, could someone point out what I am missing? Thanks in advance. Properties of the text from GUISlice Builder: ElementRef: pElemDol1 External Storage Size: 7 The co...
Anyone with this problem: You need to have the gslc_Update(&m_gui); after the elements were updated. void lcdFunc() { char acTxt[MAX_STR]; snprintf(acTxt, MAX_STR, "%s", "1234"); gslc_ElemSetTxtStr(&m_gui, pElemDol1, "acTxt"); gslc_Update(&m_gui); }
67,782,621
67,782,652
Is the type cast from sockaddr_in* to sockaddr* a violation of "strict aliasing rule"?
Is the following type cast from sockaddr_in* to sockaddr* a violation of "strict aliasing rule" ? Example code snippet from "Beej's Guide to Network programming" (version 2.3.23). The typecast is happening at the last line. ... #include <arpa/inet.h> #define MYPORT 3490 main() { int sockfd; struct sockaddr_in my_addr; ...
A lot of the UNIX networking foundations are built on these sorts of creative "abuses" of structures. This can make using these functions and structures in non C code quite difficult as many languages, like C++, forbid these sorts of arbitrary recasting operations by default. In C++ you will need to deal with the fact ...
67,782,706
67,783,461
Passing 'this' wrapped as unique_ptr C++
I have a class that acts as a node in a binary tree, one of the methods which I would like to call from inside that class is recursive, and needs to pass itself to the next node in the tree so that the next node knows its own parent. I dont want to store a class member parent because I would like to avoid using a share...
Don't use a pointer at all. You are not taking ownership, the argument is not optional, so use a reference: void MyClass::expand(MyClass& parent){ for (int i = 0; i < children.size; i ++){ children[i]->doSomethingWithParent(parent); children[i]->expand(*this); } return; } All of your code w...
67,782,870
67,783,176
C++ `using {var}` is not a member of {child class} - when using `std::deque` in MSVC or Clang
The code below gives the error error C2039: 'value_type': is not a member of 'Child_Container' on line 7. This happens in MSVC and Clang, but not with GCC. Thereby when using std::deque, but not std::set, std::vector. Does anyone know why? Thank you! #include <deque> template<typename T_Container> struct _View { u...
The variable here is simply whether std::deque requires its element type to be complete when it is instantiated. (Of course it must be complete when certain member functions are instantiated, but that’s separate.) If it does, you end up needing your value_type before it’s declared, which produces the error observed. ...
67,783,342
67,783,643
How to create a multi-dimensional container by another different type multi-dimensional container?
I have a 2D container whose first dimension is deque, and second dimensional is vector. How to translate it to the new container whose first and second dimensional is the same vector ? vector<deque<int>> v1; vector<vector<int>> v2{v1}; //error vector<vector<int>> v3(v1.begin(),v1.end()); // error /* the different...
Yes, std::transform: std::vector<std::vector<int>> v3; v3.reserve(v1.size()); std::transform(v1.begin(), v1.end(), std::back_inserter(v3), [](const auto& d) { return std::vector<int>(d.begin(), d.end()); });
67,783,768
69,163,348
using generated staticEXIOptions.c using exipg utility
I am using exipg utility from exip for generating EXI grammar definitions for schema-enabled EXI processing. Since my schema is static I have used static option. exipg −static −schema=EXIOptions−xsd.exi staticEXIOptions.c Question is How I can use the generated staticEXIOptions.c? I could not find any example in examp...
I could add the generated file to my build system and use it. We need to pass EXIPSchema object present in generated file to parse.setSchema() while parsing.
67,783,980
67,786,936
std::thread helper class to add thread name and stack size
I would like to make a helper class (or subclass of std::thread) to allow stack size to be set and also thread name. If the thread is running on a platform, which does not support e.g. stack size, the number should just be ignored. I was thinking of a "ThreadHelper", which has the extended constructor interface, and ju...
Here is what you could do: You need a wrapper around your thread start function so that you can call the appropriate functions before (and possibly after) your thread function is running. It might also be a good idea to include a try-catch block and do some error processing. template <typename ThreadStartFnc> struct Th...
67,784,050
67,784,625
Compiling C files along with C++ file in g++
I'm having a custom C header file that I have created. There are several files in my directory as follows. lib1/ -lib1.h -lib1.c lib2/ -lib2.h -lib2.c -lib_main.c -lib_main.h -main.c -main.cpp -Makefile Now, for testing the header file with a test file called main.c, I will be giving the following ...
You should (and most probably must) compile separately the c and c++ sources into a object file, and then link together. As an example gcc -c -o lib1.o lib1/lib1.c gcc -c -o lib2.o lib2/lib1.c gcc -c -o lib_main.o lib_main.c g++ -c -o main.o main.cpp g++ -o main lib1.o lib2.o lib_main.o main.o The first four commands ...
67,784,928
67,785,259
How do I optimize my OpenGL textures for Remote Desktop/ANGLE?
I display a 2D texture in OpenGL using Qt. Unfortunately I have found out that I need to support running my application via Remote Desktop to a Windows 7 PC. In this case I need to use OpenGL ES 2.0 API (ANGLE). Due to low bandwidth my 2D visualization seems to be lagging. My texture may have higher resolution than the...
I feel multiple terms are confused here: RDP just transfers the entire remote desktop for you whatever is on it, so no "OpenGL calls are executed in software locally". Hence, unfortunately it will not help if you reduce the texture size in your app, even if you remove it entirely (try it). RDP is not really suitable fo...
67,785,035
67,791,188
Shared library vs. opening a process performance
I have a certain base of Python code (a Flask server). I need the server to perform a performance-critical operation, which I've decided to implement in C++. However, as the C++ part has other dependencies, trying out ctypes and boost.python yielded no results (not found symbols, other libraries even when setting up th...
If you're struggling with creating binding using Boost.Python, you can manually expose your API via c-functions and use them via FFI. Here's a simple example, which briefly explains my idea. At first, you create a shared library, but add some extra functions here, which in the example I put into extern "C" section. It'...
67,785,205
67,785,722
C++ program only prints fixed random numbers/letters to the output.txt file
This is my code, I'm new to C++, whenever I output anything to the output.txt file I only get random numbers/letters regardless of what I try to output Screenshot here now this problem was not present until I tried to copy a string last night, but back then when I printed the initial string it would get printed normall...
Lets print "hello world" as both characters, and as numbers (in hex format): #include <string> #include <iostream> int main() { std::string bla = "hello world"; for (auto c : bla) std::cout << c << ' ' << std::hex << +c << '\n'; } Output: h 68 e 65 l 6c l 6c o 6f 20 w 77 o 6f r 72 l 6c d 64 More re...
67,785,374
67,792,186
Minimal awaitable example
I wonder why the following programme crashes. How to use awaitable not with boost::asio::async_write/async_read functions. Let's see: #include <iostream> #include <boost/asio/io_context.hpp> #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> using boost::asio::io_context; using boost::asio::co_spaw...
digging into the sources of boost::asio::awaitable, I figured out that I just should make use of co_return keyword. Surprisingly, it is not shipped with boost. It is enabled either by -fcoroutines flag or -std=c++20. Unexpectedly. Having said that, it is solved.
67,785,956
67,786,104
Class function does not take arguments
I am trying to simulate some plasma physics and for that I decided to create my "Simulation world" as a class, defined in "World.h" file: #ifndef _WORLD_H #define _WORLD_H class World{ public: World(int _Nx, double _x0, double _xf); //Constructor prototype int _Nx; //Number of nodes ...
I think that the problem is that you are calling member function of a defined class instead of an object. To fix that, I would try putting: World world(1000,0.0,0.1); //(Nx,x0,xm) world.setTime(world._dx, 10000); This way you are calling an object that you have defined as "world" of type World.
67,786,062
67,786,286
Static variable destructor
i am wondering why if i have code like this: class Test2 { public: Test2() { std::cout << "TEST2 Constructor\n"; } ~Test2() { std::cout << "TEST2 Destructor\n"; } }; class Test { public: static Test2& get() { static Test2 test{}; return test; } }; int main() { auto test = Test::get(); std::cout << "Cr...
Destructor is being called 4 times as there are 4 objects that got created. This statement auto test1 = Test::get(); calls the copy-constructor of Test class. You can verify by having a copy constructor with cout statement. auto resolves to Test not Test&. If you want to get the reference of the object, it has to be sa...
67,786,215
67,786,270
What changed introduced C++20 enables us to omit the comparator argument in container's constructor?
In C++17, the following code fails to compile, and we need to provide an argument for sets constructor in order for it to compile: #include <iostream> #include <queue> int main() { auto comp = [](int l, int r) { return l > r; }; // fails, needs comp as constructor argument auto set = std::priority_queue<i...
Since C++20 lambdas like that (with no captures) are default-constructible. What's more, they can be used in unevaluated context: #include <queue> int main() { auto set = std::priority_queue<int, std::vector<int>, decltype([](int l, int r) { return l > r; })>(); }
67,786,222
67,787,290
C++ type trait with volatile
I am trying to understand the following type trait which checks whether T is from the type container or derived from such type. My question relates to aux_iscontainer and its argument. Why does it need to have the CV qualifier in front of the argument.? Why do we even need to pass a pointer to the type and not just the...
Why does it need to have the CV qualifier in front of the argument.? One of the standard implicit conversions is adding cv qualifiers to an expression, so const volatile T* can bind to any of T*, const T*, volatile T* and const volatile T*. Why do we even need to pass a pointer to the type and not just the type itse...
67,786,389
67,786,637
No matching function for to call operator ++ overloading
I'm trying to overload the increment operator++ in my class But it tells me no matching function for call to person::person(int&). The error occurs at line 22 here is my header file #include <string> class person { private: std::string name; int age; public: //Setters void set_name(std::string name_set)...
The postfix increment is supposed to increment this and return the value before the increment. You get the error because there is no constructor for person taking an int. You can fix that by: person operator++(int) { person temp{name,age}; age++; return temp; } Though better would be to provide a copy cons...
67,786,522
67,787,270
c++ read file in binary mode into object failed but is ok in stdin and file read in text
It may be a easy problem... the method read in stdin or file read in text has been proved be right. Things go wrong in binary read. Here I have a class named Laptop and a file named laptop.txt, which is written by the code followed. I have reloaded the >> and << using namespace std; class Laptop { private: string ...
You have a class consisting of four strings and an int, and you cast a pointer to it to a character pointer and try to read it in binary mode from a text file. A string consists of a length and a pointer. The pointer is pointing to a variable-sized block of memory containing characters. sizeof returns the size of the l...
67,786,850
68,045,285
Calling a Kotlin function asynchronously from C++ with JNI
I'm trying to call the function initializationCallback which is implemented in the Kotlin class NativeConnector from C++. I read that I first need to attach the current thread to the JVM, since the thread this code is executed from was not created by the JVM. The attaching itself seems to be working/is not generating a...
Answered by Michael in a comment: Calling FindClass from a thread that you've attached yourself can be problematic. One solution to this is to resolve all necessary class references at startup (e.g. in JNI_OnLoad) and save them as global references for later use. See https://developer.android.com/training/articles/perf...
67,787,519
67,791,015
wxWidgets GridSizer puts all buttons in the same position
I'm learning wxWidgets and am trying to make minesweeper using wxButtons. I use the following code to create and position the buttons: int length = 10; wxGridSizer *grid = new wxGridSizer(length, length, 0, 0); wxButton *buttons[length*length]; for (int i=0; i<length*length; i++){ buttons[i] = new wxButton(this, ...
To make the grid sizer layout the buttons, you need to either set it to be the sizer for a window or add it to another sizer. Assuming the code above is from the constructor of your main frame window, you would set grid to be the sizer for the frame like this SetSizer(grid); On the other hand, if you have other cont...
67,787,770
67,791,352
Unicode in wxWidgets
I'm creating a calculator application in C++ wxWidgets using Visual Studio 2019. I have created a custom button class that I want to use for all mathematical operations and symbols. How can I set the button's label to √ instead of sqrt? If I do that, a ? symbol is displayed instead. I also need to display these symbol...
For a single character, you can just use wxUniChar. You create a wxUniChar with a value in hexadecimal of the Unicode code point for the desired character. Since the Unicode code point of the square root character is U+221A, you can create a wxUniChar for this character like so: wxUniChar c(0x221A); wxUnichar is imp...
67,787,920
67,789,410
Narrowing conversion error using newer compiler
I'm trying to compile my code on a new system, and I'm suddenly running into trouble with one of my older libraries. This is an example snippet of the code that is causing the issue: int main() { static const unsigned char pad_block[8] = { '\x80', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}; } I'm ...
Why does this issue suddenly appear, without specifying a new C++ version? Newer releases/versions of the 'same' compiler quite often have stricter requirements (in terms of conformance to the C++ Standard) than earlier/older ones. This appears to be so in your case. Where does the number '\37777777600' come from? ...
67,788,190
67,788,468
Test for new id combinations in R
I am looking to create an indicator that checks whether the a group takes new combinations of numbers or not. I have a dataset like this one: combinations <- data.frame(combination_id = c(1, 1, 1, 1, 2, 2, 2, 3, 4, ...
dplyr approach: require(dplyr) combinations %>% dplyr::mutate(new_combination = !duplicated(number)) %>% group_by(combination_id) %>% dplyr::mutate(new_combination = as.numeric(any(new_combination))) %>% ungroup() combination_id number new_combination <...
67,788,395
67,789,167
How do i use the fixed sized integers from 'cstdint' lib to store/pack bit data sequence with maximum length of 250MB? Why to not use normal int?
In the condition of the task that I am doing, I am specifically told: "Integers in C++ do not have a fixed size. To access integers with a fixed size, you can use the library cstdint." I take it it is recommended that I use fixed-sized integers for packing of bit data (max 250MB). I am failing to understand how does fi...
Integers in c++ are not fixed size in that they can have different sized based on arch or other environment variables (OS, compiler, etc.) The library cstdint exposes data type that are guaranteed to be fixed in size, for example the type int8_t is guaranteed to be 8 bit long, and you can use uint8_t to read/write your...
67,789,845
67,826,161
how to make text vertically centered in wxStaticText?
How can I make the text vertically centered in wxStaticText (single line) in cpp Windows using WxWidget? For example if I increase the height of wxStaticText (single line) with default font size, the text is align at top, I want it to be at center vertically.
I don't think text controls support vertical text alignment styles. As far as I know, if you want to create a text control where the text is vertically centered, the only way is to fake it. This can be done by creating a borderless text control and then center that text control inside another window whose only purpose ...