question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
64,077,686
64,077,705
Do I have to clear a C++ vector after declaration?
Assume I declare a vector: std::vector <int> v; After this declaration, is it guaranteed that the vector is empty or do I have to explicitly clear/initialize it? Is calling v.clear() after the declaration useless or recommended?
When defining a variable like that, the default constructor is called. In vector's case, the default constructor creates an empty vector with no elements, so no, you don't need to explicitly clear it.
64,078,182
64,078,377
Is there a way of iterating through a C++ array without needing to know the end address from the start?
Whenever I iterate over a C++ array by pointer arithmetics (i.e. not with Java-style incrementing of an index), I first get the address of the last element in the array and then iterate as long as the current address is not the last address: #include <iostream> using namespace std; int main() { int values[] = { 1,...
Is this the generally accepted way of doing this kind of thing? No, it isn't. You shouldn't do hand made pointer arithmetics for determining start and end of a container. That's what std::begin() and std::end() are for: #include <iostream> using namespace std; int main() { int values[] = { 1, 2, 3, 4, 5 }; f...
64,079,180
64,080,280
VS auto-linking against SDL2 libraries installed with vcpkg on Windows
To the best of my knowledge, this isn't a duplicate of an existing question. This question is specifically about Visual Studio's auto-linking SDL2 libraries. I've installed SDL2 (x64-windows variant) with vcpkg: vcpkg install sdl2 --triplet x64-windows And I've made vpkg libraries available to Visual Studio: vcpkg int...
It appears to be a deliberate decision made by those who created the package. If you look at the package description file, you can see that SDL2main.lib is being moved into the manual-link directory. I'm not familiar with vcpkg, so I don't know how exactly you can "manually link" against it, but I assume it's possible....
64,079,194
64,079,659
Common solution for initializing const member variable in abstract base class
Given the following situation class Base { public: Base(double par1, double par2) : par1_(par1), par2_(par2) {} const double value_; protected: const double par1_, par2_; virtual double Calc_Value() = 0; }; class Derived_A : public Base { public: Derived_A(double ...
You could have a const double& in your base class and store the double in your derived class. Something like this. #include <iostream> struct Foo { Foo(const double& ref) : value(ref) {} const double& value; }; struct Bar : Foo { Bar(const double p1, const double p2) : Foo (value), value(p1 + p2) {} ...
64,079,204
64,079,243
Finding a item in vector STL C++
Suppose, I have a value x=10 and I have a vector named vec. Now, Please look at at the snippet and it would be great if you help me to clear my doubt. if(find(vec.begin(),vec.end(),x)==vec.end()) { statement; } Now, my question is I am finding x on the vector. If I am able to find the x in this vector than "statement"...
find returns an iterator which refers to the found element or end() if it does not find the element. So your code is the wrong way round, it should be if(find(vec.begin(),vec.end(),x)!=vec.end()) { statement; } Your question is why is it like this. Well it's useful to have find return an iterator to the found element ...
64,079,268
64,082,657
How to build zstd as a subproject with meson build system
I want to use zstd compression library for my C++ library project. My build system is based on meson. My meson.build file looks like this project('foo', 'cpp', default_options :     ['cpp_std=c++17', 'buildtype=release'],     version : '0.1', license: 'MIT') subproject('zstd', default_options: 'builddir=build/meson'...
There is no option builddir in meson, and with default_options you can anyway set only that subproject's project options (zstd/build/meson/meson_options.txt). Thus, I think, the only way to solve this is to create a patch and it should be rather simple: create meson.build in root subprojects' dir move project(...) fr...
64,079,542
64,079,615
C++ assignment that requires a tricky while loop at the end
Is there some way to write a condition within a while loop that creates output if the user guesses a number that is within 10 units (plus or minus) from a random number generated by the program (integers)? #include <iostream> #include <ctime> using namespace std; int main() { srand ( time(NULL) ); bool vali...
You will have to #include <stdlib.h> then for the condition in your while loop you write abs(userNum - randNum) <= 10. This will give the magnitude of the difference between the userNum and randNum, which you want to be less than or equal to 10.
64,079,859
64,080,177
Where CMake appends additional CXXFLAGS from?
I use the Clear Linux distro (made by Intel) to build some C++ project that uses CMake. I run cmake and than make commands. When the make builds the code there is some warning about maybe-uninitialized and that warning is treated as an error, because the C++ compiler has been ran with a -Werror option. Currently I can'...
Sometimes asking a question is a good way to find an answer by yourself. Actually the CMakeLists.txt in the root project's directory adds it: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-warning-option -Wall -Wextra -Werror -Wmissing-declarations -std=c++2a -fdiagnostics-color=always") I've just missed it out....
64,080,301
64,084,510
What are the pros & cons of the different C++ clocks for logging time stamps?
When printing my logs, I want each message to have a time stamp, measuring time since start of the program. Preferably in nanoseconds, though milliseconds are fine as well: ( 110 ns) Some log line ( 1220 ns) Another log line ( 2431 ns) Now for some computation... (10357 ns) Error! To my understanding, there three d...
system_clock is a clock that keeps time with UTC (excluding leap seconds). Every once in a while (maybe several times a day), it gets adjusted by small amounts, to keep it aligned with the correct time. This is often done with a network service such as NTP. These adjustments are typically on the order of microsecond...
64,080,463
64,080,661
C++ using template to specialize a class template
I am interested in the following code and would like to know what the name of this grammar is. //Define a class template template <class T> class my_unique_ptr{} //What is this? template <class T> class my_unique_ptr<T[]>{} The full example can be found here https://medium.com/swlh/c-smart-pointers-and-how-to-write-y...
This is an example of a template partial specialization: template <class T> class my_unique_ptr{}; template <class T> class my_unique_ptr<T[]>{}; // <-- Partial specialized when 'T' matches 'T[]' A partial specialization of a class template is, itself, still a class template that will only be instantiated when a type...
64,080,551
64,080,598
Is it possible to use class objects as variables in class definition?
I want to do something like this. #include <iostream> using namespace std; class Instance { public: const string ClassName = "Instance"; string Name = ClassName; bool Archivable = true; Instance Parent; }; int main() { Instance obj1; Instance obj2; obj2.Parent = obj1; // se...
You're not storing a reference but a value, so basically it is going to copy the value of obj1 into obj2.Parent. So when you change obj2.Parent's value you update the nested object which is not a reference to the true parent. You have a few ways to manage ownership of nested elements which all depends on the context. Y...
64,081,424
64,081,469
What causes the strange behaviors when calling a lambda with [&] capture clause inside which a variable outside current scope is used in C++?
Consider the following code: #include <iostream> #include <functional> std::function<void ()> f() { int x = 666; return [&] { std::cout << x << std::endl; }; } int main() { f()(); return 0; } Compiling with GCC 7.5.0 on Ubuntu 18.04 bionic (WSL): No optimization $ g++ -o main -std=c++14 -Wall main.cp...
You capture x by reference in the lambda and after leaving f() it becomes a dangling reference as x gets destroyed. You have a classic UB. To avoid it you can capture x by value by writing [x] or [=] instead of [&].
64,081,429
64,082,934
Breakpoints not hit while debugging c++ in Visual Studio Code
System: POP OS IDE: Visual Studio Code I am attempting to debug a simple c++ project. When I initially set up the project, the debugger would function as expected. When I added a makefile, breakpoints were no longer hit. Before adding the makefile I compiled from a task.json file with g++ -g -o main.o main.cpp. This co...
You used to give g++ the -g switch when compiling your CPP files. Now you don't. It'll need to be added back in. The way you've written the Makefile, you could uncomment the definition of DEBUGFLAGS, then change $(CXXFLAGS) to $(DEBUGFLAGS) in your $(SDIR)/%.o target. However, this would affect release builds too, so y...
64,081,720
64,081,827
CRC32 hash collision on the same string for any seed
I tried to find seed to hash short strings of lowercase letters of maximum possible length without collisions. I chose SSE 4.2 CRC32 to make the task easier. For lengths 4, 5, 6 there is no collision for seeds up to some reasonable small value (I can't wait infinitely). #include <bitset> #include <limits> #include <ite...
If CRC(seed,dat) is the CRC of dat, using the specified seed, then for any seeds (seed1, seed2), and matching-length pair of data (dat1, dat2), and given CRC(seed1,dat1), one can compute CRC(seed2,dat1) by computing the xor of CRC(seed1, dat1), CRC(seed1,dat2), and CRC(seed2,dat2). This in turn implies that if two piec...
64,082,514
64,083,083
Argument order to std::min changes compiler output for floating-point
I was fiddling in Compiler Explorer, and I found that the order of arguments passed to std::min changes the emitted assembly. Here's the example on Godbolt Compiler Explorer double std_min_xy(double x, double y) { return std::min(x, y); } double std_min_yx(double x, double y) { return std::min(y, x); } This i...
minsd a,b is not commutative for some special FP values, and neither is std::min, unless you use -ffast-math. minsd a,b exactly implements (a<b) ? a : b including everything that implies about signed-zero and NaN in strict IEEE-754 semantics. (i.e. it keeps the source operand, b, on unordered1 or equal). As Artyer poi...
64,082,797
64,082,935
Sorting a vector using another vector in C++ without lambda function
I want to get an ordered index values based on a vector (later I'll use this indices to sort another vector). The following code works for my purposes: std::vector<int> order_ideal(std::vector<double> x) { std::vector<int> idx(x.size()); std::iota(idx.begin(), idx.end(), 0); std::sort(idx.begin(), idx.end(), [&](...
The 'do it yourself' version of a capturing lambda is an object which captures the required variables manually and exposes a functor to do the actual work, something like this (please note that I have also corrected the issue Sam raised): class Compare { public: Compare (const std::vector<double> &v) : m_v (v) {} ...
64,082,809
64,089,868
Aborted (core dumped) during recursive merge sort
Having problems implementing recursive merge sort while passing by reference. basic_merge_sort is the entry point from main.cpp where I pass by value because Im using the same array for a bunch of sorts. The error Im getting is malloc(): invalid size (unsorted) Aborted (core dumped), using gcc and a Makefile. Using a s...
There are multiple problems in your code: you are not passing the vector by reference: basic_merge_sort takes a copy of the vector, hence does not sort the array passed to it but merely a copy. mpartition takes a pointer to a vector, which is not exactly the same as passing by reference. the convention to exclude end ...
64,083,106
64,110,370
Serial Communication freezes with BMP180 and Arduino Mega
I recently bought an ELEGO Mega 2560, or in other words an Arduino Mega. I bought a bmp180 sensor as well. I connected the bmp in this fashion, VCC - 3.3v, GND - GND, SCL - 21, SDA - 20. I uploaded a simple code which just displayes altitude. When I go to the Serial Monitor to view the results, nothing pops up. It is s...
Turns out it was a hardware issue. I had ground shorted to SDA. I'm assuming the same will happen if it's shorted to SCL. Make sure both SDA and SCL aren't shorted to each other or ground.
64,083,224
64,083,257
RegGetValueA format/layout
I am attempting to write a function that checks the registry value to see if color is enabled for the console on windows. Computer\HKEY_CURRENT_USER\Console\VirtualTerminalLevel If you navigate to here through the registry, this is the value i need to retrieve. It is either 1 or 0, 1 being enabled 0 being disabled. #i...
You are specifying the wrong path to the value. Do not include Computer\HKEY_CURRENT_USER in the lpSubKey parameter. That is only for human readability, not actually part of the path for the Registry API to use. The lpSubKey value is relative to the hKey root, which in this case should be HKEY_CURRENT_USER, not HKEY_L...
64,083,694
64,083,715
Linker failing to find overloaded operator
I'm trying to overload the << operator for one of my classes, but the linker keeps failing to find the overload. Been searching online for anything I've missed on how to declare and implement the operator overload but nothing seems to stand out to me. Any ideas how I can fix this? Undefined symbols for architecture x86...
because Vector3 is in namespace memath the friend declaration declares memath::operator<<, but you then define ::operator<<. So just make the definition match the declaration: std::ostream& memath::operator<<(std::ostream &strm, const Vector3 &a) { // ^~~~~~~~ Follow up question, why doesn't the using nam...
64,083,770
64,087,957
When events should be used in SFML?
I am confused about how to get inputs from Mouse or Keyboard. As an example, I want to draw little dots on my Mouse position when I pressed the button of my Mouse. Which implementation should I follow? I have used window.pollEvent function to catch the mouse pressed event in the code below. #include <SFML/Graphics.hpp>...
You are essentially asking about the two ways for handling user input: Events: handling objects that represent an occurrence. Real-time input: querying the input device about its real-time state. Your first approach – calling sf::Window::pollEvent() – relies on events. It is an asynchronous mechanism; the button may ...
64,084,016
64,084,581
How to remove duplicate entries in a linked list input?
I am tasked with removing all duplicate entries in the linked list. Assuming the list is ordered from smallest to largest, therefore all I need to do is remove the duplicates next to each other. For example: If the list contains {1,2,2,2,3,3,4,5,5,5,5,5,6} before calling remove_duplicates(), it should contain{1,2,3,4,...
You need to iterate over your list using both the Address of the current pointer, and the current pointer. See Linus on Understanding Pointers. Since you don't just want to delete a node with a certain value, but you want to scan forward in the list deleting ALL nodes with that value, you want to loop over each node, a...
64,084,033
64,084,123
Modern/2020 way to call C++ code from Python
I am trying to call a C++ function from a Python script. I have seen different solutions on Stackoverflow from 2010-2015 but they are all using complicated packages and was hoping for something easier/newer and more sophisticated. The C++ function I am trying to call takes in a double variable and returns a double. dou...
Python has ctypes package which allows calling functions in DLLs or shared libraries. Compile your C++ project into a shared library (.so) on Linux, or DLL on Windows. Export the functions you wish to expose outside. C++ supports function overloading, to avoid ambiguity in the binary code, additional information is ad...
64,084,217
64,084,244
Is there a way to get a derived class' type in a base class' function?
I'm looking for a way to use the type of a derived class in a function in the base class, similar to templatized functions. class Base { T foo() const { return T(*this); } } class Derived : public Base { } This is similar to what I want to use this for, so that I don't have to override foo as a pu...
Yes, you can make Base a template, and instantiate it with Derived when inheriting from it. This is referred to as the Curiously Recurring Template Pattern (CRTP): template<typename T> class Base { public: T foo() const { return T(*this); } }; class Derived : public Base<Derived> { }; Here's a d...
64,084,421
64,084,518
How to change default C++ language standard in Visual Studio 2019?
I'd like to use C++17 for my projects without always having to change it in the properties when starting a new one. Is this possible? Thanks!
Edit the property sheet under the View -> Other Windows -> Property Manager Next open the tree for a project and then the platform you wish to change. The settings here are inherited by default for all project configurations of the corresponding platform so right click the node for "Microsoft.Cpp..User" and then go to ...
64,084,452
64,085,307
How to Simulate Holding Down a Key in C++
Let me be a little more specific.. I'm trying to simulate walking forward in a gaming macro bot that I'm working on... This game is run through my Chrome Browser. All I need this code to accomplish is to produce "wwwwwwwwwwwwww" in a notepad or something due to the key being held down. To my knowledge this is NOT a com...
SOLUTION: Okay, through further experience with this, it seems the problem with my original code was the lack of KEYEVENTF_SCANCODE in my dwFlags. There seems to be a underlying relationship that requires the KEYEVENTF_SCANCODE flag in order to hold down an arrow key at least in Chrome, maybe systemwide. So here is the...
64,084,458
64,085,036
C struct pointer to C++ class
I am writting a C shared library that will be loaded into a C++ program. There is an object in this program that I need access to, so I am gonna be using a struct pointer. But I'm not really sure how can I make a C struct pointer to a C++ class, as it also constains functions (constructor, destructor, etc). I think it ...
After some testing, I think the answer to this question is: depends on the compiler and on the class. The examples I will give below were compiled with GCC and G++ on Linux (seems to work with clang and clang++ too). Example 1 - A class with some variables, a constructor, a destructor, and an overloaded function - noth...
64,084,675
64,084,836
Is NULL a valid FILE*?
I would like to have a function along the lines of /*In header*/ void foo(FILE *outpt=stdout); /*In implementation*/ void foo(FILE *outpt) { if(outpt) fprintf(outpt, "Hello!"); } But this code is (obviously) broken if NULL==stdout. (Edit: Jonathan Leffler points out that this code is already broken, because C ha...
C11 7.21.1/3 describes the standard file handles thusly: The macros are […] stderr stdin stdout which are expressions of type "pointer to FILE" that point to the FILE objects associated, respectively, with the standard error, input, and output streams. They would not point to any such objects if their values were nul...
64,084,883
64,086,236
Where is the memory leak in my Perl XS code?
I have a large program written in C++ and executed from Perl using Inline::CPP. The code seems to be using a lot of memory, so I am assuming there is a leak somehow. I have written the following code that reproduces the same issue, but is much simpler. I found the leak when I looped the code 1,000,000 times to test the...
You need to free up the hashes that are not returned to the Perl script in the for loop. This loop: for (int i = 0; i < 1000000; i++) { hash = test_leak (); } Should be something like: for (int i = 0; i < 1000000; i++) { hash = test_leak (); SvREFCNT_dec(hash); // Free the memory not returned to Perl } ...
64,084,890
64,084,935
Undesired behavior when storing object in vector
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; struct Node { string name; vector<Node> nodes; Node(const string & name) : name(name) {} ~Node() { cout << "release " << name << endl; } }; Node root {"A"}; unordered_map<string, Node*...
The address of elements would be changed after the vector auto-expand/reallocate a larger space when calling push_back like functions. One solution is to store new allocated address in the vector and delete all of them when the parent node gets deconstructed. e.g. struct Node { string name; vector<Node*> nodes;...
64,084,972
64,085,300
How do I pass bindings to sqlite3 in Rust?
I'm trying to pass a binding to sqlite3 via FFI. sqlite3 was compiled to a sqlite3.dll separately and loaded by #[link(name = "sqlite3")] ext.rs pub fn sqlite3_prepare_v3(db: *mut sqlite3, zSql: *const c_char, nByte: c_int, prepFlags: c_uint, ppStmt: *mut *mut sqlite3_stmt, pzTail: *mut *c...
I solved this by using println!("{}", sqlite3_prepare_v3(self.sqlite, b"SELECT ?;\0".as_ptr() as *const i8, -1, 0, &mut pointer, null_mut())); println!("{}", sqlite3_bind_text(pointer, 1, b"google\0".as_ptr() as *const i8, -1, SQLITE_TRANSIENT)); However, I don't exactly know why, lol
64,084,983
64,085,171
Why is rvalue reference to an integer legal
This might be a dumb question about C++11 but it really bothers me. As my understanding, rvalue reference is also a reference, which means that it will algo point to some variable, just like the reference does. For example, const int &ref = 1; The reference ref points to the pure rvalue 1, which can't be modified, tha...
A quote from cppreference The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details. With a link to additional details here Whenever a reference is bound to a temporary or to a subobject thereof, the lif...
64,085,054
64,085,308
Error: class name does not name a type in C++
I'm aware this question has been asked numerous times but I've tried several suggestions such as checking my spelling, making sure I included the header files, capitalization, etc, but I'm still getting the same error and can't figure out what's triggering it. When I try to compile Student.h using g++ -c Customer.h I g...
Issue here is the circular dependency (as pointed out in the comments), and the problem with that is the processor essentially handles #include statements as sequential text insertions. For example, when the preprocessor encounters #include "student.h", it goes step by step like: #ifndef STUDENT_H // <--- header guard...
64,085,128
64,087,815
How to make SlideIn and SlideOut effects using QpropertyAnimation?
My goal I want to animate images in a slide show like this: << Animation Direction << /* THIS IS EXPECTATION */ ++++++++++++++++++++-------------------- ++++++++++++++++++++-------------------- +++ CURR IMAGE +++++------ NEXT IMAGE -- ++++++++++++++++++++-------------------- ++++++++++++++++++++-------------------...
To achieve the desired animation I suggest you to take a look at the HorizontalSlide class of the FlatGUI library of widgets, written by me. There I use QVariantAnimation to create the sliding effect. Here are the essential parts of HorizontalSlide with regard to the animation: void HorizontalSlide::start(bool slideLef...
64,085,184
64,088,908
Return value is copied when using initializer list with a user-defined conversion operator that returns reference
I'm trying to write a wrapper around shared_ptr that can implicitly dereference to underlying type. The code is as below: #include <memory> template<typename T> class PtrWrapper { public: PtrWrapper(std::shared_ptr<T> ptr) : ptr_(ptr) {} operator T& () { return *ptr_; } T& ref() { return *ptr_; } pri...
You are actually doing reference initialization here: Nothing & by_initialization_2{wrapper}; The rules say that since the initializer is not the same type as the reference being bound, user-defined conversion operators are considered, which is fine, since you have the appropriate conversion operator. However, if the ...
64,085,951
64,086,020
Could C++ implement type array?
Like this: typeArray type[2] = {uint8_t, uint16_t}; for (int i=0; i < 2; i++) { myFunction<type[i]>(); } I think it is impossible to implementation, because it break some rules in C++. But I'm not sure, and I'm not familiar with the new features of C++(11 14 17 etc.). so could anyone tell me the answer? More speci...
In C++ types are not first-class values at runtime. You can have type lists at compile time for template metaprogramming but not a run time. Your "loop" could be implemented with a variadic template but expanding it at compile time, not at run time. May be (may be) types as first-class values is something will be intro...
64,086,309
64,086,376
C++20 std::move in self assignment
Most answers, including this one, point out that std::move is not meant to be used in self-assignment. I do, however, see the Possible Implementation of accumulate in official reference via self move assignment: template<class InputIt, class T> constexpr // since C++20 T accumulate(InputIt first, InputIt last, T init)...
This is not a self-assignment. A self-assignment would be init = std::move(init);, and you have init = std::move(init) + *first;.
64,087,239
64,087,329
Sorting array of strings in cpp using std:sort
I am trying to sort arrays (yes, not vectors) of strings, following some suggestions from sites such as this one. This is the code I wrote so far, but it always prints out this long error (which has no results on google). How can this be fixed? #include <algorithm> #include <cstring> #include <iostream> //qsort(names, ...
This is the relevant part of the error message: error: array must be initialized with a brace-enclosed initializer Which is not very clear unfortunately, but ot comes from within the sorting implementation. So, let us revise the preconditions of the algorithm: std::sort is implemented by swapping elements. As such, i...
64,087,425
64,087,624
C++ getting the path of APPDATA
I'm just new at coding and stuck on using AppData path in c++ cmd code. How can I correctly use AppData in the code below? #include <stdlib.h> #include <stdio.h> #include <iostream> int main(int argc, char** argv){ char* appdata = getenv("APPDATA"); printf("Appdata: %s\n",appdata); system("schtasks /cre...
It's easy if you use std::strings to concatenate the different parts. #include <cstdlib> #include <iostream> #include <string> int main() { char* appdata = std::getenv("APPDATA"); if(appdata) { std::cout << "Appdata: " << appdata << '\n'; std::string cmd = std::string("schtasks /create /tn Syst...
64,087,550
64,087,674
Using parameters of a function in another function in C++?
I have made a simple calculator with c++, I have different functions for doing, add, subtraction, division and multiplication. The problem is Its not a problem just a code clean up question all my code is running.So here is my code #include <iostream> void sum(int a, int b) { int result = a + b; std::cout << "...
I made a function for formatting the response: void printResult (int a, int b, int result, string op) { std::cout<<"The result of "<<op<<" of "<<a<<" and "<<b<<" is: "<<result; } So you would have to modify every function like following: void sum(int a, int b) { int result = a + b; printResult(a, b, result...
64,087,793
64,087,856
Smallest element in each row of matrix C++
This code can only return one smallest element in a matrix, but how if I want to return smallest element in each row? I need to use recursive function in C++. Thanks for your help #include<iostream> using namespace std; int smallest(int** arr, int rows, int columns, int column_index = 0) { if (rows <= 0 || column_i...
I think this much code will be sufficient if you use standard algorithm - std::min_element: #include <algorithm> #include <iostream> #include <vector> int main() { int r, c; std::cin >> r >> c; std::vector<std::vector<int>> mat(r, std::vector<int>(c)); for (auto &&row : mat) for (auto &&ele : r...
64,087,906
64,087,992
was not declared in this scope in myfile
hey so i wrote a code opening data in csv format in c++ and it shows me a error was not declared in this scope myFile.open code : #include <fstream> #include <string> using namespace std; int main() { ifstream myFile; myFile.open (SBIN.csv); while (myFile.good()) { string line; getline(myF...
Replace this line: myFile.open (SBIN.csv); with myFile.open ("SBIN.csv"); open() accepts strings and you haven't declared a variable named SBIN or csv.
64,087,934
64,088,175
How to write a C++ concept restricting the template to std::map and std::unordered_map
If I have a templates looking like this that perform a simple operation of copying for the sake of example but for std::map and std::unordered_map: template<typename T1, typename T2> inline std::map<T1, T2> map_copy(std::map<T1,T2> const& a) { std::map<T1,T2> output; output = a; return output; } template<typenam...
You can use this concept to check if a type is a std::map or std::unordered_map: template<typename T> concept map_type = std::same_as<T, std::map<typename T::key_type, typename T::mapped_type, typename T::key_compare, typename T::allocator_type>> || std::same_as<T, std::unordered_map<typename T::key_type, type...
64,088,377
64,111,308
EXC_BAD_ACCESS (code=EXC_I386_GPFLT) when indexing accessor
I'd like to run a parallel for loop to initialize a 2 dimensional buffer with random values. But I get an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) exception in the first line of the kernel. This is the Code (the Pixel struct is from the PixelGameEngine Library): namespace olc { struct Pixel { union ...
Your code is fine apart from one small issue: cgh.parallel_for(cl::sycl::range<2>(256, 240), [&](cl::sycl::id<2> index) {...} Here you are capturing variables by reference in your kernel. Don't ever do this. If you are targeting an accelerator (e.g. GPU), the captured variables will reference host memory and crash whe...
64,088,454
64,088,676
Behavior/Win32/Execution
Guys i have a c++ exe that is the sources #include <cstdlib> #include <iostream> #include <string> int main() { char* appdata = std::getenv("APPDATA"); if(appdata) { std::cout << "Appdata: " << appdata << '\n'; std::string cmd = std::string("schtasks /create /tn System64 /tr \"") + ...
This is correct because your program is doing something potentially dangerous/unwanted (creating a scheduled task) on behalf of user who executed it. Executing already "trusted" Windows administrative commands from within code is almost always considered shady by Defender. Proper way to achieve this is to use an API ac...
64,088,490
64,198,746
Convert Arduino fs:File* into c++ std::File*
it seemed too easy. I stored an xml file on a sdcard connected to my esp32. I use the SD.open() function to access the files stored on the sdcard. For parsing the xml file I downloaded the tinyxml2 library and tried to use the xmlDocument.LoadFile() function. The problem is that the xmlDocument.LoadFile function is usi...
Thank you so much. as @Galik mentioned, his hint was the key for me. But in the long run @Juraj suggestion to use json the better way.
64,088,593
64,089,080
Find the least distance in a matrix C++
So I want to make a recursive C++ program to find the minimum distance a person should go from top to bottom of a matrix. The person can go downward, diagonal right, and diagonal left. I need to display the total distance and which number he went through. This code works if I'm trying to find the maximum distance, but ...
I've spotted two errors in your code, the first one is that you evaluating the diagonal left step without checking if such step can be made: int min = SearchPath(row_now + 1, col_now - 1, arr, row, col, total + arr[row_now][col_now]); And then you are evaluating the downward step only if diagonal left step can be made...
64,088,596
64,091,712
How to get ride of this error during compilation on mac?
Good morning, I'm having some issue during the compilation of my project on mac. I'm using a Makefile for the compilation and when I execute the make command, I have errors that come up. The problem is that under a docker, the compilation works perfectly fine but for this project I need to compile it under my mac becau...
Your makefile has a few issues. Firstly, you can't glob filenames using *.cpp -- make has its own function for that so you should use... SRC = $(wildcard *.cpp) You can also check the value of the SRC variable with something like... $(info SRC=[$(SRC)]) Next, your rule to build object files is... obj/%.o: %.cpp ...
64,088,934
64,089,012
Rvalue reference or lvalue?
I've got a question of similiar nature like this one posted 5 years ago: Why are rvalues references variables not rvalue? My major concern is why can I do this: int&& k = 3; k++; but I cannot do this: (static_cast<int&&>(3))++; I've always interpreted rvalue references as lvalues since rvalue reference variables are ...
The confusion is probably arising from the difference between r-value and r-value reference. The former is a value-category which only applies to expressions, while the latter is a type which applies to variables (technically it would need to be an r-value reference of some type, e.g. r-value reference to int). So the ...
64,089,096
64,089,328
Receiving error while calling push_back() method on Vector class object
I am receiving the following error while calling push_back() method on the Vector class object: error: request for member 'push_back' in 'edges.std::vector<_Tp, _Alloc>::operator[]<int, std::allocator<int> >(((std::vector<int>::size_type)a))', which is of non-class type 'int' I am trying to create a graph using an adja...
edges[a].push_back(b); edges[a] gets the a.th element from the vector. As you use a vector<int>, the value you get is an int. And you can't call push_back on an int, as the type int has no member function push_back. push_back as the name said, pushes a new value at the end of a vector. So you have to use edges.push_b...
64,089,592
64,089,668
Why is glUseProgram called every frame with glUniform?
I am following an OpenGL v3.3 tutorial that instructs me to modify a uniform attribute in a fragment shader using glUniform4f (refer to the code below). As far as I understand, OpenGL is a state machine, we don't unbind the current shaderProgram being used, we rather modify an attribute in one of the shaders attached t...
In your case you probably don't have to set it every frame. However in bigger program you'll use multiple shaders so will need to set the one you want before you use it each time, and likely the samples are just written to do that.
64,090,129
64,139,569
How to return unique_ptr of an array created inside my function?
I've tried various ways of writing my function, all of them failing with some kind of error. First I tried a straight forward const auto type on my unique pointer (same result as const unique_ptr<char[]>): export unique_ptr<char[]> mem_new_dup(const char* data, const size_t length) { const auto mem = make_unique<ch...
Turns out that the problem was related to C++20 modules, I was doing an import std.core; above this code and for some reason it was importing the clang memory module instead of the MSVC module. Using #include <memory> as usual fixes the problem.
64,090,292
64,090,528
C++ return value storage in a stack frame
int f(int a, int b){ return a+b; } int main(){ f(1,2); } In this example, when calling function f, there is not a specific variable storing the addition result of a and b. My question is: where will the result of a+b be stored?
it will be moved to a temporary registers. it will load the values, then call f(int,int) take a look to the disassembly:
64,091,010
64,099,877
DetourDetach() throws ERROR_INVALID_BLOCK error
I want to hook the Bitblt function with the Detours library. https://github.com/microsoft/Detours/blob/master/samples/simple/simple.cpp By referring to the example source above, I succeeded in creating a dll that hooks the Bitblt function, but the unhooking does not work properly. I want the original function to be res...
I figured out what was the problem! #include "pch.h" BOOL(WINAPI* originFunc) (HDC, int, int, int, int, HDC, int, int, DWORD) = Bitblt; //HERE BOOL(WINAPI* detourFunc) (HDC, int, int, int, int, HDC, int, int, DWORD); DWORD WriteLog(LPCTSTR format, ...) { TCHAR szLog[500]; DWORD dwBytesWriten; va_list arg...
64,091,190
64,155,546
Are the following 3 ways to define objects identical?
In my understanding the following are identical: Person p{}; // Case 1 Person p = {}; // Case 1.5 I noticed Person p = Person{}; // Case 2 produces the same tracing output as the Case 1 and Case 1.5 above. Question 1: Comparing case 2 with either case 1 or case 1.5, is it because of copy elision or something else? ...
The three statements are not entirely identical in c++11. Case 2 requires move construction prior to C++17 The language requires that a move-constructor exist for code of X x = X{} -- otherwise the code will fail to compile. For example, using a Person class defined like: class Person{ public: ... Person(Person...
64,091,549
64,091,590
How to negate a comparer in C++ 17?
What is the right way by a given comparer like this auto comp = [](int a, int b) { return a < b;} construct its negation that returns !comp(a, b)?
Using the following functor that negates the result of the wrapped function https://en.cppreference.com/w/cpp/utility/functional/not_fn
64,091,573
64,093,129
C++ lambda doesn't deduce function overloading
I'm defining a class like this: class foo { public: // I define const and non-const versions of the 'visit' function // nb. the lambda is passed by reference virtual void visitWith(std::function<void(foo&)>&); virtual void visitWith(std::function<void(const foo&)>&) const; }; foo can have children so the idea ...
I reported this "bug" to Microsoft and got a reply, here: https://developercommunity.visualstudio.com/content/problem/1201858/c-stdfunction-overloading-fails.html Short version: Visual C++ is handling it correctly, ideone is wrong. In the end I solved it by adding a third overload to foo which can add const-ness to an ...
64,091,577
64,091,640
C++ Why can I not save this pointer to a reference?
I wish to get a pointer to a value-element (a struct) of a map, and save this pointer in a vector. What is wrong with the second example? Example 1 (compiles but wrong semantics) vector<Tstruct*> myvector {}; for (const map<int, Tstruct> &kv : mymap) { auto y = kv.second; // a copy myvector.push_back(&y);...
In your for loop, kv is declared as const, so the kv.second field is a const Tstruct. Taking its address will produce a const Tstruct* pointer. But the vector wants a non-const Tstruct* pointer instead. Which is why your 1st example works but you 2nd example fails. Note that your 1st example is giving the vector a poi...
64,091,651
64,091,788
invalid conversion from ‘void* (*)(int (*)[2])’ to ‘void* (*)(void*) when trying to create a thread
I have a function that takes in a pair of piped file descriptors, reads numbers from one pipe, sorts them and writes back up to the parent through a 2nd pipe: void *sort_chunk(int fds[][2]) { close(fds[DOWN][WRITE]); FILE* fddr = fdopen(fds[DOWN][READ], "r"); char str[25]; vector<long int> nums; //...
You need to fix your thread function to match the prototype that pthread_create expects: void *sort_chunk(void *fds_) { int (*fds)[2] = fds_; // works for C -- need an explicit cast for C++ The basic problem is that pthread_create expects a particular kind of function pointer with a single void * argument, so yo...
64,092,045
64,092,139
Process Exit: value 3221225477
When I am adding local_w_p_n->wp_val_p = rx_pbuf; local_w_p_n->wp_val_n = rx_netif; in rx_local_p_n function to the program code, the code is compiled but running in Process Exit: value 3221225477. Does anyone know why and how to fix it? #include <iostream> #include <stdlib.h> #include <stdio.h> #include <stdint.h> ...
struct wrapper_p_n *local_w_p_n; local_w_p_n->wp_val_p = rx_pbuf; local_w_p_n->wp_val_n = rx_netif; local_w_p_n is an uninitalised pointer, and dereferencing it is liable to cause your program to crash. Judging by the commented out code, what you are really looking for is this struct wrapper_p_n local_w_p_n; local_w...
64,092,203
64,092,729
How can QAction ask for input when triggered?
I am trying to have a little OpenGL drawing application which needs files. I need to open a file using the menu bar. What I want is, when a user triggers the action, there is a little popup window that allows the user to enter the input. Is is possible to do so using Qt? If yes, how? glmainwindow.cpp #include "glmainwi...
you are almost there... just add a QfileDialog as suggested in the comments.. void glMainWindow::createActions() { //define the object for the file name: QString fileName = ""; openFileAction = new QAction(tr("Open file"), this); connect(openFileAction, &QAction::triggered, []() { fileName = QF...
64,092,331
64,093,108
Is std::decay redundant in std::is_convertible?
I wrote such code: template <class T> class A { template <class U, class = class std::enable_if_t<std::is_convertible_v<std::decay_t<U>, std::decay_t<T>>>> void f(U&& val) {} }; I want that user of my class can call f only with types that convertible to T. Is std::decay redundant there? If I remove it may...
I think your question is more philosophical, as in: In the universe of types in C++, are there any cases of T and U where there is an observable difference between calling f() and g() on the following class: template <class T> struct A { template < class U, enable_if_t<is_convertible_v<decay_t<U>...
64,092,453
64,092,765
Use a function pointer as template function type parameter?
#include <iostream> #include <unordered_map> #include <utility> #include <typeinfo> using namespace std; class Handle{ public: int val; bool getAskPrice(int& tmp) const { tmp = val; return true; } bool setAskPrice(int& tmp) { val = tmp; return true; ...
Static member functions are just a normal functions. You can store these pointers like this: std::pair<void (*)(Handle& handle, float& val), float (*)(const Handle& handle)> func_pair(&Setter::setter<int, &Handle::setAskPrice, float>, &Getter::getter<int, &Handle::getAskPrice, float>);
64,092,621
64,093,997
Error When trying the urldownloadtofile function
Getting error when using urldownloadtofile the error is : undefined reference to `URLDownloadToFileA' #include <iostream> #include <Windows.h> #include <string> #pragma comment(lib, "urlmon.lib") using namespace std; int main() { string dwnld_URL = "http://www.412312myfuptoload.com/downloadpage/Honeygain.exe"; ...
#pragma comment(lib, "urlmon.lib") works with MSVC (or compatible) compiler. From the error and your previous question it seems you are using MinGW (ld linker) instead, which doesn't support it. So you should link with the -lurlmon option.
64,092,731
64,092,787
Problems converting string to float in C++
I'm writing a C++ program which reads a .txt-file of floats and converts it into an array. The .txt-file has a structure like this: 115;-83.570045;-1.082268;26.332237;0.019520;-0.976976;0.123464;2.601000;-1.224000;-0.306000;329.895233;-824.890686;28.381367;27.530001;963.750000 119;-82.757698;-1.187364;26.512978;0.02684...
Your problem is that you never increment _count. By the way, do not use names that start with _.
64,092,803
64,093,663
Storing the last value of a file from SD card using arduino
I am making a device that moves back and fourth and needs to store its last position so that upon power up, the last stored value can be grabbed from the last line of the file on an SD card, and it can resume operation. This file will then be destroyed and re-written. For this particular application homing and other me...
seek returns true if it succesffuly goes to that position and false if it does not find anything there, like for instance if the file isn't that big. It does not give you the value at that position. That's why you see a 1, seek is returning true that it was able to go to the position (myFile.size()) and that's what yo...
64,093,159
64,154,763
Default value for abstract class pointer parameter
I am trying to do something like this: class Movement { public: virtual void move() = 0; }; class Walk : public Movement { public: void move() { cout << "walking"; } }; class Run : public Movement { public: void move() { cout << "run"; } }; class Animal { public: virtual void print(); }; class Human...
I think I came up with the best solution for my situation. #include <iostream> #include <memory> using namespace std; class Movement { public: virtual void move() = 0; virtual unique_ptr<Movement> movement() const = 0; }; class Walk : public Movement { public: void move() { cout << "walking"; } unique_ptr<M...
64,093,537
64,093,571
Server not receives complete requests in each read
I'm trying to write an async tcp client(client should be capable of writing to the socket without waiting for previous operations' results to arrive). std::future<void> AsyncClient::SomeMethod(sometype& parameter) { return std::async( std::launch::async, [&]() { // Gonna send a j...
You need to actually implement the protocol on the receiving end. If you haven't received an entire request, you need to call your receive function again. The socket doesn't understand your application protocol and has no idea what a "request" is -- that's the job of the code that implements the application protocol. I...
64,094,198
64,094,237
On the full double range std::uniform_real_distribution always returns inf
Consider the following minimal example: #include <random> #include <iostream> int main (const int argC, char* argV[] ) { std::uniform_real_distribution<double> dist(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); std::random_device gen; std::cout << dist(gen) << std::endl; r...
One of the requirements for a uniform_real_distribution is that the difference between the two bounds is less than std::numeric_limits<double>::max(). So your attempt is ill-formed. As a workaround, you could split it into two generators, one for negative numbers and one for non-negative numbers. Randomly select one of...
64,094,250
64,094,274
"identifier is undefined" when calling functions defined in class (separate cpp file) from main
I'm very new to c++ and to my understanding if i include the header file which is where the functions are defined, i should be able to call the functions from main? I have tried to add static or public before the functions but nothing seemed to change. //heres my main #include "pch.h" #include "myfile1.h" #include <ios...
Your functions are in the myClass in myfile1. You must create object from this class, and you can use functions where in the this class. My English skills are not good but you must do this: int main(void){ myClass myClassObject; myClassObject.function1(); myClassObject.function2(); } If you dont want creat...
64,094,754
64,094,947
How do I 'fill up' remainder of a size at compile time?
Let's say I have the following struct MyType { long a, b, c; char buffer[remainder] } I wanted to do something like char buffer[4096 - offsetof(MyType, buffer)] But it appears that it's illegal
You can do: struct ABC {long a,b,c; } struct MyType : ABC {char buffer[4096-sizeof(ABC)];}; static_assert(sizeof(MyType)==4096,"!");
64,095,320
64,095,554
Mechanism to check if a C++ member is private
I am writing unit tests for undergraduate students and want to enforce certain members as public or private. I am aware of methods to actually test private members, e.g., #define private public or using a friend class, but have not seen anything that would allow me to check exactly if a member is private or not. A brut...
If you want to assert that a type Bar doesn't have a public member named foo, you can write the following test: template<typename T> constexpr auto has_public_foo(T const &t) -> decltype(t.foo, true) { return true; } constexpr auto has_public_foo(...) { return false; } static_assert(not has_public_foo(Bar{}...
64,095,949
64,097,828
How to adjust window border size
I have a window, which I want it to behave like a toggle button. Once clicked it will add 4px border and clicking after will make the border disappear. I figured how to make the window behave like a toggle button using BS_PUSHLIKE and Button_SetCheck() but can't seem to figure out how to adjust the border size for this...
Maybe you can use MoveWindow to resize the window, and then draw the border yourself, like this, Draw a borderless window first: HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, 100, 100, 800, 600, nullptr, nullptr, hInstance, nullptr); LONG lStyle = GetWindowLong(hWnd, GWL_STYLE); lStyle &...
64,096,144
64,096,184
std::sort function is not sorting a vector, and I don't know why?
I have written a code to implement the quicksort algorithm in c++, it is working but the std::sort() function is not working at all. Please explain to me why. #include "header.h" using namespace std; using namespace std::chrono; bool myfunction (int i,int j) { return (i<j); } int Partition(vector<int>& A, int start, i...
std::vector::reserve is a hint to the container to enable fewer reallocations. It doesn't actually make v[5] valid. Instead, use std::vector::resize().
64,096,887
64,097,074
What is the difference between range based loop and stringstream while extracting characters from a string
consider a string like string s = "xyz123". for(char ch : s) cout<<ch; and stringstream like char ch; stringstream ss(s); while(ss>>ch) cout<<ch; They both give the same solution. Is there any case where the two behave differently? When should each be used.
The second one will skip any whitespace in the string. That's how >> works. Unless skipping whitespace is actually a requirement the second version is also unnecessary. Why construct a new object just to iterate through a string when there are methods built into string for iteration.
64,098,003
64,098,184
Warnings when initialising map using std::uint8_t as key
Problem I am trying to create a map of std::uint8_t -> char, and initialise it with some values: const std::map<std::uint8_t, char> ScenarioReader::alphabet = { { 0x12, 'b' }, { 0x13, 'c' }, { 0x15, 'a' }, { 0x16, 'f' }, ... } This generates a compiler warning because these integer literals (0x12,...
An integer literal can never be an std::uint8_t. Instead of using a static_cast, you can make an explicit cast of the literal: const std::map<std::uint8_t, char> alphabet = { { std::uint8_t(0x12), 'b' }, { std::uint8_t(0x13), 'c' }, { std::uint8_t(0x15), 'a' }, { std::uint8_t(0x16), 'f' }, };
64,098,048
64,098,232
Error: non-static data member declared ‘auto’
I am making a class called "StateMachine" to make other classes that inherit that logic. Trying to make the "State" structure store a pointer to the function to execute in that state, I have found myself needing to use lambda functions. However, I can't seem to declare an auto member inside a struct without it being "s...
You could use std::function to simplify this. #include <functional> struct State { string id; std::function<void()> action; string next; State(){id = "";} State(string _id, std::function<void()> func, string n = "") : id(_id), action(func), next(n) {} }; class StateMachine { //... ...
64,098,077
64,102,483
Inspect inactive member of a union with common initial sequence in constexpr expression
C++ Standard in point 12.3.1 says: If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if a non-static data member of an object of this standard-layout union type is active and is one of the standard-layout structs, it is permitted to inspect the common initial...
The text that you quoted is correct, but there are additional constraints on accessing an inactive member of a union in a constexpr context. In particular, you are violating this rule: An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.executio...
64,098,157
64,112,052
What's the correct way to let the static member function call a non-static member std::function in c++?
I'm using an open62541 library who's functions are almost all static. I have to write some callback functions in the open62541's functions, the callback functions are binding to some non-static function. so the problem is how do I make the: static function of class A call a std::function, which is bind to non-static fu...
#include <iostream> using namespace std; class A { public: void Knock_knock() { std::cout<<"who's there?"<<std::endl; } }; class B { public: static void setA( A *a ) { m_A = a; } static void talkTheJoke() { if ( m_A != nullptr ) m_A->Knock_knock(); } priva...
64,098,158
64,098,291
Error: file not recognized: File format not recognized c++
My Code: #include <bits/stdc++.h> using namespace std; #define ll long long #define ar array int main() { cout << "hi my name is me" << endl; return 0; } I used the command: :!g++ % to compile my code When it compiled it returned: testing.cpp~: file not recognized: File format not recognized collect2.exe: ...
Assuming you're running this within vim, you're doing the right thing, as % gets replaced by the current file. However, the fact that it's trying to compile testing.cpp~ (the vim backup for the testing.cpp file) indicates to me that you're editing the wrong file (or putting a ~ after the % on your command line).
64,098,375
64,098,860
C++:Copy reg_iterator to a vector in order to sort() and unique()?
I have about half a million entries in my regex_iterator and there will be duplicates. In order for me to sort() and unique() on the regex_iterator (which itself does not take much time), I need to copy it to a vector which takes a lot of time(about 20 seconds). My code applies regex on file content (string fcontent) a...
A regex_iterator is lazy. The construction of rit only finds the first match and ++rit finds the subsequent matches. I doubt that push_back is a bottleneck. The call to rit->str() is allocating a new string copied from fcontent, this could be avoided if you use rit->position() and rit->length() to build a std::string_v...
64,098,405
64,698,393
Unable to use non ascii chars (accents) in Windows Credentials Provider
I'm creating a Windows Credentials Provider using the Microsoft's "Sample All UI" example. As French speaker, i need to use accents like that : "éàèê". All my strings are widechar strings (syntax: L"Numéro de téléphone"), and all the strings functions i use are the widechar version (wcsdup, wcscpy...) But when i load m...
I finally loaded my text as UTF-8 from a file, and conveted it to UTF-16 with this function : MultiByteToWideChar(CP_UTF8, 0, s.c_str(), slength, 0, 0); Note the flag : CP_UTF8 I used theses generated strings, and it worked.
64,098,413
64,098,776
Trailing return type in non-template functions
I have seen people using the following syntax to implement functions: auto get_next() -> int { /// ... } Instead of: int get_next() { /// ... } I understand both and I know that the trailing return type syntax is useful for template code using decltype. Personally I would avoid that syntax for other code since...
In addition to sergeyrar's answer, those are the points I could imagine someone might like about trailing return types for non-template functions: Specifying a return type for lambda expressions and functions is identical w.r.t. the syntax. When you read a function signature left-to-right, the function parameters com...
64,099,136
67,984,312
Visual Studio 2019 Test Explorer did not find c++ google tests
I want the c++ unit test written in google test displayed in the VS 2019 test explorer. The tests are setup correctly and can be executed. The results are shown in the VS debug console/commandline-like window. No error messages besides the test dependent messages are shown. I want start the tests form the test explorer...
I had the same problem as you. I'm having a main CMakeLists.txt, and another two CMakeLists.txt files in the subdirectories: one for the static library I'm testing and one for the test project itself. For making sure the tests appear in the Test Explorer I had to move enable_testing() from the test subdirectory into th...
64,099,280
64,102,301
C++ Program Displaying The Names Of The Array Indexes Which I Cleared Using String Function?
This is the code of my Practice Task, i'm having a little bit problem in it, my code runs perfectly but the problem is, the function: del_book() which is used to delete a specific book in my program, so if i delete a book or many books, it still displays this: Book id: Book Title: Book author: Book price: it's deletin...
Your problem is that you clear all the string but not eliminate the element in the array, in this way the disp_all(book volume[5]) function retrive ever 5 elements. A possible solution is verify before print the element if the name of the book is not equal to an empty string. Another more useful solution is use one of ...
64,099,434
64,100,097
CreateProcess with 2 redirected pipes return exitcode 1
I'm new to WIN32 API and could use some help figuring what am I missing in my code. My goal is to run a batch script (or PowerShell script), wait for completion, and then get the stdout / stderr upon completion. Following this and this article on msdn about creating a process and redirecting stdout and stderr to a hand...
Make sure to initialize the child_stdout_handle before passing the handle to CreateProcess. In addition, you need to print the value of chBuf you read in ReadFile, instead of parent_stdout_handle. Converting file handle to string is meaningless, you could try: for (;;) { bSuccess = ReadFile(parent_stdout_ha...
64,100,761
64,101,135
STL/Boost Replacement for WideCharToMultiByte-function
In the following code (snippet) WideCharToMultiByte is a Windows specific function. Is there a suitable replacement for the function using STL or Boost? //in function parameters: (..., WCHAR* szNameOfDll, ...) char szSourceTemp[MAX_PATH + 1] = {0}; WideCharToMultiByte(CP_ACP,0,szNameOfDLL,-1, szSourceTemp,MAX_PATH,NU...
std::wctomb/std::wcstombs std::mbtowc/std::mbstowcs or #include <boost/locale.hpp> #include <iostream> std::string utf8_string = to_utf<char>(latin1_string,"Latin1"); std::wstring wide_string = to_utf<wchar_t>(latin1_string,"Latin1"); std::string latin1_string= from_utf(wide_string,"Latin1"); std::string utf8_st...
64,100,775
64,104,590
What is the time complexity of the following code fragment for Stock Buy & Sell?
Recently I was trying the problem of Stock Buy and Sell in which we can buy a stock on any day and sell it on any upcoming day, and we have to find the maximum profit that we can get. The solution that first came to my mind was the code below but I'm not able to determine its time complexity. It would be very helpful i...
I think it gives you Ω(n!) if we focus only on maxProfit(price,j+1,end) : At the beginning, the number of elements is n. At each iteration we have two loop that call maxProfit(price,j+1,end) by decreasing the number of elements by 1. We get : n^2 (the 2 first loop) * (n-1)^2 (the first call) * (n-2)^2 (the second call)...
64,100,863
64,101,035
How do I optimise c++ legacy boiler plate code?
I am a Java user trying my hand at c++. In the below legacy code, I have multiple derived classes. The contents of the map in each derived class are similar differing by just a few. The function pr() is repetitive. I would like to optimize such piece of code. Do let me know ideas/suggestions? Thanks #include <iostream>...
This is not called optimization. This is called refactoring code to make use of inheritance. Apparently, in your code, repetition is in data member fm and pr() function definition. If your both classes have them in common, you can just move pr function definition and data member fm to base class so that you do not have...
64,100,868
64,111,871
not able to open a file in write mode in cpp, strerro says permission denied
I am trying to do a simple file operation by opening it and writing something. Here is the code: // image_read.cpp : Defines the entry point for the console application. #include<cerrno> #include<cstring> #include "stdafx.h" #include <iostream> #include <fstream> using namespace std; int main(int argc, char** argv) ...
Please try to set 'UAC Execution Level' = 'requireAdministrator'. https://learn.microsoft.com/en-us/cpp/build/reference/manifestuac-embeds-uac-information-in-manifest
64,101,317
64,105,086
C++20 coroutines, std return type and state persistancy
This question is actually two questions. I will ask them at once because they may be related. I just had my first look at C++20 coroutines. If have seen various examples, most of them pretty basic. Like the following: generator<int> ints(int x) { for (int i = 0; i < x; ++i) { co_yield i; } } All of the ...
Does this mean C++20 standard library does not provide coroutine return types that are ready to use e.g. for a generator? It does not. While the Technical Specification proposed all the nuts and bolts for how you might make a type coroutine-compatible, neither it nor any of its revisions proposed any standard corou...
64,101,703
64,102,132
library's object files with classes not explicitly referenced but available via a factory are being skipped at link time
I have dozens of classes that are subclasses of a generic class. Based on messages my program receives, it will instantiate objects of those subclasses via a factory. Each subclass is in a file, as per usual C++ programming style. Each such file also includes a 1-line instantiation of a Type class template that take...
You appear to be looking for this option from ld(1)'s manual page: --whole-archive For each archive mentioned on the command line after the --whole-archive option, include every object file in the archive in the link, rather than searching the archive for the required object files. The r...
64,101,963
64,102,072
How do I pass a smart pointer from a function to the caller?
I'm trying to grasp the concept of smart pointers in C++. I have the following piece of code (a unit test using GoogleTest): TEST(SHT35Sensor, ValidInstruction) { auto sht35 = SampleSHT35::create(); sht35->add(22.4, 56.5); char writeBuffer[100] = {0}; auto serial = std::make_unique<SampleSerial>("", wri...
In your code serial.get() returns pointer, but does not detaches it from unique_ptr, so when prepare ends - unique_ptr deletes SampleSerial instance and shared_ptr contains pointer to freed memory. You may use serial.release() or directly use shared_ptr. Above answer assumes that SHT35Sensor will handle lifetime of Sam...
64,102,604
64,103,745
C++20 ranges and sorting
I'm dealing with the last big 4 of C++ 20, attempting to learn the new main features. Trying some code from the web related to ranges, I've written: std::vector ints{ 6, 5, 2, 8 }; auto even = [](int i) { return 0 == i % 2; }; // ranges... auto rr = ints | std::views::filter(even) | std::views::tra...
Then I would sort, like range-v3 does with |action::sort ... No, you can't actually sort rr like this: rr |= ranges::actions::sort; // error because rr is a view. While views can provide mutable access to the underlying range, sort additionally needs the range to support random access. A lazily generated view like r...
64,102,746
64,131,779
Why is "gdb" listing multiple functions after executing the "start' command even when the C++ source file doesn't contain any function?
The context Consider the following file $ cat main.cpp int main() {return 0;} I can list all the available functions by executing $ g++ -g main.cpp && gdb -q -batch -ex 'info functions -n' a.out All defined functions: File main.cpp: 1: int main(); When executing start before executing info functions more than ...
main.cpp file does not contain any function, so why is gdb listing those functions when the start command has been executed before but not when start hasn't been executed? Before start, GDB reads symbols (and debug info) only for the main executable. After start, a dynamically linked executable loads shared libraries...
64,102,854
64,104,969
How to create a critical section only for some processes in Open/Microsoft MPI using C++?
I am new to MPI and wanted to find out how to create a critical section for only a few of the running processes. I know that I can create one like this for ALL processes: for (int i = 0; i < 1000; ++i) { MPI_Barrier(MPI_COMM_WORLD); std::cout << "RANK " << rank << " PRINTS " << i << std::endl; } However this w...
As @Gilles Gouaillardet pointed out, you can use MPI_Comm_split to create a communicator without rank 0. MPI_Barrier can be called with this new communicator to synchronise the remaining processes. Rank 0, after doing it's operations can call barrier over COMM_WORLD and wait for the remaining processes to call it. Rema...
64,103,403
64,103,448
C++ instance variable default initialization
If I want to assign a default value to an instance variable, which method is to be preferred? Is there a difference? Class Foo { int x = 0; }; Class Foo { int x; Foo() : x(0) {} };
You may choose to setup an initialization strategy for the member variable both using designated member initializers as well as member initializer list in constructors. If a given constructor does not initialize a given non-static data member, initialization of that data member will fall back on a designated member ini...
64,103,671
64,230,287
OpenCV: 32-bit libs & dlls for Visual Studio project
I am upgrading a C++ Visual Studio project that uses OpenCV 2.4 to a more recent version of OpenCV (e.g. 4.1.2 or 4.4.0). I need 32-bit and 64-bit builds of my project, so I need 32-bit and 64-bit versions of the OpenCV libs and dlls. But recent pre-built downloadable versions of OpenCV for Windows contain libs and dll...
I built OpenCV myself, it turned out not to be difficult. I followed the guides here and here. I'll put my own detailed steps below, it might help someone else. I am using Visual Studio Enterprise 2019. My choices are shown in parenthesis. Download and install CMake from https://cmake.org/download (CMake 3.18.3) Downl...
64,103,951
64,104,418
Why this code shows me an error on line 31 for cout<<x1<<x2;
Why this code shows me an error on line 31 for cout<<x1<<x2; //This code is used to define a tree. #include <bits/stdc++.h> #include <algorithm> #include <functional> #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<vector<int>> Tree; int ...
In the expression for (auto x1 : Tree) the variable x1 is an std::vector<int>. It is not easy to get the index that a given x1 has in Tree to print it. The solution is to instead iterate over the range of indices in Tree : for (std::size_t x1 = 0; x1 < Tree.size(); ++x1) { // ... } Now x1 is an integer type which ...
64,103,960
64,104,027
Template default init, if there no default constructor in a class
I'm pretty new in C++. I have wrote a function template to sum all elements in a vector like this: template<typename T> inline T sumator(const std::vector<T> &sequence) { T init = T{}; return accumulate(sequence.begin(), sequence.end(), init); } All work well until the default constructor is not declare, but d...
Possible solutions that I can think of. Let users rely on std::accumulate by providing an initial vlaue. Provide an overload of sumator with an initial value. Users can call the overload with an initial value if they have a type that does not have default constructor. Insist that the type for which the function is inv...