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
73,118,484
73,118,668
CMake Compiler not set
CMake Error: CMAKE_Project_COMPILER not set, after EnableLanguage I Get this Error after writing cmake .. This is my CMakeLists.txt set(CMAKE_CXX_COMPILER "C:/mingw64/bin/g++") set(CMAKE_C_COMPILER "C:/mingw64/bin/gcc") project(CXX Project) add_subdirectory(glfw/) add_executable(${PROJECT_NAME} Main.cpp) target_inc...
You're using the project command in the wrong way. It should be project(Project CXX) That's why CMake is looking for CMAKE_Project_COMPILER instead of CMAKE_CXX_COMPILER.
73,118,892
73,118,972
How to set a specific size to the QPixmap and keep content in the same position and the same size?
I only want to resize the QPixmap, not the content.
QPixmap newPixmap(newWidth, newHeight); newPixmap.fill(Qt::black); // or the color you like... maybe you want Qt::transparent? QPainter painter(&newPixmap); painter.drawPixmap(0, 0, oldPixmap);
73,119,206
73,123,827
Proof that user compressed public key corresponds the curve equation (secp256k1)
I am trying to check if some compressed public key corresponds to an elliptic curve equation (secp256k1). As far as I know it should be valid once the following equation is fulfill y^2 = x^3 + ax + b or y^2 % p = (x^3 +ax +b) % p. Supposing that I have the following key: pubkey = 027d550bc2384fd76a47b8b0871165395e4e4d5...
For the compressed key 027d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60ef the uncompressed representation is 047d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60effbb6217403fe57ff1b2f84f74086b413c7682027bd6ddde4538c340ba1a25638 i.e. x = 0x7d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c...
73,119,624
73,120,236
Want to create a variable of datatype "Struct", and control (Array Size) of its sub element from outside
I want to feed SIZE externally while declaring a variable of datatype "Struct" . Basically I want to use this datatype with different size. struct ArrStruct final { std::array<float32_t, SIZE> Arr1; std::array<float32_t, SIZE> Arr2; }; struct Type1 final { ArrStruct var4; float32_t va...
You can make SIZE a template argument: template <size_t SIZE> struct ArrStruct final { std::array<float32_t, SIZE> Arr1; std::array<float32_t, SIZE> Arr2; }; template <size_t SIZE> struct Type1 final { ArrStruct<SIZE> var4; float32_t var5; }; template <size_t SIZE> struct StructData final ...
73,119,625
73,135,342
How to signal a class that some HTTPServer request was received?
I want to extend an existing application with a simple REST server and a dedicated UDP client for streaming data to a UDP server. The REST server should manage the UDP client based on the API requests and have access to classes in the hosting application. I want to create a new class in the hosting application so I can...
Is it a good practice to inherit HTTPServer and extend it with the above behavior (that way I may have simple access to the requests)? I don't recommend that. Create a standalone class, hold a reference to it in the request handler factory, pass the reference to each request handler, and do the required work at the r...
73,119,847
73,128,154
Qt attribute(property) binding to QLabel
Hi I'm pretty new in Qt. Can I binding class attribute(or property) to QLabel text? For example, class Dog{ string name; } QLabel lbl; When I change dog's name, I'd like to change lbl.text
In Qt things that you are talking about are the territory of signals and slots. Good way to do: Dog.h: #ifndef DOG_H #define DOG_H #include "QObject" class Dog: public QObject { Q_OBJECT public: void setDogsName(const QString &name) { m_Name = name; emit dogsNameChanged(name); } signal...
73,119,852
73,120,182
New C++11 for loop causes "error: ‘begin’ was not declared in this scope" using it for an struct with array
I'm having a struct with an array which is static and want to access the data in that array. Tried to use the new C++11 for loops and also do it without the for loop and just print array[1]. See the second cout in the main function. I already know that the problem have to do something with the fact that the array in th...
Range-based for loops need to have access to the bounds of what you're iterating. As noted on the relevant cppreference page, there are three ways: It is an array of known size (which is the case for your dataset1 member) my_struct::begin() and my_struct::end() are defined begin(my_struct&) and end(my_struct&) are def...
73,120,076
73,131,517
C linkage function cannot return c++ class when converting cpp to dll
After following some simple tutorial, I want to convert my cpp program to a dll file, however, it return several errors, like C2526'split':c linkage function cannot return c++ class 'std::vector<std::string,std::allocator<std::string>>' C2371'split':redefinition;different basic types C2491 'split':definition of dllimp...
About C calling C++ DLL, you need to pay attention to the following points: 1.The C++ function interface for C calls cannot contain C++-specific things. 2.When compiling a dll called by c code, extern "C" should be added before the function declaration in the header file to tell the compiler to process the function nam...
73,120,143
73,121,228
Recompile C++ binary from debug info
This is more out of curiosity than productive need but I have been asking myself if it is possible to extract the C++ source of a binary such that it can be recompiled to produce a working clone of the binary. If have tried to: compile the binary with "-g -Og" to include dwarf info, used objdump with "-S" and "--sourc...
Debug symbols contain a lot of information that allows you to map stuff from the binary back to the source code (assuming you have access to both) especially in unoptimized builds. But extracting/recreating the original source exactly from the compiled binary is simply not possible.
73,120,244
73,120,374
passing an object as a parameter to a constructor of another class C++
I'm trying to make a user interface class for display the weather forecast retrieve from an API, using a Nokia5110 LCD, but I'm getting an error when I try to pass a reference to an Adafruit_PCD8544 Object from the .ino to the constructor of the class. Some help will be highly appreciated. The error i get: "error: no ...
Members are initialized before the constructor body is executed. The constructor body is not the place to initialize members. If you do not provide an initializer, the member display will be default constructed. The error says Adafruit_PCD8544 has no default constructor. Use the member initializer list: UI_Nokia5110::U...
73,120,702
73,162,413
Why DACL entries of a file printed via win32 API is not matching up with DACL information in the file properties?
Here is the minimal code for reference ULONG result = GetSecurityInfo(Hfile , SE_FILE_OBJECT , OWNER_SECURITY_INFORMATION |GROUP_SECURITY_INFORMATION| DACL_SECURITY_INFORMATION , &sidowner , &sidgroup , &pdacl , NULL , &psd); This is how I extracted the access ...
The first part of the question: The reason why the program prints the name same account name repeatedly is because the LookupAccountSid function does not have enough data area. since the namelen and domainlen are IN\OUT arguments the function returns the size of the domain name and account name every time after executi...
73,121,138
73,122,039
C++ string dynamic 2D array cause memory leak
When I use a string type dynamic 2D array, there is memory leak after deleting the array. Please view the following code: #include <string> using namespace std; #define NEW2D(H, W, TYPE) (TYPE **)new2d(H, W, sizeof(TYPE)) void* new2d(int h, int w, int size) { register int i; void **p; p = (void**...
The problem with your code because it treats non-trivial types like std::string as if they were trivial. Probably you could create something using placement new that was legal C++ and worked in a similar way to the code you've written But here's an simple alternative that (hopefully) works template <typename T> T** new...
73,121,385
73,123,246
How to pass std::index_sequence param to an nested-template struct according to function traits
Here is my simple code and it did work (I passed single integer to argument): #include <iostream> #include <tuple> #include <string> #include "boost/variant.hpp" using TObjList = std::vector<boost::variant<std::string, int>>; template<typename> struct FTrait; template<typename R, typename... A> struct FTrait<R(A...)>...
In your case, typename FTrait<F>::argument<0>::type is const std::string&. std::get<const std::string&>(list[0]) won't compile you need std::get<std::string>(list[0]). It might be solved with std::decay: template<typename F, size_t... Index> void MyCall(const F& Func, const TObjList& List, const std::index_sequence<I...
73,121,967
73,122,245
How to remove an item from a list of tuples in c++?
I'm iterating over my list of tuples : list<tuple<int,int>> edges, and want to remove some elements in it. This is necessary for me to reduce the total overhead as I am working with huge data. std::list<tuple<int, int>>::iterator it; for (it = edges.begin(); it != edges.end(); ++it) { if (get<0>(*it) == 0 || get<1>...
In C++20, you can simply use a specialization of std::erase_if for std::list to do this. #include <list> #include <tuple> int main() { std::list<std::tuple<int, int>> l; std::erase_if(l, [](const auto& elem) { auto& [first, second] = elem; return first == 0 || second == 0; }); } Demo However, since std::l...
73,122,040
73,122,076
C++ Is it safe to modify a int64_t when reading it from another thread?
I have 2 threads, A and B. Thread A want to let B know how many records of data it has received. In modern C++, we can use Atomic or CAS or Mutex to modify the counter. How ever, neither of them is fast enough for me. I am thing about, use a int64_t without a lock to share data counter between threads. Only thread A ca...
No, it's undefined behavior. Make it a std::atomic<int64_t>, instead. This is what std::atomic is for.
73,122,400
73,122,845
How to make a template class that force it's child class to extends itself?
I would like to know the C++ equivalent of the following Java code. public Class MyClass <T extends MyClass<T>> {...} I have tried the following but failed using C11: template <class T> class Parent { static_assert(std::is_base_of<Parent<T>, T>::value); public: T* next; }; class Child: public Parent<Child> { ...
Unfortunately, within CRTP, T is an incomplete type (so most traits won't work on it). You might add the check in a member instead (type would be complete at that point). Good candidates are constructor and destructor: template <class T> class Parent { // T is incomplete here. public: ~Parent() noexcept { ...
73,122,595
73,122,807
Visualize the Result of a Hough Transformation
I am currently programming a laser 3D-sensor which provides me with edge points (X,Y,Z) in a 2D array as a result. The coordinates are used to perform a Hough-transform. The result in Rho and Theta is output to my console.My question now is whether I can visualise this result, to check for correctness. I have thought o...
You can draw your points in an OpenCv image as a contour , then apply Hough transform as follow: cv::Mat dst; cv::drawContours(dst, contours, -1, cv::Scalar(0, 255, 0), 2); // contours is your 2D vector) vector<Vec2f> lines; // will hold theta and rho HoughLines(dst, lines, 1, cv::CV_PI/180, 150, 0, 0 ); for( size_t...
73,122,646
73,122,779
Initializing a std::shared_ptr<std::random_device>
I understand that std::random_device is non-copyable. In this scenario, I have a std::shared_ptr<std::random_device> that I want to init in one of the member functions of the class. I assumed std::move would work. I was wrong. Would somebody explain what the 'proper' way to init the same is ? Note : std::random_device ...
You seem confused about the syntax. This is not valid C++: std::random_device rng = std::make_shared<std::random_device> (std::random_device); It looks somewhat like you were trying to do this: std::shared_ptr<std::random_device> rng = std::make_shared<std::random_device> (std::random_device{}); That would buil...
73,122,708
73,125,400
cmake generator expression for target architecture?
Is there a modern approach to use target architecture within a condition for a generator expression in CMake? There are some answers that are somewhat outdated. I am looking for a modern or at least very robust and reliable custom script for using target architecture within a generator expression. The docs do not seem ...
I checked a solution from this answer and it worked. cmake_minimum_required(VERSION 3.14.2 FATAL_ERROR) project(cmake_target_arch) set(CMAKE_CXX_STANDARD 17) include(TargetArch.cmake) target_architecture(TARGET_ARCH) message(STATUS "target_architecture: ${TARGET_ARCH}") add_executable(cmake_target_arch main....
73,122,891
73,126,434
How to pass structure with template variable as an argument inside member function of class in c++?
I would like to pass 'structure with template variable' as an argument inside member function of class. I am getting error "no matching function for call to". Can anyone help me? I am doing some mistake either in declaration / definition / while passing argument from the main. template <typename T> struct msg_1{ int...
Your template function A::test is only templated with one type T and requires that both parameters have the same type T*. In your example you pass different parameters: msg_1<int> * and msg_2<int> *. If you really want test to only accept two parameters with identical type, then you can't pass ob_1 and ob_2. If you wa...
73,123,672
73,148,315
Is it possible to cross-compile C++ applications from Linux for Windows XP?
I have a simple console application which I already ported to Windows. I also cross-compile it using mingw. However the problem is applications compiled like this only run on Windows Vista or newer. How would I go about compiling it for XP using Linux? Also, I don't know if this is necessary, but here are my compiler f...
You to use a version of MinGW-w64 that was built with configure flags --with-default-msvcrt=msvcrt-os and --with-default-win32-winnt=0x0501. These flags will result in MinGW-w64 libraries that will only use Windows features available up to Windows XP.
73,124,077
73,124,390
Why do DLLs have a private section?
Based on what I've read about exporting symbols from a DLL in Microsoft's documentation, you can tell the linker to not include a symbol in the .lib import file by appending the PRIVATE keyword to the export. This, in effect, hides that symbol from application code that uses the library. My question is, doesn't the C++...
static and PRIVATE (wrt. DLLs, similar to -fvisibility=hidden for Linux DSOs) are two different concepts. The C++ standard as such is agnostic to DLLs and its implementations on different operating systems. static is applied on a translation unit (TU) level, i.e. it restricts the visibility of a symbol (function/variab...
73,124,165
73,124,234
How to convert a char16_t into a stringstream divided with 2 bytes
I made a utf8 to utf16 conversion where i get the code units for the utf16 char16_t. { std::string u8 = u8"ʑʒʓʔ"; // UTF-8 to UTF-16/char16_t std::u16string u16_conv = std::wstring_convert< std::codecvt_utf8_utf16<char16_t>, char16_t>{} .f...
A straightforward way is adding each bytes to std::stringstream using a loop. std::stringstream ss; for (char16_t c : u16_conv) { ss << (char)(c >> 8); ss << (char)c; } std::string str = ss.str(); for (char c : str) { std::cout << std::hex << std::showbase << (int)(unsigned char)c << ' '; }
73,124,199
73,129,656
static object calls constructor at wrong time
I have an opengl batch renderer, which has a static vao, vbo, ebo etc. problem is, int the constructor of those are opengl methods. now, because they are static the opengl methods like glGenBuffers get called before opengl has been initialized. so you can get a better picture, this is how it looks: class renderer2d { ...
One trick is to delay initialisation of the object like this: renderer2d& get_renderer() { static renderer2d renderer; return renderer; } This method works for any class, it does not require the renderer itself to have static data. The function can also be a static member of the class, as part of the Meyers si...
73,124,745
73,124,795
Convert integer to binary string with variable size
Suppose I want to get every combination of 1's and 0's with length n. For example, if n = 3, then I want 000 001 010 011 100 101 110 111 My initial thought was to use something like: #include <iostream> #include <bitset> #include <cmath> int main() { int n = 3; for (int i = 0; i < pow(2, n); i++) std::cout <<...
A straightforward way: Extract each bits using bitwise shift operation. #include <iostream> int main() { int n = 3; for (int i = 0; i < (1 << n); i++) { for (int j = n - 1; j >= 0; j--) { std::cout << ((i >> j) & 1); } std::cout << '\n'; } return 0; } Note that this...
73,124,815
73,149,655
Elegantly switching template arguments for a set of functions
I am writing some code that uses an external library, where several functions are defined approximately like this: // Library.h template<typename T> void foo(int arg1, bool arg2); template<typename T> int bar(float arg); (examples are given to illustrate that both argument lists and return value types are diverse, b...
First of all, it's clear that there is no 100% elegant solution because you can't really do anything with function templates except instantiating them. You can't abstract over them whatsoever. So at least a small amount of boilerplate code for every function template is required. But I think lambdas provide a neat way ...
73,124,846
73,133,536
Month auto increment using mktime and timegm functions in C++
I'd like to convert a string date (UTC) to a timestamp using C++. It works fine except for the month, which is auto incremented by one. If the string is 20221222074648, for 2022-12-22 07:46:48, the timestamp will be 1674373608, which is the timestamp of 2023-01-22 07:46:48. I don't understand the reason of this auto-in...
Your problem is pretty simple ! the tm.tm_mom goes from 0 to 11, You need to add -1 on your month value t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10) - 1;
73,125,259
73,142,379
Need advice on adding test framework (GoogleTest) to a .cpp file having main() function
I am a beginner at testing in CPP and this is my first testing project. I have written a code in CPP and I have to add test cases using any test framework, for which I have decided to use GoogleTest after learning on the internet that it is the most popular and beginner friendly. My .cpp file looks like this... #inlcu...
One way is to create these files: func.h: in which you just put declarations of your functions. Example: // Only function declarations: void read_input(); void print_output(); func.cpp: in which you put the implementation of your functions. This would be similar to what you have but without the main function. This ...
73,125,275
73,125,474
Why do I get this error in Clang? "constexpr if condition is not a constant expression"
I am trying to compile a class using Clang: #include <string> #include <type_traits> #include <cstdlib> struct foo { template <class T, class... Ts> struct is_any: std::disjunction <std::is_same <T, Ts>... >{}; template<typename T, std::size_t N> static constexpr bool is_pointer_to_const_char(T(&)[N])...
Did I do something wrong in the class method's definition? The problem is that function parameters (like str) are not constant expressions. For example, we cannot use str as a template non-type parameter, or as a size of a built-in array. This means the expression is_str( str ) that contains the subexpression str is ...
73,125,825
73,126,069
Is it correct to define a global static const std::string in a header file
Is it correct to define a global std::string in a header file like this : namespace Colors { static const std::string s_blue = "Blue"; }
Correct? Yes. static here means that each translation unit (TU) that includes this header will have a unique object. So there isn't 1 s_blue object for the whole project, but one for each TU. However since it's const all objects will be equal, so for the user it doesn't make a difference. Recommended? Maybe, depends. T...
73,125,934
73,126,171
Binary files: write with C++, read with MATLAB
I could use your support on this. Here is my issue: I've got a 2D buffer of floats (in a data object) in a C++ code, that I write in a binary file using: ptrToFile.write(reinterpret_cast<char *>(&data->array[0][0]), nbOfEltsInArray * sizeof(float)); The data contains 8192 floats, and I (correctly ?) get a 32 kbytes (8...
Leaving aside the fact there seems to be some precision difference (likely the display settings in MATLAB) the issue here is likely the difference between row major and column major ordering of data. Without more details it will be hard to be certain. In particular MATLAB is column major meaning that contiguous memory ...
73,126,558
73,126,835
How should I use thread_pool in this case?
for example: when I write this code I recieve right result. boost::asio::thread_pool t(3); std::vector<int> vec = {10,20,30}; boost::asio::post(t, [&]{ foo(vec[0]);}); boost::asio::post(t, [&]{ foo(vec[1]);}); boost::asio::post(t, [&]{ foo(vec[2]);}); t.join(); but when i want use boost::asio::post in for-cicle i reci...
You are capturing i by reference for a lambda that is used asynchronously. When t.join(); is reached, i is a dangling reference. Capture it by value so it doesn't change or expire. boost::asio::post(t, [&,i]{ foo(vec[i]);});
73,126,584
73,127,017
Writing single-char vs. char const* to buffer
When writing single characters to an output stream, the purist in me wants to use single quotes (e.g.): unsigned int age{40}; std::ostringstream oss; oss << "In 2022, I am " << age << '\n'; // 1. Single quotes around \n oss << "In 2023, I will be " << age + 1u << "\n"; // 2. Minor ick--double quotes around ...
As you can see in the assembly and in the libc++ source here, both << operations in the end call the same function __put_character_sequence which the compiler decided to not inline in either case. So, in the end you are passing a pointer to the single char object anyway and if there is a pointer indirection overhead it...
73,126,697
73,128,568
Getting error outputs due to using ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); in the code
In this code below the ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); statement seems to be causing some problems. I tried with different variation like ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); or ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); For these test cases : 5 5 apple 15 schtschurowskia 6 polish 5...
You're explicitly unsyncing the standard C++ streams and the standard C streams, but then mixing them in your code. Switch the scanf with cin.
73,126,760
73,127,141
Initializing distributions for use across class methods (C++)
I am trying to make a class that has a set of rng distributions as class attributes, with class methods having access to these distributions. Trying to follow the example in the documentation, I've distilled the problem to the following mwe. The code returns the errors member "A::rd" is not a type name and no instance ...
The code line: mt19937 gen(rd()); is ambiguous. I get that error message with GNU C++ v11.3: q73126760.cpp:14:17: error: 'rd' is not a type 14 | mt19937 gen(rd()); | ^~ q73126760.cpp: In constructor 'A::A()': q73126760.cpp:22:59: error: invalid use of non-static member function 'std::m...
73,126,915
73,126,965
Iterating through a 2D vector using one use case of for loop gives segmentation fault
I needed to write a simple method that calculates the highest element in a matrix data (implemented in this case using a 2D vector). Inside the method, initially, I was accessing each element in the 2D vector using the one form (the most common one) of for loop which gave a "segmentation fault". Unfortunately, I could ...
I believe it may be because in the inner loop you have for(int j=0;i<accounts[i].size();++j) when it should be for(int j=0;j<accounts[i].size();++j){
73,127,178
73,173,302
How to force GDB to start number breakpoints at 1
How can I force GDB to start its numbering of newly added breakpoints at 1, after I have deleted all breakpoints with the delete command? I'm using this version of GDB: GNU gdb (GDB) 8.0.50.20171024-git TL;DR Rationale During complicated debug sessions, I have a separate command file that I use the source command to so...
Given your use-case described in your rationale, you're probably best off not trying to get the breakpoints assigned to specific numbers and instead use convenience vars to keep track of the breakpoint numbers. Whenever you set a breakpoint, gdb will set $bpnum to the number of the breakpoint. You can save that value ...
73,127,253
73,128,313
Does split_regex support group?
Can I setting split_regex working based on groups instead of using lookbehind? The code I'm using is as follows: string data = "xyz: 111.222: k.44.4: 12345"; vector<string> data_vec; boost::algorithm::split_regex( data_vec, data, boost::regex("(:\s*)\d")); my expected result is: xyz 111.222: k.44.4 12345
In case you are open to other solutions, one using std::regex would be: Loop searching for a :\s* separator. Keep a vector of tokens. Push back the first token and any token that starts with a digit. For tokens not starting with a digit (other than first one), add them to the last element of the container (together wi...
73,127,302
73,127,412
Append vector to itself?
I'm trying to cloning the vector itself, for example if the vector is [2,3] it will become [2,3,2,3]. This is my program: #include <iostream> #include <vector> using namespace std; int main() { vector<int> a; a.push_back(2); a.push_back(3); for(int i: a) { a.push_back(i); } ...
Range-for is syntactic sugar for an iterator-based for-loop, and std::vector::push_back() can invalidate iterators like the ones being used internally by the range-for: If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only t...
73,127,632
73,127,758
find_if is not returning the expected output
I am using find_if() to find the next higher value in a vector. It is returning the next index and not a higher value. The input vector is: vector<int> height = { 1,8,6,2,5,4,8,3,7 }; I am looking for the next highest value, starting at i=0, height[0] = 1. The code updates to set i=1, height[1] = 8. I expect to get i=...
Your lambda should look like this [&height, i](int x) { return x >= height[i]; } find_if passes the value of each element of the given sequence to the predicate. Not the index of each element.
73,127,939
73,128,120
Any way to check count of template parameters at compile time?
Is there any way to check number of template parameters and compile time? I would like to do this (this is not real code): template<typename... Types> class Foo { // Enable this if count of 'Types' is 1. Types[0] Bar() { return Types[0]{}; } // Enable this otherwise. std::variant<Ty...
One option is to add a template parameter and then leverage constexpr if to check if the pack is empty or not like template<typename first_t, typename... rest_t> class Foo { auto Bar() { if constexpr (sizeof...(rest_t) == 0) return first_t{}; else return std::variant<firs...
73,127,942
73,128,396
Overloaded method resolution for variadic tuples displays strange results
I'm getting strange and unexpected results for this code: https://godbolt.org/z/8vs87vcKK #include <string> #include <iostream> #include <tuple> using namespace std; struct Foo { template < typename ... t_Tys > static void foo( tuple< t_Tys ... > const & ) { cerr << "foo()\n"; } template < class ... t_T...
The first template is using cerr, while the others are using cout. Since you used '\n' instead of endl to end the line, your output is not immediately flushed. This is reordering your output. Fixing this, the first output becomes: foo( string ) foo() foo() foo( string, int ) [1] The first foo() does indeed result in f...
73,128,622
73,129,801
How to run function after delay asynchronously in C++
I want to implement something like Java's TimerTask in C++. I want to use it for invoking functions sometimes, not periodic. For periodic launching it will be a good idea to implement "event loop" scheme with 2 threads, with creating tasks in the first thread and process it in the second. But I do not want to write muc...
template <typename F, typename... Args> auto timed_run(const uint64_t delay_ms, F&& function, Args&&... args) { std::packaged_task<void()> task([=]() { std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); function(args...); }); auto future = task.get_future(); std::thread(std::move(task))....
73,129,254
73,129,679
Parameter pack constructor preferred over other constructor calls
Consider a constructor accepting a parameter pack, such as template<typename First, typename... Rest> consteval explicit foo(const First& first, const Rest... rest) : arrayMember{first, rest...} { } where First and Rest... all have arithmetic types, And another, different constructor that takes t...
Assuming an implementation similar to this: template <typename T, std::size_t Size> class foo { private: T _vector[Size]{}; public: using size_type = std::size_t; // .. other constructors .. explicit foo(size_type lower, size_type higher) { // (1) // ... } template <typename St...
73,129,264
73,129,515
Generic way to select a map based on data type of key
I have a few disjoint maps which map unique types to strings. For example: enum class Colors {RED, GREEN}; enum class Days {MON, SUN}; std::map <Colors, std::string> map1{ {Colors::RED, "red"}, {Colors::GREEN, "green"}, }; std::map <Days, std::string> map2{ {Days::MON, "mon"}, {Days::SUN, "sun"}, }; ...
In C++17 and later, you can use if constexpr, eg: template <typename T> auto extractValue(T k){ if constexpr (std::is_same_v<T, Colors>) { return map1[k]; } else if constexpr (std::is_same_v<T, Days>) { return map2[k]; } return std::string{}; } Otherwise, you can use template specia...
73,129,518
73,129,793
Inconsistent implicit conversion behavior
I encountered a case where I cannot understand the implicit conversion behavior in c++. The code is the following: template <bool b, int i, unsigned... us> void foo() {} template <int i, unsigned... us> void foo() {return foo<false, i, us...>();} int main() { foo<true, -1, 0ul, 1ul, 2ul>(); // compiles with clang...
A non-type template argument is required to be a converted constant expression of the template parameter's type. A converted constant expression specifically does not allow for narrowing conversions, which in the case of constant expression evaluation between integral types means that the conversion is not allowed if i...
73,129,742
73,130,266
Fire base Update c++ / how to detect string in URL
I want to change some Data in my realtime firebase based on the id. I want to customize my Https but it does not work. when i add + id to my URL i got a failure: QNetworkRequest newAdminRequest(QUrl("gymmanagment-a6c01-default-rtdb.europe-west1.firebasedatabase.a…" + id)) – void DatabaseHandler::AddAdmin(QString name, ...
You need to access the 'id' as if it were an 'endpoint', like this: https://gymmanagment-a6c01-default-rtdb.europe-west1.firebasedatabase.app/Admin/-N7pPxSHoPVlyEi8e0xW.json For general case, you can join each part: QString id = "-N7pPxSHoPVlyEi8e0xW"; QString base = "https://gymmanagment-a6c01-default-rtdb.europe-wes...
73,130,012
73,130,310
How do I pass a return value to another function and assign the return value to a variable within that function?
My program consist of 3 files. The clockType.h - the class function prototypes, clockTypeImp.cpp - definitions of functions, and the testing program testClockClass.cpp. I am trying to pass the return value of the first function to the next function in the code below. I think I am supposed to pass it as a reference peri...
clockDiffseconds() is a non-static method that acts on this, calculating the difference in seconds between this and another clock otherClock. That is fine. But secondsToHHMMSS() has no concept of otherClock. It is also a non-static method that acts only on this. So, for secondsToHHMMSS() to be meaningful, you have a ...
73,130,340
73,130,928
How to not break bindings in qml?
I currently have an image which becomes visible or not depending on some steps of a process. The qml code for that image is the following : Image { id : cameraDisplay visible : mainViewModel.getCurrentSegmentIsCameraDisplayed anchors.centerIn : parent source: "Images/Todo.png" } I also have a button, ...
You can change your binding in C++ to emit a signal when a change occurs, like this: Q_PROPERTY(bool getCurrentSegmentIsCameraDisplayed READ getCurrentSegmentIsCameraDisplayed WRITE setCurrentSegment NOTIFY segmentChanged) In your class.h, class MyClass : public QObject { Q_OBJE...
73,130,478
73,130,942
Variadic template: inline pattern expansion
C++ variadic templates can use patterns where you can repeat blocks surrounding the variadic argument, like so: template<typename... Args> struct MyStruct : seq<pair<Other, Args>...> MyStruct<X, Y> // expands to seq<pair<Other, X>, pair<Other, Y>> However, as far as I can tell, all these pattern expansions require (a...
If you fancy doing meta-programming yourself, you can accomplish the behaviour with four utility overloads. Like another answer pointed out, the key is concatenating seq types, so our utilities will do just that. The important thing to understand is that meta-programming is primarily functional in nature, so the tools ...
73,131,354
73,131,439
Redis-protobuf: Err type mismatch seen with protos having nested messages
When there are more than one proto files with nested messages loaded by libredis-protobuf.so, unable to set any fields of the second proto message. Both proto files are proto3 version. 127.0.0.1:6379> PB.SCHEMA Msg "message Msg {\n int32 i = 1;\n .SubMsg sub = 2;\n repeated int32 arr = 3;\n}\n" 127.0.0.1:6379...
Because you've already set key as an object of Msg type. When you try to set key to an object of another type, e.g. Rsg2, it returns error reply: type mismatch. It behaviors like trying to set a key of which the type is HASH. You need to delete the key, and then you can set it to an object of another type. Or just sett...
73,131,430
73,132,491
P/Invoke (DLLImport) Different Function Signature
According to the documentation, when trying to call unmanaged code in my managed code, it should has the exact same function signature as the unmanaged code. I tried putting in a different function signature that I know should not have worked. Original: int Foo(LibraryDefinedString str, _Outptr_ LibraryDefinedHandle * ...
No, there is no warning. How could there be? There is no reflection on the native side, so there is no way for the PInvoke marshaller to validate if the managed side is correct. Either the code works, or the code has undefined behavior that may or may not fail. In any case, your "wrong signature" may or may not be wron...
73,131,471
73,131,528
Does header initialization break RAII?
Consider the following C++ header: #include "OtherThing.h" class Thing { public: Thing(); //ctor private: OtherThing my_var_{}; }; Is the private var my_var_ still managed according to RAII, or does its lifetime exceed the scope of Thing in any way? I searched for a clear answer for a good while, but either ...
Is the private var my_var_ still managed according to RAII, or does its lifetime exceed the scope of Thing in any way? The data member my_var_ is a non-static data member and is associated with a particular instance of class Thing. More importantly, it's lifetime can never exceed the lifetime of the associated Thing ...
73,131,627
73,133,527
Forward and reverse conversions between vector<Eigen::Vector3f> and Eigen::Matrix3Xf
How to convert vector<Eigen::Vector3f> to Eigen::Matrix3Xf ? and inverse operation ? #include <Eigen/Eigen> #include <iostream> #include <vector> using namespace std; vector<Eigen::Vector3f> x{{1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}}; Eigen::Matrix3Xf y; y = x? vector<Eigen::Vector3f> x; Eigen::Matrix3...
Assignment vector to Matrix, use a Map (you need to make sure that x.size()>0): // Works as constructor or assignment: Eigen::Matrix3Xf y = Eigen::Matrix3Xf::Map(x[0].data(), 3, x.size()); The other way around, you can use the iterator interface of Eigen: // Constructor: vector<Eigen::Vector3f> x(y.colwise().begin(), ...
73,131,649
73,131,670
C++ class overloaded operator `()` called in template is not able to change member variable's value
I met a problem when working with templates and overloaded operators in C++. I want to create a class Foo with an overloaded operator (), and I also want to change the value of a private member variable bar_ of class Foo inside the overloaded (), and keep that value for later use. I have to finish this with a template:...
Your function int NodeWalk(T action) takes the parameter by value, which means that the first print from your operator()() is called from a copy, which did alter the value of bar_. But once the function ends, the copy is destroyed. The original object declared in main() is unaltered, which is why you see the original v...
73,131,716
73,131,820
Using private member variable as private function parameter
class C { public: void clearWithParam() { clearImage(image, size); } void clearWithoutParam() { clearImage(); } private: unsigned char* image; size_t size; void clearImage(unsigned char* image, size_t& size) { for(int i=0; i<size; i++) { image[i] = 0; } } void clearIm...
By the rules that govern scope, the function args are given preference over the members of the same name. Since the instance remains accessible, you can still access the member variables via things like this->image. Some people prefer to try and avoid such ambiguity and have established a fairly popular (to the point ...
73,131,777
73,146,722
Is it possible to use ActiveX controls in an SDI application (as opposed to a dialog-based application)?
I'm new to MFC and ActiveX. I'm trying to use a 3rd party ActiveX control in my MFC application. I successfully did it using a dialog-based MFC Application, but it doesn't work if I select 'Single document' when creating a new MFC project(solution) in Visual Studio. 1. How can I use a 3rd-party ActiveX control if I wan...
The easiest way to integrate/support controls (and activeX controls) in your MFC SDI application, is to derive your view class from CFormView. That will allow you to add Win32 and ActiveX controls to your form window, similar to how you did it with a dialog-based application. When you create a new MFC SDI application, ...
73,132,051
73,132,107
C++ Use vector rvalue as an argument
Consider the code snippet below: void PrintLines(vector<string>& lines){} vector<string> lines = {"Images", "Transcriptions"}; PrintLines(lines); Is there a possibility to pass the lines values directly, without initializing the "lines" variable? Like this: PrintLines({"Images", "Transcriptions"});
First things first, you've not specified the return type of the function when defining it. Is there a possibility to pass the lines values directly, without initializing the "lines" variable? Yes, you can do that by making the parameter lines to be a const lvalue reference to std::vector so that it can bind to rvalue...
73,132,267
73,132,313
How to import library in CMAKE download by vcpkg?
I am trying to import a library that i installed using vcpkg (vcpkg install azure-storage-blobs-cpp) In my c++ file I am trying to import azure/storage/blobs.hpp In my vcpkg directory, i have the following file ./installed/x64-osx/include/azure/storage/blobs.hpp ./packages/azure-storage-blobs-cpp_x64-osx/include/azure/...
You need to use: -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]/scripts/buildsystems/vcpkg.cmake while configuring your cmake. You can see full guide here. So you need to first correct your cmake as follows: cmake_minimum_required(VERSION 3.9.1) project(CMakeHello) set(CMAKE_CXX_STANDARD 14) find_package(azure-storage-blobs-...
73,132,597
73,133,364
std::sample() with integer range
How can I pick multiple values randomly in any given integer range? With std::sample(), one possible implementation would be: void Sample( int first, int last, std::vector<int> *out, std::size_t n, std::mt19937 *g) { std::vector<int> in{}; for (int i = first; i < last; ++i) { in.emplace_back(i);...
In C++20 you can sample on iota_view #include <ranges> #include <vector> #include <algorithm> #include <random> void Sample( int first, int last, std::vector<int> *out, std::size_t n, std::mt19937 *g) { std::ranges::sample( std::views::iota(first, last), std::back_inserter(*out), n, *g); } Demo Note that t...
73,133,226
73,133,401
This print function cannot output the value in the deque
The result of the current execution of this program does not display the result. I want to display the values in the even deque and odd deque through the print function. During the debugging process, I found that the value in the deque already exists, but the print function will end in the middle. #include <list> #incl...
You have an error in the print function, the condition should be beg != end. Here is the function: void print(std::deque<int>::iterator beg, std::deque<int>::iterator end){ while (beg != end) { std::cout << *beg; beg++; } std::cout << "\n"; }
73,133,294
73,133,313
What is the difference between deque.at(0) vs deque[0]
So i have this queue deque<int> deq1(2,10); I Have accessed the element using 2 way and both of them return the same value cout<<deq1[0]; cout<<deq1.at(0); why did them make a special function to do the same thing or is one way better than the other?
The only difference is that the function at throw an exception if the index is out of range while the operator[] doesn't make any check. You can see the documentation here https://en.cppreference.com/w/cpp/container/deque/at https://en.cppreference.com/w/cpp/container/deque/operator_at
73,134,196
73,134,792
Hidden friend to_json function unexpectedly resolves for shared_ptr
The code below (Goldbolt) compiles and runs (on both gcc and clang) and does what I would hope. But I'm surprised! I expected to have to use an adl_serializer specialisation (as opposed to the hidden friend here) for it to be able to find the to_json/from_json functions, as the Example class is hidden inside a std::sha...
A friend function definition not declared elsewhere is declared in the same namespace as the class it is defined in. There are two reasons your to_json and from_json are found. The first, and simplest reason is that Example is in the global namespace, so lookup will reach there if it doesn't find a match elsewhere. The...
73,134,275
73,134,425
Is there a clean way to make declvals for types with no default constructors?
consider this example: template<typename T> concept Iteratable = requires(T n) { n.begin(); n.end(); }; namespace detail { template<Iteratable T> using subtype = std::decay_t<decltype(*(std::declval<T>().begin()))>; template<Iteratable T> constexpr auto deepest_subtype_recursive() { i...
You can return std::type_identity<T>{} (which is always default-constructible) and use decltype()::type to get the wrapped type. namespace detail { template<Iteratable T> using subtype = std::decay_t<decltype(*(std::declval<T>().begin()))>; template<Iteratable T> constexpr auto deepest_subtype_recursiv...
73,134,485
73,134,534
In the following code, does pop() actually removes the item from the array 'num' or the item still exists inside the 'num'?
Does pop function really removes the item from the array, it just changes the pointing index? int STACK::pop() { int temp; if(isEmpty()) return -9999; temp=num[top]; --top; return temp; }
No, the element isn't removed from the array. It isn't possible to add or remove elements of an array. Arrays have constant number of elements through their lifetime.
73,134,544
73,165,866
Qt Creator Clang Code Model can't find included header in included header
My problem is as follow: The clang code model from Qt Creator is unable to find the first header included in the header file of a cpp file. CPP-File: Header file of that cpp-file: As you can see, the code model has no issues finding QDialog in the header file, but has so in the cpp file. I have the same issue in oth...
Disabling unity build fixed it.
73,134,842
73,134,921
How can I extend or change the behaviour of c++ standard library objects
Let's say I want to change the default way the std::bitset prints out its bit. The normal way is: #include <iostream> #include <bitset> int main() { std::cout << "size of int is: " << (sizeof (int)) << std::endl; std::bitset<32> bits = 0xFFFF0000; std::cout << "Original\n" << bits << std::endl; ...
I want to know how can I extend or add more functionality and options to a standard library object. Don't. At least not directly. In general you better do not overload operators for types you do not own. In this case there is already an std::ostreams << operator. Rather write your own custom type that manages how to...
73,135,323
73,138,604
Should I call `delete` on object allocated using polymorphic allocator
Does polymorphic allocator (I personally use boost and C++17, but guess that it's the same for stl and C++20) in it's destructor automatically destructs objects allocated inside it's memory resource, or should delete for each object be called manually, like if I'm using default stl std::allocator (where not calling del...
A polymorphic allocator is a cheaply copyable object and doesn't own objects. What you might be confusing it with is a memory_resource, which has capacity to store objects. Still, it doesn't own those, because it cannot even know the type(s) of object(s) stored in its capacity. On the other hand, there are container ty...
73,135,493
73,135,636
QT C++ how to append text on last lıne and keep old lınes?
Instead of overwriting the new text, I want to preserve the existing content and add it to the new line. I need make a simple log for login. But When I try save to txt file Is overwriting on file. But when I try it, It just overwriting on file. How can I add to new line when new log is coming? Here is my login function...
Did you check the documentation? The flag you want is QIODevice::Append.
73,135,760
73,201,976
pybind11 crashes (segmentation fault (core dumped)) while importing ONNX python module
I am using pybind11 in my C++ code. When I try to import onnx, my code crashes with Segmentation fault (core dumped). However, if I import onnxruntime, everything is well. Of course both onnx and onnxruntime are installed on my system via pip. // installed libraries pip install onnx pip install onnxruntime // C++ code...
I am answering my own question. The cause of the problem was that onnx was not compatible with protobuf version 3.19.0 or higher. Using protobuf between 3.18.1 and 3.12.0 will solve the problem.
73,135,910
73,135,954
why does my std::transform retuns nothing/empty string?
can you help explain me how to use std::transform ? I need to create a function that returns a string and has a string as parameter and use std::transform to convert all the uppercase char to lower and vice versa lowercase char to uppercase example: input = "aBc" output = "AbC" and i want to do it with a lambda, not us...
You haven't allocated any space in result, so you are observing a pretty "gentle" case of undefined behavior ("gentle" because the program is observably not working, rather than happening to work by pure luck). To solve the problem, you can either allocate such memory before calling std::transform, e.g. via result.resi...
73,136,044
73,136,347
How can i make private destructor from singleton using shared_ptr?
i tested two type of singleton from C++17 first is unique_ptr second is shared_ptr these have to work with private constructor and destructor cause nobody can't change any instance status i finaly successed to compose unique_ptr version but shrared is not done shared_ptr version makes error error is 'Singleton2::~Singl...
You can use a custom deleter and make that friend of Singleton2: #include <memory> #include <iostream> class Singleton2 { struct Deleter { void operator()(Singleton2* ptr){ delete ptr;} }; friend Deleter; public: static Singleton2& GetInstance() { if(!mFlag) { ...
73,136,532
73,138,839
Where is the data race in this simple c++ code
Both clang++ and g++ sanitizers produce similar warning about data race for this simple code. Is it a false alarm? What is the problem? Code: #include <thread> struct A { void operator()() { } }; struct B { void operator()() { } }; int main(void) { // callable objects are created and moved...
The program is well-formed. It doesn't have any data race or other undefined behavior and it also doesn't have any race condition or unspecified behavior (except for the possibility of aborting with an uncaught exception if thread creation fails). Thread sanitizer is simply not playing nice with the undefined behavior ...
73,137,993
73,161,527
Is there any way to get more debug info from gdb?
I can get more debug info if built my program on Windows compared to Linux. Here is my code: #include <iostream> #include <vector> using namespace std; class Base { public: Base() = default; virtual ~Base() = default; }; class Derived : public Base { public: Derived() = default; ~Derived() = default;...
I fixed this problem by add a init command to the ~/.gdbinit. Add the following command to the first line of file ~/.gdbinit. set print object on
73,138,314
73,165,433
how to make pybind11 property docstring to show up?
I have following code: py::class_<Logger> logger(m, "Logger"); logger.doc() = "class docstring"; logger.def("setLevels", [](uint16_t levels) { LoggerInstance.setLevels(levels); }, R"( Turns on/off different logging levels Parameters * levels Logging level flags )" ); ...
I think it's a bug (see here). If you can change the C++ source you could try to make those members non-static and then use def_property_readonly (for which docstrings show up, at least in my tests).
73,138,979
73,144,015
Finding denominator which the dividend has the maximum remainder with
I need to find the maximum remainder for n divided by any integer number from 1 to n, and the denominator which this remainder is found with. In my implementation fun1 works as expected and returns the max remainder, fun2 is supposed to give 3 but its giving 2 .probably mistake is at break statement. Sample input: 5 Ex...
In fun2 you have: if(c == p){ break; } d = i; When you found the right index so that c == p the break will exit the loop and d == i; is not execute. Therefore d has the value from the previous loop, i.e. one less than you need. Apart from that the code really smells: fun1 should not have a second...
73,140,361
73,150,780
QT - embedding translations works on Windows, not on Linux
In the SQLiteStudio I started using CONFIG += lrelease embed_translations for automatically embedding all translations into the app's resources. I did so by declaring: CONFIG += lrelease embed_translations QM_FILES_RESOURCE_PREFIX = /msg/translations TRANSLATIONS += $$files(translations/*.ts) This is done for all mod...
I got the solution. Short answer Add QMAKE_RESOURCE_FLAGS += -name coreSQLiteStudio_qm_files to all pro files (and replace the coreSQLiteStudio_qm_files to unique name in each case). If you have other (explicit) resource files in the project, you will need to have dynamic, but predictible names, like: QMAKE_RESOURCE_FL...
73,140,470
73,157,546
No matching function to call 'createMatrix'
What I'm trying to do I'm trying to convert a buffer of type [Int] to [[Int]]. Since arrays are not super easy to return in C, I'm creating a new empty array and passing the pointer into a void function that is supposed to fill the address space with Integers from the buffer. Afterwards, the matrices are supposed to ge...
Any variable that is a pointer or reference must be declared with one of the address space attributes. This is the correct implementation of your function: void createMatrix(device int (*arr)[6][6], int count, constant int* buff) { for(int i = 0; i < count; i++) for(int j = 0; j < count; j++) ...
73,141,573
73,141,655
VS2022 C++20 E3309 an export declaration cannot export a name with internal linkage
This happens when exporting a module namespace variable. It compiles and works as intended but Intellisense seems disagree. Is it an intellisense bug or a undefined behavior that has side effects? Tried Unnamed/anonymous namespaces vs. static functions but still same error. Env: windows11 VS2022 ISO C++latest with Exp...
As usual in these cases, intellisense is incorrect. Well, the rule it cites is correct, but it is applying it where it shouldn't. Yes, you cannot export a name with internal linkage. However, your variable doesn't have internal linkage. The rules for that have an explicit carve-out for "inline or exported" non-template...
73,142,306
73,142,347
Selection sorting. not getting the required output
What is wrong with this code? Not getting the right output. void selectionSort(vector<int>& arr, int n) { for(int i = 0; i < n-1; i++ ) { int min = arr[i]; for(int j = i+1; j < n; j++) { if(arr[j] < min) min = arr[j]; } ...
You are using the local variable min in the swap where you needed to use the vector element. swap(arr[index_min], arr[i]) // `index_min` is the index of the current min value.
73,142,525
73,142,680
MessageBox - HWND parameter
I am working on an MFC application and I am adding some error checking with the use of MessageBox which has documentation found here. int MessageBox( [in, optional] HWND hWnd, [in, optional] LPCTSTR lpText, [in, optional] LPCTSTR lpCaption, [in] UINT uType ); Note: The utype parameter is a list...
You are not calling the MessageBox() function that you think you are. You are looking at the MessageBox() function in the Win32 API, but MFC has its own MessageBox() method in the CWnd class. The latter one, which does not have an HWND parameter, is the one you are actually calling.
73,142,639
73,145,428
C++ file cannot find library linked with CMake
I wanted to use DearImGui therefore I needed to either copy ImGui into the project or use a package manager, so I chose the latter. I'm currently using Conan as a my package manager, the file looks like this: conanfile.txt [requires] boost/1.79.0 imgui/1.88 glad/0.1.36 glfw/3.3.7 [generators] cmake_find_package cmake...
Don't mix up mutually exclusive generators like cmake_find_package vs CMakeDeps, or cmake_paths vs CMakeToolchain. Here is a basic example of non-intrusive integration of conan: conanfile.txt [requires] boost/1.79.0 imgui/1.88 glfw/3.3.7 [generators] CMakeToolchain CMakeDeps CMakeLists.txt cmake_minimum_required(VERS...
73,142,695
73,142,955
Can I use Qt visual studio tools for comercial projects?
I understand that I can work on closed source projects using Qt as long as I link dynamically the Qt libraries and don't include them in the release version of my app. My question is, if I use Qt visual studio tools, would it compile it including the Qt libraries on my release? if so, how could I make use of Qt librari...
This dialog in the installer has the answers to all your questions. So, with these limitations in this wizard, you can use the open source version of Qt in your project. And yes, you can of course link against Qt dynamically either in qmake or cmake. All these common and popular IDEs support cmake, like Visual Studio ...
73,142,903
73,143,098
What is the difference between epoll and multiple connect attempt?
Let's say i have a non blocking TCP client socket. I want to connect to a TCP server. I found that either of the following ways can be used to do so. int num_of_retry=5; for(int i=0;i<num_of_retry;i++){ connect(SOCKET_FD,...); sleep(1000ms); } and this connect(SOCKET_FD,...); epoll_wait(...,5000ms) What are the...
In this particular example, the main difference is that sleep() will not exit until the full interval has elapsed, whereas epoll() (and select(), too) will exit sooner if the pending connect operation finishes before the full interval has elapsed. Otherwise, both examples are blocking the calling thread until something...
73,142,919
73,143,221
Why does my stringstream get filled with garbage after tryng to insert the contents into a vector?
Consider the code: void someFunc { std::stringstream value; std::vector<std::vector<int>> mapLayerCollision; int row = 0; for(int i = 0; i < gid_list.length(); i++) { if(gid_list[i] == ',') { value.str(""); int j = 1; while (gid_list[i-j] != ',' and i - j > 0...
I know that stringstream can be finicky It is not finicky, you use it improperly. All your code can be simpler std::vector<std::vector<int>> mapLayerCollision; std::string line; while (std::getline(cin, line)) { mapLayerCollision.emplace_back(); // This fixes your issue you have asked std::istringstream values(l...
73,142,968
73,142,969
Variable changes value when using conditional breakpoints in Eclipse
I am using the Eclipse IDE to develop C++ code for an ARM (STM32) processor. One of the options the debugger/Eclipse has is to set not only a breakpoint, but a condition at which to break. For example, "break at line 5 only if foo is 10." However, when debugging in this way, I came across a problem where memory was ...
The "condition" field for a breakpoint allows you to write a C/C++ statement which will be evaluated to determine if the processor should be paused. The fact that this can be ANY valid C/C++ statement can have some interesting (i.e., problematic) side-effects if you are not careful. For example, consider the following ...
73,143,373
73,144,311
Boost Graph Library: Are Vertex Descriptors Necessarily Unique?
I realize this might be pedantic, but are BGL vertex descriptors always unique? For background, I have the following graph definition: typedef boost::adjacency_list<boost::setS, boost::listS, boost::undirectedS, VProp, EProp> Graph; Where I'm using listS as the node data structure. I know that this makes my descriptor...
To the title: Are Vertex Descriptors Necessarily Unique? Yes. In other words, is comparing descriptors directly a valid way to check node equality? Yes. Clearly this is true when the node data structure is vecS Exactly. I was just going to give this exact example to give a partial proof. This means that your unde...
73,143,507
73,143,625
How to concatenate 2 BSTRs with a space in between them?
I have some methods that return a BSTR, and I need to concatenate those BSTRs, but it should have a space between each BSTR: BSTR a + " " + BSTR b + " " + BSTR c + and so on... I found a function that concatenates two BSTRs, however I cannot insert a space between each BSTR. Sample code: static BSTR Concatenate2BSTRs(B...
Simply include room for the space character in your length calculation, and then assign the actual space character in the allocated memory, eg: static BSTR Concatenate2BSTRs(BSTR a, BSTR b) { auto lengthA = SysStringLen(a); auto lengthB = SysStringLen(b); auto result = SysAllocStringLen(NULL, lengt...
73,143,614
73,143,648
does this reference the pointer returned with "new"?
I have created a char* str_1 and have allocated 64 bytes to it. Then I created another char* str_2 and referenced it to the initial string. char* str_1 = new char[64]; char* str_2 = str_1; // does it reference the object created with the new statement. My question is, does str_2 contain the reference to the allocated...
After the declaration of the pointer str_2, both pointers str_1 and str_2 are pointing to the same dynamically allocated memory (character array). char* str_1 = new char[64]; char* str_2 = str_1; After calling the operator delete []: delete[] str_2; Both pointers become invalid, because they both do not point to an e...
73,143,615
73,166,330
TaskDialogIndirect randomly fails and makes empty, undrendered window
I use TaskDialogIndirect() to display more advanced Error Messages. I can customize the buttons, icons, and more. The problem is that, sometimes it makes these invisible empty dialog boxes. I need it to be reliable. I am wondering why this is even happening in the first place. Example of it failing (there is no visible...
The problem was the flag TDF_ENABLE_HYPERLINKS. Adding hyperlinked text that is too long caused the dialog to spawn outside of the desktop view.
73,143,660
73,143,733
An elegant approach to comparing many int variables to a value - C++
Of the two current answers, I have chosen the one using the range based for loop as it better addressed my first requirement which is to avoid being lengthy. The answer with the variadic template is interesting (and I will try it out!) but lengthier than I would like (since I want everything done inside the same functi...
You can use a range based for loop as for example for ( const auto &item : { v1, v2, v3, v4, v5, v6 } ) { if ( item == -1 ) return; } or in C++ 20 for ( int value = -1; const auto &item : { v1, v2, v3, v4, v5, v6 } ) { if ( item == value ) return; } If you do not want to create copies of the variables in the ...
73,144,100
73,144,285
Error when using std::vector::size to create another vector
I am learning DSA and while practising my LeetCode questions I came across a question-( https://leetcode.com/problems/find-pivot-index/). Whenever I use vector prefix(size), I am greeted with errors, but when I do not add the size, the program runs fine. Below is the code with the size: class Solution { public: int...
If you use vector constructor with the integer parameter, you get vector with nums.size() elements initialized by default value. You should use indexing to set the elements: ... for(int i = 0; i < l; ++i){ sum2 = sum2 + nums[i]; prefix[i] = sum2; } ... If you want to use push_back method, you should create a z...
73,144,358
73,144,389
C++ Same Variable on Left and Right Side of Assignment
Suppose that we have some object, such as std::vector<int> foo. I know from reading the C++ docs on self-assignment that foo = foo (although weird) should technically be OK since classes in C++ are responsible for being self-assignment safe. However, suppose that I also have some method reverse() that does not modify t...
Yes on both counts. Everything is safe. foo = reverse(foo); If reverse doesn't mutate foo, then it returns a completely unrelated vector, and that vector is assigned to foo. Those two steps happen in that order. The result of reverse must be fully known before operator= is ever called on foo, for the same reason that ...
73,144,452
73,144,556
Segmentation fault with references
Why do I get Segmentation fault with the code below? #include <iostream> #include <string> const std::string& f() { return "abc"; } std::string&& g() { return "xyz"; } int main() { const std::string& s1 = f(); std::string&& s2 = g(); s2 += "-uvw"; std::cout << s1 << ", " << s2 << std::endl; re...
Your second example with no extra function calls is well-defined due to the reference lifetime extension rules. Essentially, when a prvalue is immediately bound to a reference upon creation, the lifetime of the referenced object is extended to that of the reference. In your first example, reference lifetime extension ...
73,144,724
73,145,444
Python vs C++ Precision
I am trying to reproduce a C++ high precision calculation in full python, but I got a slight difference and I do not understand why. Python: from decimal import * getcontext().prec = 18 r = 0 + (((Decimal(0.95)-Decimal(1.0))**2)+(Decimal(0.00403)-Decimal(0.00063))**2).sqrt() # r = Decimal('0.0501154666744709107') C++:...
The origin of the discrepancy is that Python Decimal follows the more modern IBM's General Decimal Arithmetic Specification. In C++ however there too exist support available for 80-bit "extended precision" through the long double format. For reference, the standard IEEE-754 floating point doubles contain 53 bits of pre...
73,145,529
73,151,406
Can not include linked with CMake third-party library
I am trying to use an fmt library in my C++ project for formatting. I have installed the package with anaconda. Afterwards, in my CMake file I have found the fmt package and link: set(fmt_DIR "/opt/anaconda3/lib/cmake/fmt/") find_package(fmt REQUIRED) target_link_libraries(<my_target> fmt) But even though these steps ...
As @Tsyvarev mentioned in comment: ... after find_package(fmt) one should link with fmt::fmt: target_link_libraries(<your-target> fmt::fmt). So using target_link_libraries(<your-target> fmt::fmt) instead of target_link_libraries(<your-target> fmt) works perfectly.
73,145,946
73,146,008
Merge two 2D arrays into one C++
I would like to merge two arrays (inventory & inventory2) into one new array (inventory3) for sorting purposes. I am unable to have inventory3 have values assigned by inventory2 (the second nested for loop). inventory3 is accepting assignment from inventory correctly. I cannot figure out why this is not working. I ...
You're trying to assign an int to a string in this statement: inventory3[count][count2] = inventory2[count][count3]; To make it work, convert the int to string like this: inventory3[count][count2] = to_string(inventory2[count][count3]);
73,146,307
73,146,335
Are standard library non-type template classes explicitly instantiated?
When we have a templated class (or function) that has a non-type template parameter, how are the versions generated by the compiler? Surely it doesn't create a version for every possible value of N Suppose something like std::array<T,N> ? I am trying to write my own templated function with a size_t template parameter, ...
Neither the standard library nor you need to explicitly instantiate any template specialization, whether it has non-type template parameters or not. Any specialization of the template which is used by the user in a way that requires a definition for the specialization to exist will cause it to automatically be implicit...
73,146,387
73,146,671
How to include webview in existing Qt project?
I am trying to include one of the following libraries: #include <QtWebView> #include <QWebView> #include <QtWebEngineWidgets> #include <WebEngineCore> #include <QtWebEngine> Each time I add one of its includes an error appears in my code. However, I use Qt 6.3.1 and I find files that correspond to the includes in my s...
You need to make sure that you install the QtWebEngine module when installing Qt. Then, in your CMakeLists.txt, you would write something like this below. Please note that you should use versionless targets as recommended by the Qt Project, i.e. do not use Qt6::WebEngineWidgets as that would have portability issues. f...
73,146,581
73,146,758
Is it UB to reference bind to underlying type of enum class object?
Is it UB to reference bind to underlying type of enum class object? I'm aware of the danger of pass-through return reference of the as_int function. The thunking function is just to help explain the question. XY problem - after a bunch of inline operators to static_cast to/from underlying type at appropriate places, I...
Accessing the return value of as_int(i) as done in your main is an aliasing violation and therefore causes undefined behavior. The relevant paragraph of the standard ([basic.lval]/11) does not list underlying types of enumeration types as specifically allowed to alias. Currently the standard doesn't even specify that t...