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
71,459,542
71,459,621
Different results on different compilers c++(vector copying)
I need to implement a simple version of schedule for monthly tasks. For example payment of electricity bills, subscription fees for communications, etc. I want to implement a set of the following operations: ADD(i,s) - assign a case with name s to day i of the current month. DUMP(i) - Display all tasks scheduled for da...
Look here copy(current_month.begin(), current_month.begin() + day_mon[n_ind], next_month.begin()); What happens when current_month has 28 days and the next month has 31 days - ie day_mon[n_ind] = 31
71,459,815
71,459,994
C++ Program Printing 0 When Numbers Too Large
I'm trying to write a program that prints the factorial of a number: #include <iostream> using namespace std; int main() { int ans,fact=1, number; cin>>number; for (int i=1; i<=number; i++) { fact = fact*i; } ans = fact%998244353; cout <<ans<<endl; return 0; } When I try to input ...
Some hints for doing math in a finite field or ring while avoiding overflow. Mathematically is true that: (a*b)%c == ((a%c)*(b%c))%c and also: (a+b)%c == ((a%c)+(b%c))%c But in the case a*b or a+b will overflow, you have to use the righthand expression because it is less likely to overflow.
71,459,975
71,460,093
C++ MSVC '=' unable to resolve function overload
I have an API which I'm able to register multiple function pointer as callbacks. However I need to track additional data when a callback is called (in this example an index). What I want to do is generate a bunch of methods at compile which holds this additional data. My code is the following: #include <iostream> ...
The problem is the use of variable i as template parameter. The proper approach is to use integer sequence which provides a pack of compile-time constants that can be used as template parameters: #include <iostream> #include <vector> #include <sstream> #include <array> #include <utility> #include <cstddef> // API func...
71,460,068
71,460,291
How do I print out the value that make magic square?
I have tried this code that I found online and it worked, but I want it to print out which number makes magic square. In this case it is 83, so instead of cout<<"Magic Square", how do I change it to show 83 instead? Thank you in advance. # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) using namespace std;...
If the given square is a magic square, that means when isMagicSquare(mat) is true, then iterate through the given square and print each of the values. To do that, you'll have to learn how to print a 2D array. In your case, you can do like below: if (isMagicSquare(mat)) { for(int i = 0; i < 3; i++) { for...
71,460,170
71,465,701
Audio samples to musical note detection issue
I'm trying to setup a pipeline allowing me to detect musical notes from audio samples, but the input layer where I identify the frequency content of the samples does not land on the expected values. In the example below I... build what I expect to be a 440Hz (A4) sine wave in the FFTW input buffer apply the Hamming wi...
I think you've misunderstood the M_2_PI constant in your GenerateSinWave function. M_2_PI is defined as 2.0 / PI. You should be using 2 * M_PI instead. This mistake will mean that your generated signal has a frequency of only around 45 Hz. This should be close to the output frequencies you are seeing. The same constan...
71,460,334
71,460,451
How can I make sure only one thread performs IO from a file?
Here's my use case (using C++): I have a multithreaded environment performing operations on data structures written on disk. There are M files. The workflow is: Thread reads from file into a data structure Operations on the data structure are performed The data structure is inserted in cache Last recently used element...
Put file name in an std::map as a key. Then add mutex pointer as a value. Then whenever a thread has a file name to work on, it locks using the mutex and a lock guard. { lock_guard<mutex> lg (*mapping[filename] ); compute(filename); } As OS has its own file cache, it would be good to use read-lock to let multiple ...
71,460,427
71,460,638
Why do these lambda captured values have different types?
Two int variables, one a reference, when captured by lambdas, differ in type in MSVC's c++20. Why? Scott's technique to determine type at compile time produces expected results for c++14 and 17 but not for c++20. However, it seems this odd difference occurs in other compiles for earlier versions too. Specifically, two ...
The behavior of Clang, GCC and MSVC in C++20 mode is correct for all standard versions supporting lambdas. decltype(i) and decltype(ri) yield the type of the named variables. It is not rewritten to refer to the members of the closure object, as would be the case for decltype((ri)). (see e.g. [expr.prim.lambda.capture]/...
71,460,531
71,460,571
How to check invalid address/deleted pointer?
I'm pretty new to c++ and I'm stuck at this problem. I append a struct pointer(Bar*) to a vector and that struct have a pointer class member(Foo*). struct Bar { const int var{ 0 }; Foo* m_foo{ nullptr }; }; std::vector<Bar*> list; int main() { Bar* p_Bar = new Bar; p_Bar->m_foo = new Foo; list.emplace...
How to check whether the pointer's deleted/pointer's address is valid or not? It isn't possible to check whether a pointer is valid or invalid. If a pointer is valid or null, then you can check which one it is. If a pointer is invalid, then the result of the comparison will be unspecified. Besides comparing an invali...
71,460,632
71,461,062
variadic template function (to delete number of dynamically allocated variables)
I don't get exactly if I am doing the right thing template<typename ...AllVArgs> auto dealloc_all(AllVArgs &..._AllVArgs) -> void { (((std::cout << "\nin dealloc_all function " << &_AllVArgs), ...) << " "); ((delete _AllVArgs), ...); ((_AllVArgs), ...) = nullptr; } I allocated 2 struct and try to free them by usin...
just wanted to know if I successfully free the allocated memory. Yes: with ((delete _AllVArgs), ...); you correctly free all the allocated memory I don't get exactly if I am doing the right thing Not completely: with ((_AllVArgs), ...) = nullptr; you set to null pointer only the last argument of your function. If...
71,460,936
71,461,287
Merge two Linked List In c++ without using inbuilt sort method
You are given two linked lists the thing is that one of them is sorted and the other isn't the task is that you have to merge them and sort their value while comparing during execution not sorting both linked lists separately and also without using any inbuilt method from c++ template library. I have attempted the ques...
You need at first to rewrite the function insert_end. Initially the both pointers last and last2 are null pointers Student *first = NULL; Student *last = NULL; Student *first2 = NULL; Student *last2 = NULL; So if the user will decide at first to fill the second list then due to this if statement if (k == NULL) { i...
71,461,032
71,461,072
Why does this pointer behave differently between g++ and visual studio 2022's compiler?
Edit: my question was relating to the difference between compilers but I was just mislead to think there was different behavior when really both compilers were showing the expected "undefined behavior" I know that using the static keyword here would be good for the building_num integer, but I don't understand why the v...
Variables declared in a scope (in this case, the scope for building_num is the body of the function assign_ building_num) cease to exist once the scope exits. You are taking the address of an integer that only has a short lifetime, and retaining its address after the object has been destroyed. Reading from a pointer to...
71,461,570
71,462,065
Printing an element from an octree with cout alters the content?
I tried creating an octree in c++. Seems to work fairly well, but when I print the content of the tree it returns an access violation error. Running this in debug will print two different numbers, although the content should not have been changed. Here is the printout: 2 11 32762 From what digging I have done it seems...
The specific error is here Node new_node = Node(current_node, d+1, max_depth); //Make it current_node->children[subindex] = &new_node; 'new_node' is a local variable and it will get destroyed once this function exits. You cannot store its address, its meaningless. UB. You need Node *n...
71,461,594
71,461,606
Error defining const static member of class if the class has template
I have the following code in a .h file: class Test1 { struct A1 { int x; }; static const A1 a1; }; template <class T> class Test2 { struct A2 { int x; }; static const A2 a2; }; and I define values for both a1 and a2 in a .cpp file: const Test1::A1 Test1::a1 = { 5 }; template<c...
The fix is suggested by a compiler, just be more careful in reading the compiler messages. <source>(17): warning C4346: 'A2': dependent name is not a type <source>(17): note: prefix with 'typename' to indicate a type <source>(17): error C2061: syntax error: identifier 'A2' <source>(17): error C2143: syntax error: missi...
71,462,073
71,462,123
How to replace std::bind with lambda within steady_timer::async_wait
Live On Coliru #include <iostream> #include <boost/asio.hpp> #include <functional> class printer { public: printer(boost::asio::io_context& io) : timer_(io, boost::asio::chrono::seconds(1)) { timer_.async_wait(std::bind(&printer::print, this)); // timer_.async_wait([this]() { // print(); //...
Your lambda doesn't have the required signature. Based the boost documentation, the callback takes a const boost::system::error_code& argument. std::bind lets you be a bit looser in the function signature (Why std::bind can be assigned to argument-mismatched std::function?), but lambdas need to be an exact match. The ...
71,462,164
71,481,189
boost::iostreams::mapped_file_source opens a file that has CJK filename
Assume we have code like this: boost::iostreams::mapped_file_source dev(paFileName.u8string().c_str()); where paFileName is a std::filesystem::path object. On Windows, the internal character in std::filesystem::path is wchar_t, but boost::iostreams::mapped_file_source seems to only accept variant width character strin...
According to the message of the compile-time error: C:/msys64/mingw64/include/boost/iostreams/detail/path.hpp:138:5: note: declared private here 138 | path(const std::wstring&); | ^~~~ Somehow Boost.Iostreams tried to convert the std::filesystem::path into a boost::iostreams::details::path but failed, ...
71,463,199
71,463,275
Returning const char* from funciton
I have this function, where I'm trying to return a const char*, but when I try to output the returned value, I get garbage value; virtual const char* what() const noexcept { std::stringstream s; if(m_id > -1) s << m_message << " with id " << m_id << " does not exist"; else s << m_message <<...
You are returning a pointer to the internal char data of a local std::string object that is destroyed when the function exits, thus the returned pointer is left dangling, pointing at invalid memory. Trying to access the data afterwards is undefined behavior. Normally, you would have two choices to fix that: return a s...
71,463,257
71,465,776
Developing Windows Software on Linux
I am making software for windows that uses things like windows api and I really do not like developing on windows. Is there a way to develop software on Linux, for Windows, preferably without virtual machines as my computer is not very powerful, I am using C/C++.
There is probably no universal answer to this. This is how I develop software on Linux that is used mainly on Windows: I use the Qt framework which abstracts away all platform-dependent details in my case. I use MinGW-w64 to cross-compile. It works very well with CMake-based projects and the excellent binaries from Ma...
71,463,657
71,464,231
C++: Pass string literal or variable to function
I have a function f that takes a string as input. I usually want to provide a string literal, e.g., f("hello"). However, I want to implement another function g that builds upon f: std::string f(const std::string&& x) { return x + " world"; } std::string g(const std::string&& x) { std::string res = f(x); // proble...
The traditional way to take a read-only parameter is by const lvalue reference. std::string f(const std::string& x) This rule of thumb applies to many types, not just std::string. The primary exceptions are types that are not bigger than a pointer (e.g. a char). It's rather unusual for a function to have a const rvalu...
71,463,785
71,463,833
Why is this code not producing expected output?
#include<iostream> using namespace std; #define sp ' ' std::ostream& nl(std::ostream os) { return os << '\n'; } int main() { cout << 1 << sp << 2 << nl; cout << 3 << sp << 4 << sp; cin.get(); cout << 5 << sp << 6 << nl; cin.get(); cout << 7 << sp << 8; return 0; } I'm testing out...
The problem is in nl function. you have to pass ostream by reference. Have a look at this code // Pass by Ref std::ostream& nl(std::ostream& os){ os << '\n'; return os; }
71,464,671
71,464,883
Input basic_ostream in the template
Why don't use ttt::focus_pocus() and is used without ()? What is the rule and why does it work here? #include <iostream> namespace ttt { template<class CharT, class Traits> std::basic_ostream<CharT, Traits>& focus_pocus(std::basic_ostream<CharT, Traits> &os) { return os << "focus pocus"; } }; int main() ...
The << operator is overloaded to accept functions with the same signature as the focus_pocus function in your example [1]. That is the reason why you don't call the function and don't need () brackets. This overload is present, to allow outputtable objects like e.g. std::endl to manipulate the output stream and for exa...
71,464,736
71,783,973
How to attach Visual Studio to Unity in order to debug a native dll?
I have a native dll which is used by a project in Unity 2019.4.35f1. Since the logic in the dll is complicated I would like to be able to debug it. From the main answer here https://answers.unity.com/questions/30620/how-to-debug-c-dll-code.html I was able to log debug from inside the dll. From the answer from this th...
After a month I have accidently found the reason. Error Pause was activated. I have logged an error so the Game has paused which makes it impossible to attach to the Unity process. I hope this helps anyone.
71,465,026
71,466,332
Modern c++ while dealing with legacy code owning raw pointers: unique_ptr VS "softer" GSL owner<T*>
I would like to figure out pro and contra of different ways to deal with the issue of owning and not-owning raw pointers mixed up, within the pre-C++11 OOP framework that I am using. My role "as framework user" is basically to implement a dozen of abstract classes among the huge class hierarchy provided by the framewor...
A) all owning raw pointers (clearly detectable by the delete in the destructor but also always cross-checked with the user guide) replaced with unique_ptr. CONTRA I have to add .get() at every call of the framework methods (plus sometimes some .reset() when initlization cannot happen in-class/in-initializer-list), w...
71,465,484
71,471,871
Is there a proper way to receive input from console in UTF-8 encoding?
When getting input from std::cin in windows, the input is apparently always in the encoding windows-1252 (the default for the host machine in my case) despite all the configurations made, that apparently only affect to the output. Is there a proper way to capture input in windows in UTF-8 encoding? For instance, let's ...
This is the closest to the solution I've found so far: int main(int argc, char* argv[]) { _setmode(_fileno(stdout), _O_WTEXT); _setmode(_fileno(stdin), _O_WTEXT); std::wcout << L"ñeñeñe"; std::wstring in; std::getline(std::wcin, in); std::wcout << in; return 0; } The solution depicted her...
71,466,444
71,466,774
C++ class as namespace for static values
Is there anyway to have the same API from namespace with a class Exemple for namespace : namespace Direction { static const vec3 up = vec3(0, 1, 0); } // in code { vec3 v = Direction::up; } whereas using a class I have to use a method class Color : public vec4 { // class stuff // static Color black() ...
try this class Color { public: Color(int x, int y, int z, int t) {} const static Color BLACK; }; const Color Color::BLACK{1,2,3,4}; int main() { Color c = Color::BLACK; } I tested at https://godbolt.org/z/4oP55jTMK
71,466,707
71,510,692
C++ container without C++ standard lib
In the context of embedded software I want to make a std::vector-like container. Vector has both size and capacity, which means vector has allocated capacity*sizeof(T) bytes, but only size entries are constructed. An example vector<string> v; v.reserve(100) v.resize(10) v[9] gives a valid string , but v[10] gives a va...
How can I build an object in a given memory address just using C++ compiler without including or any other C++ standard include files? You have to read your compiler documentation and/or source code and related libraries and find out what is needed for that particular compiler with particular options used by you to ...
71,466,931
71,468,126
Hash Function for a 7 digits int
I'm new to hash tables and functions, so I apologize in advance if I got anything wrong. I'm trying to create a hash table in C++ for a list of about 100k entries comprised of a 7 digit number. The thing is, I got stuck while trying to figure out what hash function to use. When using %100000 I got ~65k unique keys, whi...
The standard library comes with two types internally using a hash table: std::unordered_map and std::unordered_set. As your key type is an integral type you get a hash table pretty conveniently by std::unordered_map<YourIdType, YourDataType. You can easily access the data via theMap[someId], but be aware that if the ke...
71,467,220
71,467,301
How to concatenate the preprocessor constant and a literal string in cout
I started to learn c++, and when I tried to cout a macro it prints the value in the console but when I tried to cout the macro with another string literal, it raises an error. #include <iostream> using namespace std; #define PI 3.14; int main() { cout<<"Value of PI: " << PI; cout<<"Value of PI: " << PI << endl...
The problem is that you have a semicolon at the end of the macro. This line cout<<"Value of PI: " << PI << endl; then becomes: cout<<"Value of PI: " << 3.14; << endl; // ^ So, just remove the ; at the end of the macro: #define PI 3.14 You could also use a proper constant instead of a macro...
71,467,245
71,467,292
Passing pre-processor flags that contain special characters [c++17, g++]
I am trying to assign a value to a const char* by using a pre-processor flag in the following way. #include <iostream> #define ST(A...) #A #define STR(A) ST(A) const char* output = STR(FLAG); int main() { std::cout << output; } This approach works well, unless FLAG contains some special characters. When I attem...
You don't have to use stringification macros when FLAG is a string: -std=c++17 -DFLAG="\"a,b!c)d}e-f\"" Live Demo
71,467,348
71,467,403
Reusing String in C++ in function
As someone whose main language has been Python so far, I have a problem with string reuse. Here's an example code (simplified): void function(std::string &basicString) { std::cout << "Function print: " << &basicString << "\n"; } int main() { std::vector<std::string> x_files; /* Does sth, x_files contains some string...
std::cout << "Function print: " << &basicString << "\n"; Here you use unary & operator, which is an address-of operator, in other words it gives you a pointer. And since this is not a char pointer, std::cout prints the pointer value, in other words a memory address, as hex. Solution is simple, remove &: std::cout << "...
71,467,429
71,469,469
Link dll against static build of QuaZip using Qt5.12 in VS2017
I'm trying to link a .dll against a static builld of QuaZip library to get rid of the quazip.dll dependency at runtine. Since I've ran into a dependency conflict at production because a customer is using other third party applications in the same process where my .dll is uncluded, which are also using the quazip.dll bu...
Ok, three days of agony and I have the solution. I recompiled the zlib, this time not using the provided project file in \contrib\vstudio\vc14, but generating my own with CMake. Then QuaZip linked against it with the flag QUAZIP_STATIC. I then set this flag in my project, which uses QuaZip and linked it against the bui...
71,467,718
71,468,004
How do I fix this for loop problem in C++?
I have this for loop problem in my c++ program. When i try to run it it's all working fine but there is a small problem in the "Enter name:" loop. The "Enter name:" outputs 5 times but the first "Enter name:" is not recognized as part of the loop but instead the 6th empty line before the last "Enter name:" loop is reco...
There are 2 problems with your code: Mistake 1 The variable i is uninitialized and you're using that uninitialized variable when you wrote: cin>>names[i]; //this is undefined behavior since `i` is uninitialized which leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited ...
71,468,108
71,471,278
DocuSign integration from desktop application
I am trying to implement document signing with the DocuSign API in our Windows desktop application built in VC++. Our application is built with unmanaged code without using .net. I tried the supported languages, C++ is not available so I tried C# that is web interface which I can't use inside my application. How can I ...
You can use the Microsoft open-source REST API C++ SDK https://github.com/microsoft/cpprestsdk " C++ Rest SDK The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact wi...
71,468,470
71,469,669
Use thread with shared memory
I have an exe that writes data to shared memory than i read data from shared memory, i want to use std::thread when copy shared memory to different memory because writer exe does not stop writing. When i use std::thread for copying shared memory,i pass memory structure as parameter than memory structure will be null in...
Okay, there are some problems with your code as written. First, main is almost certainly going to quit before the thread gets a chance to run. But even if this isn't main but is something else (and thus your program isn't trying to quit), then bufferList is going out of scope before your thread runs. This is a time whe...
71,468,722
71,488,391
reverse_iterator weird behavior with 2D arrays
I have a 2D array. It's perfectly okay to iterate the rows in forward order, but when I do it in reverse, it doesn't work. I cannot figure out why. I'm using MSVC v143 and the C++20 standard. int arr[3][4]; for (int counter = 0, i = 0; i != 3; ++i) { for (int j = 0; j != 4; ++j) { arr[i][j] = counter++; ...
This is very likely a code generation bug of MSVC related to pointers to multidimensional arrays: The std::reverse_iterator::operator*() hidden in the range-based loop is essentially doing a *--p, where p is a pointer type to an int[4] pointing to the end of the array. Decrementing and dereferencing in a single stateme...
71,469,730
71,469,948
How to initialize all fields of a big class with two different fields in standard C++
I have a very big class with a bunch of members, and I want to initialize them with a given specific value.The code below is the most naive implementation, but I don't like it since it's inelegant and hard to maintain because I have to list all the members in the constructor. struct I_Dont_Like_This_Approach { int ...
I would argue that the first one is much more maintainable, with the right warnings enabled (and a modern compiler), you will see if your initializer list gets out of sync with the class fields at compile time. As to your alternative.. you're using templates as compiler arguments, which is not what they're meant to be....
71,469,748
71,470,010
Move object from local variable to std::shared_ptr
Please note that with the words "object" and "move" in the title, I do not mean the C++-specific concepts of what an object is and what it means to move an object. I have a local variable of a pretty simple struct type where I accumulate some values read from a config file. struct Foo { std::string name; float ...
How about if (currentFooSetting) { *currentFooSetting = f; } else { currentFooSetting = std::make_shared<Foo>(f); } this sort-of ensures that you have just one shared pointer, and once it is created, its value is changed on update. Alternately, if existing holders-of-the-shared-pointer should keep their values...
71,470,625
71,471,149
const object as a data member vs normal variable
I was trying to make a Container class that will be using an object of a class Comparator which will be passed through the template. So I am doing something like: template<typename T> class Container{ const T c; }; struct Comparator{ public: bool operator()(const int a, const int b)const{ return a...
If no initializer is given for the const Comparator variable it must be const-default-constructible. But your class Comparator is const-default-constructible because it has no non-static data members. For actual rules determining that see [dlc.init.general]/7. This is not only the requirement for such a variable, but a...
71,471,136
71,471,420
why pointer variable inside private class can't point to outside variable of class
#include<iostream> #include <string> using namespace std; class Human { private: int *age; string *name; public: Human(string p_name, int value) { *name = p_name; *age = value; cout <<"Name of Person is "<<*name <<" and age...
why pointer variable inside private class can't point to outside variable of class The premise of your question is faulty. A private member variable can point to outside of the class. Human(string p_name, int value) { *name = p_name; *age = value; You didn't initialise the pointers...
71,471,142
71,490,226
How can I make my container compatible with boost::range?
I'm rolling a custom, standard-like container and I'd like to have it compatible with the boost::range library. So far it works with all the STL algorithms and it also satisfies the following: BOOST_CONCEPT_ASSERT((boost::InputIterator<my_container::const_iterator>)); BOOST_CONCEPT_ASSERT((boost::Container<my_container...
You need iterator as well as const_iterator. Try: using iterator = const_iterator;
71,471,386
71,472,638
OpenGL Alpha Channel not affective
Trying to make objects that fade over time in openGL. I am doing this by decreasing the value of the Alpha in the color I am using to draw the object. But this does not seem to have any effect on the object, it still draws it as solid. I have simplified the code to simply drawing three rectangles. Each rectangle is dra...
You need to enable blending and set an appropriate blend function (see Blending). To run an OpenGL instruction, you need an OpenGL Context. The context is create when the OpenGL window is created with glutCreateWindow. Therefore you must add the instructions after glutCreateWindow. int main(int argc, char* argv[]) { ...
71,471,684
71,471,919
Why does a C++ mathematical operation accept a letter as an input and output a number?
I'm brand new to c++, so maybe this is a stupid question, but I coded a very simple temperature conversion program. It looks like this: #include <iostream> int main() { double tempf; double tempc; // Ask the user std::cout << "Enter the temperature in Fahrenheit: "; std::cin >> tempf; // Conversio...
"However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind." By default, std::cin reports errors by setting internal error bits that must be checked manually. One mechanism is to use the good() member function to check for any error bits. Another is to use the bool conver...
71,472,463
71,482,486
VLC huge buffering times over rtp for local H264 stream
I'm outputting an H264 stream, encoded by my application using ffmpeg. I can display it using ffplay, but when trying to view the stream in VLC, I only get the first frame, or it looks like that's the case. The messages output shows that it is "buffering", taking around a minute to get to 100% when the frame updates. ...
The problem with my approach above was that it was based on the ffmpeg example encode_video.c with some bits for stream output borrowed from google. Thanks to @rotem I started putting together a standalone executable and stumbled on the example muxing.c in the ffmpeg examples. This let me find the steps I was missing: ...
71,472,475
71,473,401
How to create make not visible range so when user clicks near point, the point will be chosen
I have a set of vector points, with each click on my window I add pair to the vector. I want to add an invisible radius on my point which will help me to detect if a point was clicked. The point is basically 1 pixel in size so the user is not able to click on it directly. How can I achieve this? Do I need to use any ma...
If I understand your question correctly, you just need to run through your vector and check if any of the saved points are within a range of the clicked point. So something like this should work: if (event->button() == Qt::RightButton) { int radius = <something> QRectF range(event->x() - radius,...
71,474,096
71,474,786
What must I do for visual studio 2017 to use the natstepfilter file to avoid stepping into std library functions and class methods?
First, I am testing this capability by editing the default.natstepfilter file on purpose. I realize that there is a just my code feature built into visual studio now and an associated compiler setting /JMC. However I have a legacy project that is built using the older VS2013 tools still so I can't use the newer just ...
I think I solved my own issue by starting over and creating a new file with the .natstepfilter extension. I can't prove that a mistake in the file was the problem because the previous files I tried were changed or deleted already. However I am fairly confident that there was an error in my edited .natstepfilter file....
71,474,612
71,513,890
WebView2 AddScriptToExecuteOnDocumentCreated - How to wait for completion in C++?
In a C++ (MFC) app using WebView2, I can't find a way to simply wait until the script passed to AddScriptToExecuteOnDocumentCreated() is ready. My ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler() is just never called if I add some waiting code (e.g. WaitForSingleObject()) after calling AddScriptToExec...
Ok, I found a solution to my problem. Although I could make it work using the old dirty MFC message pumping trick (which I really don't like), I could finally refactor some code and call the navigate from the handler directly. Pretty simple. Thanks for your replies. auto res = webView->AddScriptToExecuteOnDocumentCreat...
71,474,982
71,475,029
Why can't I return std::getline's as-if-boolean result?
A standard idiom is while(std::getline(ifstream, str)) ... So if that works, why can't I say bool getval(std::string &val) { ... std::ifstream infile(filename); ... return std::getline(infile, val); } g++ says "cannot convert 'std::basic_istream<char>' to 'bool' in return". Is the Boolean conte...
The boolean conversion operator for std::basic_istream is explicit. This means that instances of the type will not implicitly become a bool but can be converted to one explicitly, for instance by typing bool(infile). Explicit boolean conversion operators are considered for conditional statements, i.e. the expression pa...
71,475,054
71,475,104
Structured bindings in Python
C++17 introduced the new structured bindings syntax: std::pair<int, int> p = {1, 2}; auto [a, b] = p; Is there something similar in python3? I was thinking of using the "splat" operator to bind class variables to a list, which can be unpacked and assigned to multiple variables like such: class pair: def __init__(s...
Yes, you can use __iter__ method since iterators can be unpacked too: class pair: def __init__(self, first, second): self.first = first self.second = second def __iter__(self): # Use tuple's iterator since it is the closest to our use case. return iter((self.first, self.second)) ...
71,475,844
71,476,733
Understand the usage of timeout in beast::tcp_stream?
Reference: https://www.boost.org/doc/libs/1_78_0/libs/beast/example/websocket/client/async/websocket_client_async.cpp https://www.boost.org/doc/libs/1_78_0/libs/beast/doc/html/beast/using_io/timeouts.html https://www.boost.org/doc/libs/1_78_0/libs/beast/doc/html/beast/ref/boost__beast__tcp_stream.html void on_resol...
Question 1 Yes that's correct. The linked page has the confirmation: // The timer is still running. If we don't want the next // operation to time out 30 seconds relative to the previous // call to `expires_after`, we need to turn it off before // starting another asynchronous operation. stream.expires_never(); Ques...
71,476,045
71,476,195
c++ pointer segfaults without compiler warning, works when previously assigned
I have a difficulties understanding pointers and how/when they fail. So I made a tiny program which creates a pointer, assigns a value to it and then prints that value. Compiles fine with both gcc and clang and does not give any warnings when using the -Wall switch. Why does it segfault and why does it not segfault whe...
A pointer is a variable that save a memory address. You "can" have any memory address in your pointer, but trying to read from memory space outside of where your application are allowed to read, will trigger the OS to kill you application with a segfault error. If you allow me the metaphor: You can write on a paper th...
71,476,058
71,476,218
Bazel doesn't exit after build when called from CMake (ExternalProject_Add)
I am trying to build an external project that uses Bazel as its build system from CMake with Ninja. I am doing this by using ExternalProject_Add ExternalProject_Add(bazel_proj SOURCE_DIR "${bazel_proj_DIR}" CONFIGURE_COMMAND : CONFIGURE_HANDLED_BY_BUILD ON BUILD_COMMAND bazel build //:install INSTALL_COMMAND ...
Bazel has a client/server model, where the server stays around for subsequent incremental builds. So this might be due to the server staying around. Try using the --batch startup flag, which tells bazel not to use this client/server model: bazel --batch build //:install https://bazel.build/docs/user-manual#batch Note t...
71,476,403
71,489,578
Why does GetPointCount of a GraphicsPath always return 0?
I am trying to learn the gdiplus windows API, and in particular how to use GraphicsPath to get points from different shapes. I noticed that I could never get anything to appear from microsoft's example code, so I tried to see how many points were actually in a GraphicsPath like this: #include <windows.h> #include <gdip...
Ahh read more documentation and found this: The GdiplusStartup function initializes Windows GDI+. Call GdiplusStartup before making any other GDI+ calls https://learn.microsoft.com/en-us/windows/win32/api/Gdiplusinit/nf-gdiplusinit-gdiplusstartup This code works: #include <windows.h> #include <gdiplus.h> #include <iost...
71,476,428
71,476,624
C++ unusual use of placement new into NULL
In the following C++98 statement: multiThreadService[nextBuffer] = new (NULL) MultiThreadService(binder); Would it be correct to say: this is "placement new", the object will be created (at NULL, somehow?) and thrown away, and multiThreadService[nextBuffer] will now be NULL? I was also told this could be UB - is tha...
First, it is not necessarily calling the global non-allocating placement-new operator new overload void* operator new(std::size_t size, void* ptr) (What is commonly meant by "placement new".) Because the new-expression is not qualified as ::new, it may prefer an in-class overload of operator new if a suitable one exist...
71,476,653
71,480,150
What is a pattern to ensure that every derived class (including derived classes of the immediate derived class) implement a method?
I have a base class and a number of generations of descendants (derived classes): class Base{ public: virtual void myFunc() = 0; } class Derived : public Base{ //This class needs to implement myFunc() } class Derived2 : public Derived{ //How to force this class to implement its version of myFu...
I propose the following solution: #include <iostream> template <class BaseClass> class RequireMyFunc: public BaseClass { public: virtual void myFunc() = 0; // declaration to force write implementation protected: void callBaseClassMyFunc() override { BaseClass::callBaseClassMyFunc(); ...
71,476,758
71,480,105
How to create a wrapper or intermediate layer to access a class, without exposing it?
I use a third party engine, that has a class "Sprite". My classes use sprite, and call its methods. There is a probability that "Sprite" will be replaced in the future by some other game engine. I would like to have a layer between my class, and Sprite, so that it is easy to swap out Sprite in future. I figure there ar...
You just need to create a Wrapper class that publicly inherits from Sprite and use it. It automatically fully inherits all the methods and variables of the Sprite class in the Wrapper class with the same level of visibility: class Sprite { public: void foo(){}; void bar(){}; int mod...
71,476,864
71,477,050
Why r-value is not copied, when it passed to function by value?
I have the following code: struct Foo { Foo() = default; Foo(const Foo&) { std::cout << "Copy" << std::endl; } Foo(Foo&&) noexcept { std::cout << "Move" << std::endl; } }; struct Bar { Bar(Foo foo) : foo(std::move(foo)) {} Foo foo; }; int main() { Foo foo; std::cout << "Pass l-value:" << s...
The {} in your second call isn't just an rvalue, it's a prvalue: a pure rvalue. Prvalues don't act like objects so much as they do instructions for initializing an object. Prvalues only get materialized under certain circumstances. Those being primarily when they're used to initialize an object or when bound to a re...
71,477,234
71,477,745
How do I fix this Expected Expression Error?
I am trying to write a code for a project, and in my if else statements I want to put that the SWI is greater than or equal to 305 and less than or equal to 395. How would I place those limitations in the code? I tried using <= and >=, but I do not think the placement is correct, and I am confused on how to fix it. #in...
There are too many syntactic errors. Corrected version below. also you might need to consider a check on T. It must be >49 else the log function gets a -ve input. #include <iostream> #include <cmath> int main() { using namespace std; double T,SWI,W; cout << "HELLO USER, PLEASE ENTER THE TEMPERATURE AND...
71,477,428
71,477,611
C++, Nothing in the output
I am new to C++ and coded my first main.cpp but I got an error, not exactly an error, it is a logical error, I guess because I wrote the following code: #include <iostream> // including the iostream using namespace std; // using the std namespace int main() { // starting the main function cout << "Hello World!" <<...
The command g++ main.cpp creates the file a.out or a.exe. After that file is created you need to run it by the command ./a.out on Linux and Mac or a.exe on Windows.
71,478,077
71,478,455
boolean check behaving unexpectedly when returning value
#include <iostream> #include <string> bool is_favorite(std::string word) { int isTrueCounter = 0; std::cout << "\nisTrueCounter: " << isTrueCounter; if (isTrueCounter == word.length()) { return true; } else { for (int i = 0; i < word.length(); i++) { if (...
You didn't return anything, you can do this in many way. For example from your code, return false immediatly after condition is not true (not in a-f). bool is_favorite(std::string word) { int isTrueCounter = 0; std::cout << "\nisTrueCounter: " << isTrueCounter; if (isTrueCounter == word.length()) { ...
71,478,253
71,487,664
Read bitset from file using istream_iterator
I'm trying to read a text file into a vector of std::bitset-objects. The file consists of 1's and spaces (for indicating 0 or false) and I'm trying to do this by overloading the input operator>> and using istream_iterators. I start by changing the spaces in the string to 0's and then construct a bit that I push to the ...
Interesting question. The reaon, why this happens is that the std::bitsethas already an overwritten extraction operator >>. Please see here. You can read that this behaves like a formatted input function. So, it will read until the next white space and then stop. It will end reading, if we have an "end of file" or unti...
71,478,720
71,480,227
how to override operator== in inheritance without being limited to base class?
struct Data { std::string Info; // Object Info virtual bool operator==(Data& b) { return this->Info == b.Info; } }; struct Data1: public Data { int ID; virtual bool operator==(Data1& b) override // overrides the bool operator==(Data& b) ba...
As a rule, objects of different types can't be equal to each other. That being the case, for your case, you may be able to get at least reasonably sane results with code on this general order: struct base { std::string info; virtual ~base() = default; virtual bool cmp(base const& other) const { ret...
71,479,264
71,479,390
CPP Enums as template flags
I'm trying to refactor an entire codebase of "std::filesystem::path path = blah; if (path.extension() == ".whatever") load_file(path) else abort/error". Thus far, I've written my enum as a bitfield with all the file extensions I wish my application to accept, and this function in the Assets namespace: enum class Accept...
You can write your own overload of operator| for your enum. E.g. #include<cstdint> constexpr uint32_t BIT(int i){ return static_cast<uint32_t>(1)<<i; } enum class AcceptedFileExtension : uint32_t { SCENE = BIT(0), OBJ = BIT(1), GLTF = BIT(2), GLB = BIT(3), PNG = BIT(4), JPG = BIT(5), T...
71,479,442
71,480,289
Binding temporary to r-value reference produces error
I'm trying to write a pImpl without using a unique_ptr. I don't understand while writing something like this: class PublicClass { public: // Some stuff PublicClass(); private: class ImplClass; ImplClass&& mImpl; }; class PublicClass::ImplClass { public: ImplClass() {} }; PublicClass::PublicClass()...
From class.temporary: The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except: A temporary bound to a reference member i...
71,479,736
71,479,912
What is the effect of calling a virtual method by a base class pointer bound to a derived object that has been deleted
The fllowing questions are: p->test() should not work after b is destroyed. However, the code is running without any issue, the dynamic binding still works; when the destructor of A is defined, the dynamic binding doesnot work anymore. What is the logic behind it? #include <iostream> using namespace std; struct A { ...
p->test() should not work after b is destroyed. However, the code is running without any issue, the dynamic binding still works; It does not "work". p->test() invokes undefined behavior. when the destructor of A is defined, the dynamic binding doesnot work anymore. What is the logic behind it? There is no logic...
71,479,959
71,479,994
How can an if statement change a variable, when there's no assignement operator used?
I have a dynamic queue, so I want to check if the head pointer is pointing to something. So I do this: if (mHeadPtr = NULL) return false; The pointer isn't empty (which is also why it does not go into the "return false" line) before this executes, but somehow it is afterwards, and I have no idea why. If I instead ...
For comparisions you should use == instead of =. By using a single = you don't compare the value of the variable but assign NULL to it.
71,480,646
71,493,732
Does QtNetworkAuth support PKCE
I use Qt5. I did not find any documentation on how to enable PKCE when using QOAuth2AuthorizationCodeFlow. If so, please provide the link. If there is no support, how can this feature be added to it? I added code_challenge and code_challenge_method, but it is not enough. I don't know what the next step is. #include <Qt...
The next step is to set code_verifier at RequestingAccessToken stage. auto code_verifier = (QUuid::createUuid().toString(QUuid::WithoutBraces) + QUuid::createUuid().toString(QUuid::WithoutBraces)).toLatin1(); // 43 <= length <= 128 auto code_challenge = QCryptographicHash::hash(code_verifier, QCryptographicHash::Sha...
71,480,809
71,484,148
Acqrel memory order with 3 threads
Lately the more I read about memory order in C++, the more confusing it gets. Hope you can help me clarify this (for purely theoretic purposes). Suppose I have the following code: std::atomic<int> val = { 0 }; std::atomic<bool> f1 = { false }; std::atomic<bool> f2 = { false }; void thread_1() { f1.store(true, std::...
Neither assertion can ever fail, thanks to ISO C++'s "release sequence" rules. This is the formalism that provides the guarantee you assumed must exist in your last paragraph. The only stores to val are release-stores with the appropriate bits set, done after the corresponding store to f1 or f2. So if thread_3 sees a...
71,480,912
71,481,059
Same math and numbers different answers?
im writing a simple program that you give a number of days and it gives back the number of years weeks and days that equal to the numbers of days you give. but i noticed that you can get two different answers even tho when i checked the math it makes sense in both cases . can someone please please explain to me why the...
There are not an exact multiple of weeks in a year, so you are displaying different things. They will be the same in years divisible by 7. E.g. Assume that a given year starts on a Tuesday. Days corresponds to how many days past the last Tuesday you are. SameDays corresponds to what day you are on. See also the disti...
71,481,244
71,482,525
Protobuf Partially Copy vector into repeated filed
In this question, it is answered how a vector can be copied into a repeated field by using fMessage.mutable_samples() = {fData.begin(), fData.end()}; ( and the other direction works too ). But how about a partial copy? Would the below work? std::copy( fData.begin() + 3, fData.end() - 2, fMessage.mutable_samples()->...
I created a program to test this, and it seems that using std::copy works! syntax = "proto3"; message messagetest{ repeated float samples = 6; } #include <iostream> #include <vector> #include "message.pb.h" int main(){ std::vector<float> fData(10); messagetest fMessage; std::generate(fData.begin(),fData.e...
71,481,294
71,493,038
LLVM IR basic blocks meaningful names
I'm trying to have meaningful names for the basic blocks in LLVM IR. That is, instead of the name 6 for this loop header, I would like it to be something like: loop.header.6. I'm pretty sure previous llvm/opt versions had this option, but I can't seem to find it in llvm-13. The actual source code for this is probably i...
The value names are only added by a frontend (clang) if it is compiled in debug mode / with assertions enabled. Note that the names might become misleading after optimizations, etc.
71,482,152
71,482,520
why can't bind be turned into function?
the problem is that IDE says the bind cannot be turn into function pointer. Fudge<int> obj(1); std::function<void(std::vector<int>&)> a = std::bind(&Fudge<int>::_pack_method, obj); //IDE warning here where the _pack_method is declared as template <class E> class Fudge { public: Fudge() = delete; Fudge(int i) {}; v...
Your problem here is you are not accounting for the function parameter of _pack_method. You need to tell bind how to fully bind with the function and you don't do that, you only give it the object to call the function on and not the vector parameter that it takes. To fix this, you either need to provide the vector yo...
71,482,195
71,709,945
Can we assume std::is_default_constructible<T> and std::is_constructible<T> to be equal?
Pretty short question here: Will std::is_default_constructible<T> and std::is_constructible<T> give the same result? And what about to the new concepts std::default_initializable and std::constructible_from. It might be important to know the distinctions when making templated factory or emplace functions.
So I finally got to reading the specification. Here's what I found: 20.15.4.3 is_default_constructible<T>: As pointed out by @Raymon Chen in the comments: true precisely when is_­constructible<T> holds true. 18.4.11 constructible_from<T>: Is defined in term of is_constructible<T>, but also poses the additional requirem...
71,482,327
71,482,771
Implementing Binary Semaphore using atomic<int>
I have written this code to demonstrate Binary Semaphore using only atomic . 1 thread producer will push 100 elements in the queue initially. later threads 2 and 3 which is the consumer will run in parallel to consume this queue. The issue is: I can see the same data/element print by both the threads BinarySemaphore.cp...
If you need to do more then one action on atomic you need check consistency if data was not changed. Other wise you will have a "gap" as point out in other answer. There is a compare_exchange which should be used for that: void wait() { auto oldValue = s_.load(); while (oldValue == 0 || !s_.comp...
71,482,623
71,483,437
std::cin not working correcly with large numbers
I found a strange behavior of std::cin (using VS 17 under Win 10): when a large number is entered, the number that std::cin is reading is close but different. Is there any kind of approximation done with large numbers ? How to get the exact same large number than entered ? double n(0); cout << "Enter a number > 0 (0 t...
You need to learn about number of significant digits. A double can hold very large values, but it will only handle so many digits. Do a search for C++ doubles significant digits and read any of the 400 web pages that talk about it. If you need more digits than that, you need to use something other than double. If you k...
71,482,792
71,482,929
C++ abi compatability without pimpl using abstract class
Suppose I have a class B_Impl which inherits and implements a pure abstract class B (not containing any data-fields). Suppose class A uses B_Impl via B* only. If I add a field to B_Impl.h (clearly, not included by A), will ABI compatability be preserved? I thought, that it will not be preserved, -- after reading https:...
If I add a field to B_Impl.h (clearly, not included by A), will ABI compatability be preserved? Yes. If a translation unit doesn't include the definition of B_Impl, then changes to B_Impl won't affect the compatibility. The interface compatibility - whether it is API or ABI - matters only when the interface is used. ...
71,482,810
71,528,374
using cmake, build a visual studio project with dependencies, being able to debug also into the dependencies
I have a C++ project source code with several dependencies (C++ packages, compiled libs and source). I need to create a CMake file which will generate the Visual Studio solution and projects files in such a way that if I put a break point in one of the dependencies source code, the execution of the main project in debu...
I ended up modifying the dependencies so that they implement unique target names for documentation, but if built individually to create the original named target: DOCUMENTATION. doxygen_add_docs(DOCUMENTATION_${PROJECT_NAME} doc src/component ) ...
71,482,828
71,497,693
Crash when calling interrupt() on a boost::thread, which has another boost::thread
I'm getting a crash when calling interrupt() on an outer boost::thread, which runs an inner boost::thread, which is connected to a thread_guard. It's not crashing when calling join() manually on the inner thread. Crash: terminate called after throwing an instance of 'boost::thread_interrupted' Source: https://gist.gith...
I got a solution. The problem was, that the join() of the thread_guard waits for the inner thread with a condition_variable::wait(). condition_variable::wait() itself checks, if it's interruptible and throws an exception. The solution is to use a custom thread_guard with disable_interruption: #include <iostream> #inclu...
71,483,146
71,511,497
How can I know which file called the function? cpp
I'm trying to understand a program(Moveit!) connected with many other files. The program runs fine without any problem, but I want to know which function(from a different directory) calls the function I'm interested in. Since there are so many directories and functions of the same name, I can't just simply track them e...
Thank you guys! The program I've been using(ROS Moveit!) had a built-in gdb debugger and I could find the log file which showed all the directories .cpp file launched. This might not be applied to all for sure, but below is just an example of the location of the log file for my case. ~/.ros/log/cf90466c-a51d-11ec-b5e0-...
71,483,341
71,484,219
SWIG - OverflowError when methods have enum typed arguments
I have a C++ code base which uses SWIG to generate Python 3 interfaces. I had a problem where I couldn't convert enum values into large enough types. This was solved with good help. Now I have a new problem that relates to the other one. Methods that take the corrected enum values as arguments are throwing an OverflowE...
SWIGTYPE is the default type match when a type-specific match is not found. You can use the following to apply to all enumerations: %apply unsigned long long { enum SWIGTYPE }; See 13.3.3 Default typemap matching rules in the SWIG documentation. Example: test.i %module test %typemap(constcode) int %{SWIG_Python_SetC...
71,483,904
72,156,301
Escape sequences for char8_t and unsigned char
Trying to use escape sequences to construct a char8_t string (to not rely on file/compiler encoding), I got issue with MSVC. I wonder if it is a bug, or if it is implemention dependent. Is there a workaround? constexpr char8_t s1[] = u8"\xe3\x82\xb3 \xe3\x83\xb3 \xe3\x83\x8b \xe3\x83\x81 \xe3\x83\x8f"; constexpr un...
This is a bug in MSVC that I expect to be fixed at some point during Microsoft's implementation of C++23. Historically, numeric escape sequences in character and string literals were not well specified in the C++ standard and this lead to a number of core issues. These issues were addressed by P2029; a paper adopted fo...
71,484,271
71,485,268
C++: insert element into std::map<MyStruct> where MyStruct can only be aggregate initialized and contains const unique pointers
Here is what I am trying to do and what I have tried: #include <memory> #include <map> #include <string> using namespace std; struct MyStruct { const unique_ptr<int> a; const unique_ptr<int> b; }; int main() { auto a = make_unique<int>(7); auto b = make_unique<int>(5); map<string, MyStruct> myMa...
Both myMap.emplace(piecewise_construct, forward_as_tuple("ab"), forward_as_tuple(move(a), move(b)) ); and myMap.try_emplace("ab", move(a), move(b)); should work in C++20. You need to construct the pair in-place, because it will be non-copyable and non-movable due to MyStruct. This leaves only the emplace fami...
71,484,680
71,505,403
Match a set of unicode characters with ctre-unicode
Say, I have a string char8_t text[] = u8"• test\n - two\n •• three\n-• four\n"; I would like to substitute any number of consecutive blank characters, -, or • with just a single space. I tried the following: char8_t* b = text + std::size(text)-1; for (char8_t* r = text;;) { auto m = ctre::search<u8R"([\s\-•]+)">(...
I opened an issue in the github repo and the author replied. The Unicode mode of operation is implemented internally by using ctre::utf8_iterator. But in the current implementation, the use of utf8_iterator is triggered only if the search function receives std::u8string_view as the argument. In the current implementati...
71,484,705
71,484,840
C++: Why I can change the assignment of reference on my computer?
I am new to C++, and I am studying the concept of reference. I have studied the fact that a reference should not be assigned to something else once defined and initialized, the description of reference on C++ primer states that once you have bound a reference to an object, then you can't change the object which the ref...
then you can't change the object which the reference is bounded to. I am confused by this statement The statement tries to say, that the reference cannot be modified to refer to another object. The object that is referred can be modified. When left hand operand of assignment is a reference, you are indirecting throug...
71,485,000
71,486,808
NTP timestamps using std::chrono
I'm trying to represent NTP timestamps (including the NTP epoch) in C++ using std::chrono. Therefore, I decided to use a 64-bit unsigned int (unsigned long long) for the ticks and divide it such that the lowest 28-bit represent the fraction of a second (accepting trunction of 4 bits in comparison to the original standa...
Your tick period: 1/268'435'455 is unfortunately both extremely fine and also doesn't lend itself to much of a reduced fraction when your desired conversions are used (i.e. between system_clock::duration and NTPClock::duration. This is leading to internal overflow of your unsigned long long NTPClock::rep. For example,...
71,485,418
71,485,835
runtime error: member access within null pointer of type 'ListNode' - Clone a linked list
I am trying to clone a linked list in reverse order. ListNode* cloneList(ListNode* head) { ListNode *prev = new ListNode(head->val); head = head->next; while (head != NULL) { ListNode *p = new ListNode(head->val, prev); head = head->next; prev = p;...
It is unusual for a clone method to return a new list in reverse order, but OK, if that is your actual requirement. As stated in comments, the code you have shown does not account for the possibility of the list being empty (ie, when head is nullptr), eg: ListNode* cloneList(ListNode* head) { if (!head) return null...
71,485,543
71,486,824
Where does MFC get the Automation IDs from?
I am about to add automatic GUI tests to an MFC application (created with Visual Studio 2019). It seems as AutomationId is something that could be useful when identifying various child windows in the application. When I examined the application using Microsoft’s tool “Visual UIA Verify” I noticed that most of the child...
Automation IDs are obtained from UIA (User Interface Accessibility), you should generally be able to count on them being the same from run-to-run of the same program, but note that a new version may or may not be "the same". From the UIA documentation: Identifies the AutomationId property, which is a string cont...
71,486,284
71,502,376
parquet_cpp StreamWriter not writing anything to file
Hey guys I am using the parquet_cpp's StreamWriter, but the output file is not empty. Even the header was not written, as the file was a 4-byte file. std::shared_ptr<::arrow::io::FileOutputStream> outfile_{""}; std::string outputFilePath_ = "/tmp/part.0.parquet"; PARQUET_ASSIGN_OR_THROW( outfile_, ::arrow::io::...
Yeah. The RowGroup must be flushed too. So all I need is to have: os_.EndRowGroup(); While the data is written out, the parquet file's footer is corrupted and could not be read. I posted a question HERE on this writing out footer issue.
71,486,418
71,486,592
Bubble sort a pack of cards
I have taken myself down a rabbit hole that I do not know how to get out of, I have created a deck of random cards. However, I now need to sort them firstly by suit then by rank in the order of my enum's. Firstly I can't figure out how to get elements from within the vector and within the enum, so I can compare them, s...
The way to access the members of the deck is to write: deck.cards[i].rank or deck.cards[i].suit You have multiple options for sorting. Simply write two functions: void bubble_sort_by_rank(Deck& deck ){ bool swapp = true; while (swapp) { swapp = false; for (int i=0; i < deck.cards.size()-1; ...
71,486,792
71,486,861
no match for 'operator+' (operand types are 'std::basic_string<char>' and 'double') c++
double vitesse(); string description(); string toString() { return nom + " : " + description() + "\nvitesse : " + vitesse() + ", poids : " + poids; } this code is part of class I'm testing, and whene i try to compile it the error in the title pops up return nom + " : " + description() + "\nvitesse : " + vitesse() ...
It's because the function vitesse() returns a double value, which can't be concatenated as-is with strings. I believe if you replace vitesse() in the return value with to_string(vitesse()), it would work.
71,486,864
71,487,375
boost::graph: How to remove in-edges of a previously removed vertex?
I created the simplest directed graph possible using boost::graph, and added 2 vertices that are mutually connected via 2 edges. After removing the first vertex, the second vertex still has an out-edge that points to the previously removed vertex. boost::adjacency_list< boost::vecS, boost::vecS, boost::dire...
The implementation isn't "going through the trouble" - it's just doing anything, because you didn't satisfy the pre-conditions: void remove_vertex(vertex_descriptor u, adjacency_list& g) Remove vertex u from the vertex set of the graph. It is assumed that there are no edges to or from vertex u when it is removed. One ...
71,486,992
71,501,520
gnuplot visual studio invalid command error in console
This is the following code I have for plotting a series of random points in gnuplot. I have no errors in gnuplot-iostream header. #include <iostream> #include <vector> #include <random> #include <numeric> #include "gnuplot-iostream.h" int main() { Gnuplot gp("\"C:\\Program Files\\gnuplot\\bin\\gnuplot.exe\""); ...
For debugging I used 5 points instead of 1000, so it was easier to see the first error: line 6: undefined variable: v0 It turns out that the title of the first plot must be quoted: gp << "plot '-' with lines title 'v0'," There is also a typo in the second one, it must be lines instead of lins: << "'-' with lines ...
71,487,302
71,501,314
How to build SDL_Image from FetchContent?
I'm attempting to build a C++ program with SDL2 and SDL_Image using CMake by fetching them from their respective GitHub repositories; and it works for the most part! When I ran my code with SDL2 everything built fine, and when I added the code for SDL_Image everything compiled without a problem. However, things break w...
There are two problems with your CMake file: GIT_TAG release-2.0.5 If you look at the SDL_Image repo at that tag, there's no CMakeLists.txt file. That is indeed the most recent tag, though. But fortunately, according to the docs you can use a git SHA for GIT_TAG. With the most recent git SHA at the time of writing, tha...
71,487,540
71,487,624
Can access private sections in Singleton class
I wrote an singletone class as below: class logger { FILE *__fp_log = NULL; const char* __logpath; //Constructor logger(); static logger* __instance; logger& operator=(const logger &) ; logger(const logger &); public: ~logger(); void write_file( const char* ,... ); static logger*...
You're not performing any copying or assignment of loggers here. You're copying/assigning pointers to logger, which doesn't involve the logger object being pointed to at all. The operation you're trying to prohibit would be something like: logger log = *logger::getInstance(); // Dereferencing and copying to separate ...
71,488,084
71,488,551
Proper declaration of C++ private standard library type member
I'm trying to declare a priority queue as a private member so all other methods in the class can access it. However, I am not able to get this to work with a custom lambda compare function. Moreover, what is the recommended way of handling such situations? This works: private: priority_queue<int, vector<int>, great...
The problem here is a fairly subtle one. Before C++ 20, lambdas are not default constructible, but from C++ 20 on, they are. So looking at this: priority_queue<int, vector<int>, decltype(comp)> pq; we can see that pq only knows the type of your comparator and will need to instantiate that type itself. But, before C+...
71,488,464
71,489,051
Is way to get more colors in windows console (c++)?
Is way to get more colours in windows console (c++)? by "more" i mean RGB colours, i have tried: CONSOLE_SCREEN_BUFFER_INFOEX info; info.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX); HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfoEx(hcon, &info); info.ColorTable[0] = 0x505050; info.ColorTab...
From some of the documentation on the console API, specifically relating to Virtual Terminal Sequences for Extended Color: Some virtual terminal emulators support a palette of colors greater than the 16 colors provided by the Windows Console. For these extended colors, the Windows Console will choose the nearest appro...
71,489,173
71,546,749
Integrate pre-compiled libraries into C++ codebase with CMake ExternalProject
I want to integrate CasADi into a CMake-based C++ codebase as an ExternalProject. For this purpose, I would like to use pre-compiled libraries because building from source is not recommended. So far, I have only managed to write the following: ExternalProject_Add( casadi-3.5.5 URL https://github.com/casadi/casadi/r...
There is a natural problem with ExternalProject_Add: ExternalProject_Add executes commands only on build. Hence, download will not happen at the configure stage of your project which makes it difficult to use find_package, because the files cannot be found during your first configure run. Take this CMakeLists.txt: cm...
71,489,212
71,489,608
Visual Studio 2019 Preprocessor definition as a result of cmd/sript
How can i make a definition as a variable from an evaluated expression? I add in my c++ project ( Visual Studio 2019 ) in the Project->Configuration Properties-> C/C++ -> Command Line /D "__MYVAL__=$(python3 .\calc.py)" but i get errors "the expression cannot be evaluated". How can i do this in visual studio 2019 prepr...
So this is not actually a Visual Studio thing - this is one level deeper. Welcome to the relatively unknown world of MSBuild. MSBuild is the backend build engine for Visual Studio. It handles all the elements of the build process, and is responsible for managing and evaluating properties of the build, executing targets...
71,489,412
71,490,265
What exactly is the -xhost flag?
I am having trouble understanding the purpose of the -xhost flag used with icc. On the intel website, it states: xHost, QxHost Tells the compiler to generate instructions for the highest instruction set available on the compilation host processor. I am not sure what is meant by "highest instruction set". Also, I see ...
The -xhost flag generates the most optimal code possible, based on the capabilities of your current CPU (that is, the one in the computer you're using to do the compilation). By "highest instruction set", it means that the compiler will automatically turn on the code-generation flags corresponding to the highest instru...
71,490,067
71,491,023
how do I change the way VS comment out the lines from `//` to `/**/`
In Visual Studio, I selected the lines and click "Comment out the selected lines" in the tool bar. The VS will put // in front of all selected lines. How do I change the style so that the VS put the selected lines in between /**/?
Currently, there is no such setting you want in C++ project. You can go to Developer Community to propose this new feature and post the link in comment. In addition, Visual Studio now supports Ctrl + Shift + / to comment and uncomment.
71,490,470
71,490,485
Reading input with varying number of ints each line in C++
I am trying to read in user input from the console. The data is as such 3 3 100 5 100 6 9 200 6 9 Where the first line represents N, and there are 2*N entries following it. How would I decide whether a line has two int inputs or just one. I thought about implementing getline, but that just gives me the whole line, and...
I always use getline and parse the string myself. This gives you the most flexibility and is pretty much a requirement when you get to the point that you want to do error handling. It's not that hard to split a string into pieces based on a common delimiter (like a space). And writing that code is good practice for you...
71,490,651
71,491,337
va_arg returns different values on x86 and ARM
I'm a new developer on a team who was just given a new Macbook with an M1 Pro (ARM). The rest of my team uses Intel Macbooks (x86). I ran a test which was supposed to create a file and write to it, however, the test errored out because the file was created with incorrect permissions. I traced it back to a wrapper funct...
It is undefined behavior to call a function through a function pointer of the wrong type. In this case, open has signature int(const char*, int, ...) and is being called through a int (*)(const char*, int, int). I would say it's a miracle this code ever works on any architecture! The (IMO quite confusing, consider not ...