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
69,428,557
69,437,512
Is it possible to explicitly specify template arguments in a generic lambda passed to a function?
I want to create a compile-time loop over a small container (like 4-8 elements) with a size known at compile time. It's not hard to create just one simple loop: I can create a template functor F with operator() overloaded and call it like in the code below constexpr std::array<T, N> array{/*fill the array*/}; template...
In a generic lambda, operator() is a template, but the lambda type is not. Instead of instantiating a template at an index F<I>{}(), one needs to instantiate operator() at an index. Since the lambda has captures, one will need to pass it instead of just the type as a template argument. Replace: template <template<std::...
69,428,611
69,429,164
Using std::make_unique with the GetProfileBinary function call
I have seen this answer (Advantages of using std::make_unique over new operator) where it states: Don't use make_unique if you need a custom deleter or are adopting a raw pointer from elsewhere. This is is my code: void CAutomaticBackupSettingsPage::GetLastBackupDate(COleDateTime& rBackupDate) { DATE* pDatTime = ...
pDateTime is supposed to be nullptr, and GetProfileBinary handles the allocation. Code Analysis mistakenly thinks you forgot the allocation. It does need to check for success before calling delete[]. We can't use delete[]pDatTime because pDatTime is not an array. But GetProfileBinary allocates using new BYTE[size], so ...
69,428,657
69,428,749
Convert const wchar_t* to LPWSTR
I'm trying to convert a const wchar_t* to LPWSTR but I'm getting the error E0513. I'm using Visual Studio with C++17. Here is my code: int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LPWSTR* argv; int argCount; argv = CommandLineToArgvW(GetCommandLineW(),...
To answer your question: You can use const_cast: argv[1] = const_cast<LPWSTR>(L"2048"); Or a local wchar_t[] array: wchar_t arg[] = L"2048"; argv[1] = arg; However, CommandLineToArgvW() will never return any array elements set to nullptr to begin with. All array elements are null-terminated string pointers, so empty ...
69,428,696
69,441,331
How to replace the RCData of an executable?
I'm trying to modify the RCData of a compiled AutoHotkey script: void ReplaceStringTable() { HANDLE hRes = BeginUpdateResource( _T( "C:\\Users\\CAIO\\Documents\\Github\\main\\scripts\\ahkDebug\\Novo(a) AutoHotkey Script.exe" ), FALSE ); if ( hRes != NULL ) { std::wstring data[] = { L"MsgBox Test" };...
You need to use std::string instead of std::wstring, as AHK is expecting 8bit characters, not 16bit characters. Also, you need to get rid of your vector, as AHK does not expect each line to be prefixed by its length. Try this instead: void ReplaceStringTable() { HANDLE hRes = BeginUpdateResource( TEXT( "C:\\Users\...
69,428,979
69,429,072
my (find & replace) method is not working properly
I am actually trying to code a program to perform (find & replace) on a given string but it is not working properly (it partially works specially in the first occurrence). any idea? here is below the code: string Find_Replace(string str,string substr,string replacement){ int x = substr.length(); int i = 0; ...
This call of the member function replace str.replace(i,i+x,replacement); is incorrect. The second argument must specify the number of characters to be replaced. The function should be defined the following way std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement ) { ...
69,429,078
69,435,207
Cmake - select different c++ standard for different sources
As the title suggest, I'd like to use cmake to build a project, and depending on the source file, enforcing a different c++ standard. The reason is : I am working on a library and would like to make it c++03 compliant for compatibility, but would like to use Google test suite which requires c++11. So the unit tests wou...
So just do that - ompile your library with one standard, and your tests with the other. Nowadays, https://stackoverflow.com/a/61281312/9072753 method should be preferred. add_library(mylib lib1.cpp) set_target_properties(mylib PROPERTIES CXX_STANDARD 03 CXX_EXTENSIONS off ) add_executable(mytest main.c...
69,429,111
69,429,190
Why rvalue reference member would be const?
I am trying to write a move constructor for a structure but I can't understand why I fail to call the move constructor of structure member: #include <memory> struct C { std::unique_ptr<int[]> mVector; size_t mSize; C() = default; C(C &&temp) : mVector(temp.mVector) , mSize(tem...
Why rvalue reference member would be const? Don't assume that it's const. You should assume that unique_ptr(const unique_ptr&) is merely the best match, from the available constructors. Because in constructor temp is a rvalue reference Surprise! It is not an r-value reference. The variable temp is bound to an r-v...
69,429,827
69,430,110
Providing an allocator for Boost's `cpp_dec_float_100`
I have a dataset stored in .root file format (from the CERN ROOT framework) as type cpp_dec_float_100 (from the boost::multiprecision library). This data is read into an std::vector<cpp_dec_float_100>. By default, cpp_dec_float_100 is unallocated. If I were to try to read this data into a vector as-is, an std::bad_allo...
Your problem has nothing to do with allocator, just because cpp_dec_float<...> has no operator<(), only number<cpp_dec_float<...>> supports. You should redefine your Mult_t as: using namespace boost::multiprecision; using Mult_t = number< cpp_dec_float<100, int, std::allocator<number<cpp_dec_float<100>>>>>;
69,430,143
69,430,188
Returning objects constructed in lambda in transform
The following function does something different than I want, which is to return the matches. If I call it on vector<string>{"a b", "cd ef"}, the output is cd cd ef instead of a b cd ef Why? #include <regex> using namespace std; void f(const vector<string>& v) { vector<smatch> P{}; transform(begin(v), end(), bac...
For std::match_results: Because std::match_results holds std::sub_matches, each of which is a pair of iterators into the original character sequence that was matched, it's undefined behavior to examine std::match_results if the original character sequence was destroyed or iterators to it were invalidated for other rea...
69,430,164
69,432,184
How to calculate the sum of an array in parallel using C++ and OpenMP?
my task is to parallelize the creation, doubling, and summation of the array seen in my code below using C++ and OpenMP. However, I cannot get the summation to work in parallel properly. This is my first time using OpenMP, and I am also quite new to C++ as well. I have tried what can be seen in my code below as well as...
Unfortunately your code is not OK, because you run the for loop number of thread times instead of distributing the work. You should use: #pragma omp parallel for to distribute the work among threads. Another alternative is to use reduction: int main() { const int size = 256; const double step = (2.0 * M_PI) / s...
69,430,274
69,430,326
How to retrieve full file path from DIR pointer?
From a DIR* variable from <dirent.h>, how do I get the full file path (e.g. "/home/ubuntu/Desktop/planning")? Note: This needs to work on Linux.
There's nothing in the DIR object that gives you the name of the directory that the DIR object is reading. There is no function in the C library that does this. You will need to implement this logic yourself. Wherever you open a DIR: save the name of the directory you opened, and consult it as needed. Or, in modern C++...
69,430,434
69,508,314
How would I implement this maximumGrade function?
#include <fstream> // For file handling #include <iomanip> // For formatted output #include <iostream> // For cin, cout, and system #include <string> // For string data type #include "CourseGrade.h" using namespace std; CourseGrade* maximumGrade(CourseGrade* course0, CourseGrade* course1) { } int main() { cout <...
I have three objects due to the prompt, but it only asks for two pointers? The only way to make sense of two pointers passed to maximumGrade is to assume that these are the beginning and end of an array which contains the three objects. CourseGrade courses[3] = { Course0, Course1, Course2 }; cout << "The cour...
69,430,521
69,433,278
Building simple function to inherit 3 classes in C++
I have created 3 classes - GrandMother, Mother and Daughter. I wrote a code such that the Daughter class inherits from the Mother class and the Mother class inherits from the GrandMother calss. GrandMother.h :- #ifndef GRANDMOTHER_H #define GRANDMOTHER_H class GrandMother { public: GrandMother(); ...
Your header are not self-contained, so you have to include them in right order: #include "GrandMother.h" #include "Mother.h" #include "Daughter.h" but it is fragile. Right way is to make the header self contained: #ifndef GRANDMOTHER_H #define GRANDMOTHER_H class GrandMother { public: GrandMother(); ~GrandMot...
69,430,685
69,430,788
Getting NaN value when raising double by a fractional exponent of 1/3
I'm new to C++ so if there is a quick solution to this question please let me know in the comments. I'm working on a third-degree polynomial equation solver application, and for that I need to divide a certain double value by a fractional exponent, which in this case is 1/3. Here is the code so far: #include <iostream>...
pow does not support taking roots of negative number in this fashion. cppreference on std::pow: Error handling Errors are reported as specified in math_errhandling. If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur. C++ provides a function for directly...
69,431,523
69,431,576
Calling member function through const qualified object gives error as function is not marked as const?
Code #include <iostream> class A { public: mutable int x; mutable int y; A(int k1 = 0, int k2 = 0) :x(k1), y(k2) {} void display() { std::cout << x << "," << y << "\n"; } }; int main() { const A a1; a1.x = 3; a1.y = 8; a1.display(); return 0; } Output Error: 'this...
Why line a1.display() is giving an error ? The mutable variable let you modify the member variables inside a const qualified function. It does not allow you to be able to call the non-const qualified member function to be called via a const qualified instance. Therefore, you need a const member function there.
69,431,615
69,444,675
input inside of while loop without waiting for user
I am going to write a program in which there is a while loop in which the user can input the program at any time, but the while loop does not wait to receive the user input and continues to work. Whenever a user enters a new input, the program will run according to that input. The program is in C ++ and the name of the...
thank you pepijn kramer.With your help, I completed my program. while (1) { system("CLS"); show(grid,grid_rows,grid_cols); if (_kbhit()) { ch = _getch(); } Move(grid,snake,grid_rows,grid_cols,len_snake,ch); check_(grid,snake,grid_rows,grid_cols,len_snake); Sleep(500);...
69,431,700
69,431,899
How does C++ "send" temporary values to functions by value?
I have a simple snippet: class Object { private: int value; public: Object(int value) : value(value) { cout << "Object::ctor\n"; } Object(const Object& obj) { cout << "Object::copy-ctor\n"; } Object(Object&& obj) { cout << "Object::move-ctor\n"; } }; Object take_and_return_obj(Object o) { return o; } ...
Yes, in take_and_return_obj(Object(5));, the copy/move operation for constructing parameter o is elided; which is guaranteed since C++17. Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have obse...
69,431,723
69,431,894
My while loops and else if loops don't work
I am trying to have the letter show with the appropriate grade. Then I would like the program to ask me over and over my midterm and my final score. Then give the appropriate grade for that score as of now it only give me the scores of the first run. #include <iostream> #include <iomanip> using namespace std; int main...
Fixed few logical errors in if statements and few other errors (explanation is at the end). I hope this modified code does the required task: #include <iostream> #include <iomanip> using namespace std; int main() { int midterm=0; int final=0; cout << "please enter midterm grade: "; cin >> midterm; ...
69,432,326
69,432,394
Protecting against Time-of-check to time-of-use?
I was reading: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use They showed this code to be buggy and I totally understand why it's so: if (access("file", W_OK) != 0) { exit(1); } // Attacker: symlink("/etc/passwd", "file"); fd = open("file", O_WRONLY); // Actually writing over /etc/passwd write(fd, buffe...
You can use the O_NOFOLLOW flag. It will cause the open to fail if basename of the path is a symbolic link. That would solve the described attack. To cover links along the directory path, you can check whether frealpath(fd, ...) matches what you would expect. Another way to prevent a process from overwriting /etc/passw...
69,432,375
69,432,395
Default constructed std::priority_queue with a lambda
I mistakenly omitted the compare argument when defining a std::priority_queue: #include <queue> int main() { constexpr auto cmp{[](int a, int b) { return a > b; }}; std::priority_queue<int, std::vector<int>, decltype(cmp)> pq; } , and it compiled successfully and worked properly when I used it to implement Di...
The change happened on lambdas. If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does not actually capture anything). (Since C++20) Before C++20, lambda closure types are not...
69,432,461
69,432,530
Undeclared identifier error on using square() function given in a book
I came across the square() function in a book on C++. On implementing the function as given in the book Xcode gives an 'undeclared identifier' error. I have tried including 'cmath' and 'math.h' header files but it doesn't seem to fix the issue. I cannot find a header file for it and I am not even sure if that's the act...
There is no square() function in the c++ standard library, you need to implement it. Anyway, there is the function pow(number, power), it calculates the power of a number, you can use it including the cmath header.
69,432,829
69,433,323
nanopb oneof - encoding problems
I am trying to encode a message using oneof - and the size does not seem ok. Looks like this is ignoring the oneof part - and not encoding it into the stream. The encoding functions all return "TRUE" - which means that they encoded as I requested, which means I encoded wrong... I am missing something very silly. static...
I think your problem is here: toAppMessage2.which_payload = WifiCredResult2_ip_tag; This would indicate that your payload oneof contains an item of type WifiCredResult2.ip, but there is no such item in that oneof so nothing gets encoded. It appears you want instead: toAppMessage2.which_payload = ToAppMessage2_wifi_tag...
69,432,941
69,433,134
while repeat not stop after i input one time
how do i get my program to repeat non stop? i want it to keep asking me to input the same information for multiple students. and not stop after i input once. can someone help please? i really appreciate all the help thank you guys. enter code here #include <iostream> #include <iomanip> using namespace std; int main()...
Put your whole code in a loop that never stops. Example: #include <iostream> #include <iomanip> using namespace std; int main() { while(true) { int midterm=0; int final=0; cout << "please enter midterm grade: "; cin >> midterm; while (midterm < 0 || midterm > 200) ...
69,433,613
69,433,693
Passing template template parameters
Let's say we have a class called TypeCollection that holds a packed template of types: template<typename ...Types> class TypeCollection {}; And if we have a class that templates a TypeCollection you would need to do something a little like this: template<template<typename ...> class Collection, typename ...Types> clas...
Flip your CollectionHandler declaration around to dissect the TypeCollection through template specialization: template <class TypeCollection> class CollectionHandler; template <class... Types> class CollectionHandler<TypeCollection<Types...>> { };
69,433,726
69,433,842
Limitations of std::result_of for lambdas in C++14
I have a working piece of C++17 code that I would like to port to C++14 (project's constraints). The code allocates a functor on the heap, based on the lambda returned by a provider. decltype(auto) fun_provider(std::string msg) ...
Is this approach not viable? auto fun = std::make_unique< decltype(fun_provider(std::declval<std::string>())) >(fun_provider("Provided functor")); The use of std::declval isn't even necessary; std::string{} instead of std::declval<std::string>() is just fine.
69,434,339
69,435,540
Metadata Like Config file parser
i am trying to parse this config file ... MODEL: "modelname1" { FILEPATH = "FILEPATH1"; TEXTUREPATH = "TEXTUREPATH1"; NORMALPATH = "NORMALPATH1"; } MODEL:"modelname2"{FILEPATH = "FILEPATH2";TEXTUREPATH = "TEXTUREPATH2";NORMALPATH = "NORMALPATH2";} here is my attempt : #include <iostream> #include <map> #include <fstre...
Since you want to learn fundamentals, I will only answer with outlines of solutions. Note that neither will work if you want to add block nesting to your language. For that you need a proper grammar like boost::spirit or similar. Use getline to extract one block at a time: std::string model_name, block_contents; getlin...
69,434,424
69,435,033
Qt/C++ pass static method's argument to class method
Is there a way to pass a static method's argument to a class method? I've tried with QTimer this way: QTimer g_timer; QString g_arg; void staticMethod(QString arg) { g_arg = arg; g_timer.start(1); // It will expire after 1 millisecond and call timeout() } MyClass::MyClass() { connect(&g_timer, &QTimer::timeout,...
In this specific instance you can use QMetaObject::invokeMethod to send the message over a cross-thread QueuedConnection: QMetaObject::invokeMethod(&g_timer, "start", Qt::QueuedConnection, Q_ARG(int, 1)); This will deliver an event to the owning thread from where the start method will be called, instead of the current...
69,434,848
69,434,946
Is it necessary to cast individual indices of a pointer after you cast the whole pointer in c? Why?
In the code below the address of ip is casted to uint8_t *. But below again each index of the casted pointer is casted to uint8_t. Why the programmer has done this? Does it make a difference if we remove all those casts that come after the initial cast? This code converts an IPv4 IP Address to an IP Number. Thank you ...
Why the programmer has done this? Ignorance, fear, or other incompetence. The type of ptr is uint8_t *, so the type of ptr[i] is uint8_t. Converting a uint8_t to a uint8_t has no effect. Also, putting it in parentheses has no effect. Does it make a difference if we remove all those casts that come after the initial ...
69,435,425
69,435,484
namespace myspace { int x } Now why `myspace::x=3;` gives error?
Code #include <iostream> namespace myspace { int x; } myspace::x=3; // This line is giving error. int main() { myspace::x=5; return 0; } Output Error: C++ requires a type specifier for all declarations So why line myspace::x=3; giving error that C++ requires a type specifier for all declarations ?
The statement myspace::x=3; isn't an initialization, it's a plain assignment. It's no different from the myspace::x=5; you have inside the main function. Any statement that isn't a declaration or a definition can't be outside functions. If you want to initialize the variable, do it at the definition: namespace myspac...
69,435,528
69,435,594
C++ boost 1.72 reconnect on tcp::socket throwing an exception with WSAEADDRINUSE on linux, but works on Windows
Hi my code works properly on windows but on linux the reconnect feature doesn't work,it throws an exception with WSAEADDRINUSE value. pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001)); First time it works on both Windows and Linux, but when i close the socket ...
Try using the reuse option: boost::asio::socket_base::reuse_address option(true); socket.set_option(option); Update: This usually happens we you try to bind a server socket to an address that is already in use or it has been used recently (and the socket is still waiting to be cleaned up by the OS). With client socket...
69,435,538
69,435,666
Extract static member type from class of local variable
Is it possible to extract a static member type from the class of a local variable? aka something in the lines of class A { public: typedef int constituent_type; constituent_type a; A(constituent_type _a) :a(_a) {}; } int main() { auto a = A(42); // ... lots ... of other code; where I have long since forgo...
You can do that in C++ 11 or later using decltype: decltype(a)::x Live demo: https://godbolt.org/z/cTq9zhKxe
69,436,122
69,436,399
Giving an arbitrary container, deduce a container type of a related type
Say I have a templated class Wrapper, is there a way to create a type alias template that automatically deduce a container of Wrapper <T> from a container of T, so that: alias(Wrapper, vector<int>) would become vector<Wrapper<int>> alias(Wrapper, map<int, string>) would become map<Wrapper<int>, Wrapper<string>> alias(...
Not sure if this is exactly what you need, but specialization of class template can handle this nicely: #include <type_traits> #include <vector> #include <array> #include <map> #include <string> template<template<typename> typename Wrapper, typename Container> struct repack; template<template<typename> typename Wrapp...
69,436,608
69,436,936
How to add several string together such as "123"+"456"?
How to achieve such operation, the Visual Studio always tells me that it was wrong. The wrong code is C2110 and E2140. Can anyone help? std::string a = "2323" + "22323" + "232332";
The expression "2323" is not a std::string, it is a const char[5]. Since C++14, you can have a literal of type std::string: using namespace std::string_literals; std::string a = "2323"s + "22323"s + "232332"s;
69,437,173
69,441,170
C++ Win32 Menubar being drawn over owner-drawn menu items
I have 2 owner-drawn menu items, when I launch the program I only see one of the owner-drawn menu items; the first one. It is being drawn except the menubar is drawn over every other menu item which is not drawn in the first position, If I mouse over the second owner-drawn menu item or update it in any other way it dra...
Why is DrawMenuItem() calling ReleaseDC(MainWindow, hDC);? That doesn't belong there, get rid of it. You didn't obtain the HDC from Get(Window)DC() so you don't own it and shouldn't be trying to release it. Also, you are not un-selecting the objects you selected into the HDC. You need to restore the original objects yo...
69,437,596
69,437,775
Binary search tree algorithm crashing when passing a parameter that isn't in the tree to the search function
i tried building a binary search tree, everything worked fine when i gave it parameters that were in in the tree, but i wanted to see if it would print 0 when it couldn't find the int in the tree instead when i call search it's crashing. i tried adding a condition after the first if statement but that ruined the recurs...
When you run cout << search(R, 65)->data << endl; search(R, 65) returns NULL. You can't dereference NULL by doing ->data on it. You probably want: Node* result = search(R, 65); if (result) { cout << result->data << endl; } else { cout << "Not found" << endl; }
69,437,727
69,438,128
Using boost spirit expression
I have a problem with boost spirit expression.The original code is more complicated and I made a small snapshot of it. This code works as expected in debug mode and doesn't in release, parse returns false, but should return true ( I'm testing it on Visual Studio 2019) int main() { namespace qi = boost::spirit::qi; ...
You ran headlong into the the dangling temporaries trap with Spirit's Proto expressions. The short rule is: Don't use auto with Spirit expressions Your program exhibits Undefined Behaviour: see it Live On Compiler Explorer The workarounds involve BOOST_SPIRIT_AUTO or qi::copy (which used to be available only as bo...
69,437,925
69,438,074
Problem with calling C++ function that receive command line arguments from Rust
I am trying to call a C++ function from rust. The function suppose to receive the command lines arguments then print it. I used cmake to compile the C++ code to a static archive. I write a build.rs script to referee to the static library location and to make the static linking to it. // library.cpp #include "library.h...
The problem is in this code: let args = std::env::args() .map(|arg| CString::new(arg).unwrap()) .collect::<Vec<CString>>(); // ... let c_args_ptr = args.as_ptr() as *const c_char; That creates a vector of CString objects, which you then proceed to cast into an array of pointers. But a CString consists of two w...
69,438,184
69,438,625
Including a header in multiple headers in my C++ code
I am trying to include a header file from the book Numerical Recipes in my code. The header files I have to include are the nr3.hpp and the interp_1d.hpp. The interp_1d needs the definitions of nr3 in order to work. I will write some of the code that appears on interp_1d.hpp so that you get an idea of what I am dealing...
When working with a single file (or for brevity for books), some code can be simplified, but making multi-file case wrong. In your case, header guards are missing, and inline are missing (or a cpp file to put definition). So you cannot use them as-is. You have either: split code for header/cpp file: // interp_1d.hpp #...
69,438,255
69,448,568
Should the suspended coroutine handle be always destroyed before program ends?
Look at this simplified example: std::coroutine_handle<> logger; const char* next_msg = nullptr; void log(const char* msg) { next_msg = msg; if (logger) logger.resume(); } struct wait_msg { bool await_ready() { return next_msg != nullptr; } void await_suspend(std::coroutine_handle<> h) { ...
Should the suspended coroutine handle be always destroyed before program ends? No, there are cases when destroy() is not needed nor even possible. Yes, in the code from question, destroy() on coroutine handle is needed. This quote from the standard explains the thing: The coroutine state is destroyed when control fl...
69,438,388
70,050,483
Converting RGB8 to to NV12 with libav/ffmpeg
I am trying to convert an input RGB8 image into NV12 using libav, but sws_scale raises a reading access violation. I must have the planes or the stride wrong, but I can't see why. At this point I believe I'd benefit from a fresh pair of eyes. What am I missing? void convertRGB2NV12(unsigned char *rgb_in, width, height...
There are two main issues: Replace AV_PIX_FMT_RGB8 with AV_PIX_FMT_RGB24. rgb_in should be "wrapped" with array of pointers: const uint8_t* in_planes[1] = {rgb_in}; sws_scale(sws_context, in_planes, ...) Testing: Use FFmpeg command line tool for creating binary input in RGB24 pixel format: ffmpeg -y -f lavfi -...
69,438,583
69,438,808
Missing bytes when reading from file
I am writing some code to combine two .txt files containing test data captured for the same equipment, but taken on separate occasions. The data is stored in a .csv format. EDIT: (As in while they are saved as .txt (UTF8 with BOM encoding), they are formatted to appear like a csv file) Without worrying about the combin...
fstream opens the file in "text" mode by default. On many platforms, this makes no difference, but specifically on Windows systems, text mode will automatically perform character conversion. \r\n on the filesystem will be read as simply \n. See Difference between opening a file in binary vs text for more discussion. ...
69,439,030
69,439,176
Only allow further inheritance from child class
Context: I'm doing some internal cleanup to move away from large & unwieldy data structures to more well-defined data structures. Current I have a class that does something like this: class Base { public: virtual int DoStuff(BigType input); }; Calling code: std::vector<Base*> bases; BigType input; for (const auto& ...
If you want to disallow inheriting from Base directly you can make Base::Base() private and make FocusedBase a friend: struct Base { private: Base() = default; friend class FocusedBase; }; struct FocusedBase : Base {}; struct Foo : Base {}; struct Bar : FocusedBase {}; int main() { //Foo f; /...
69,439,350
69,439,623
What would cause a C++ object's type information to change after it is returned from a function?
Introduction I have C++17 code of the following form: Base& makeDerived(int val) { std::shared_ptr<Derived> derived = secondLayer(val); std::cout << typeid(derived).name() << std::endl; return *derived; } int main(void) { Base& derived = makeDerived(7); std::cout << typeid(derived).name() << std::endl; ...
It is not clear how you can get output of Derived Derived or Derived Base, because derived is a std::shared_ptr<Derived>. Anyhow, here is a minimal example with the same issue as your code (most likely): #include <iostream> #include <memory> struct Base { virtual ~Base() = default; }; struct Derived : Base {}; std::s...
69,439,920
69,440,118
C++ conditional template member function
I am trying to understand how to use std::enable_if to choose between 2 functions implementation. In this case, if the type TupleOfCallback doesn't contains all the type, it will not compile because std::get<...> will throw an error. For exemple: Executor<Entity1*, Entity2*> task([](Entity1 *e){}, [](Entity2 *2){}); Th...
If you can guarantee that all types appear only once, then the following should work: template<typename... Ts> class Executor { using TupleOfCallback = std::tuple<std::function<void(Ts)>...>; public: Executor(const std::function<void(Ts)>&... func); template<class E> std::enable_if_t<(std::is_same_v<Ts, E*> |...
69,440,017
69,447,925
Using the same object instance in several classes
I want to be able to instantiate and use the same object instance in several .h files so that: a) that object can be instantiated once and then re-used in several places b) the value for one of the variables of that object instance is to be updated later in the code and thus available to all of the functions which are ...
Solved in the following way: class AddressHelper { private: uint32_t pid; DWORD_PTR baseAddressPtr; public: AddressHelper() { } static AddressHelper& getInstance() { static AddressHelper instance; // Guaranteed to be destroyed. // Instantiated on...
69,440,238
69,440,621
Cmake how to set a global definition?
I have a simple structure in my project that includes several subfolders/subprojects. The structure is as following: main |- CmakeLists.txt |- include |- src |- library |- CmakeLists.txt |- include |- src The main CmakeLists.txt project(main) file(GLOB SRC . src/*.cpp) file(GLOB INC . include/*.h) add_execut...
The "modern cmake" approach is that all flags are encapsulated in the subprojects, and when you link to the subproject with target_link_library(MYEXE libsubproject), all necessary paths, flags, and definitions are propagated to the main project. To do this, use target_compile_definitions(library PUBLIC ADDS) in the sub...
69,440,892
69,441,084
Finding a specific template from just one template parameter. Is it possible?
Suppose I have something like this: template <typename T, typename ...args> static std::map<T, std::tuple<args...>> MyMaps; Every type is known on compile time. So for every configuration of types added to the map, a new map is created. Is there a way to search in all instances of map that matches the T parameter with...
No. The underlying problem one would have to solve is determining whether a template variable has been instantiated or not. Otherwise have fun searching through infinitely many possible instantiations. C++ provides no tools for answering such questions because implementation would be near impossible. Mainly due to sepa...
69,441,285
69,441,429
Copy assignment operator with non-copyable members
Say I have a class A with only a constructor: struct A { A() = default; A(const A&) = delete; A& operator=(const A&) = delete; }; I also have a class B which contains an instance of A and defines the copy constructor as follows: struct B { B() = default; B(const B& other) : _a{} {} A _a; }; Th...
If you want operator= to create a fresh new A similar to the copy constructor and if dynamic allocation is feasible you can use a std::unique_ptr<A> as member: struct A { A() = default; A(const A&) = delete; A& operator=(const A&) = delete; }; struct B { B() : _a{std::make_unique<A>()} {} B(const B...
69,441,476
69,441,770
Tcl convertion to double not working with large examples
I have a list of dicts and I want to retrieve some values of these dicts. Here is the code: void Get_Dict_Value(Tcl_Interp *interp, Tcl_Obj *dict, const char* key, std::function<void(Tcl_Obj*)> data_handler) { Tcl_Obj* val_ptr; Tcl_Obj* key_ptr = Tcl_NewStringObj(key, -1); Tcl_IncrRefCount(key_ptr); Tcl...
You should (well, must really) test the result of Tcl_DictObjGet to see if it is TCL_OK or TCL_ERROR. It's a C API, so it returns result codes instead of throwing C++ exceptions. void Get_Dict_Value(Tcl_Interp *interp, Tcl_Obj *dict, const char* key, std::function<void(Tcl_Obj*)> data_handler) { Tcl_Obj* val_ptr = ...
69,441,566
69,442,095
How to declare a class member that may be one of two classes
I am working with a project that is largely not of my creation, but am tasked with adding in some functionality to it. Currently, there is a device class that has a member variable that is responsible for storing information about a storage location, setup like this: device.hpp class device { public: // Stu...
You are on the right track, but you have to learn how to use polymorphism. In your example, you need the following fixes: In the base class, make all functions virtual, and add a virtual destructor: class StorageInfo { public: virtual ~StorageInfo(){} virtual void initializeStorage(); //... ...
69,441,597
69,443,142
c++ issue with variables not being declared in scope error and mismatched types warning
I have run into an issue with my program. The basis of the program, in the grand scheme of things, is to read input about a student from files. This includes their name, ID, homework scores and test scores. It is then supposed to calculate all the scores and produce a letter grade. I'm currently only working on printin...
Change ifstream, ostream, and ofstream to std::ifstream, std::ostream, and std::ofstream. Also, get rid of this line: infile.open(out);
69,442,488
69,442,545
How can I divide two Eigen::Vector3f by the corresponding elements
I need to divide two vectors by the corresponding elements. How can I accomplish this? I couldn't find any good sources. Something like Eigen::Vector3f v1 = { 10.0f, 10.0f, 10.0f }; Eigen::Vector3f v2 = { 5.0f, 2.0f, 2.0f }; Eigen::Vector3f v3 = v1 / v2; Expected result: { 2.0f, 5.0f, 5.0f } It says "no operator / ma...
While the builtin matrix (expression) types support common linear algebra operations through overloaded operators (e.g. matrix-vector multiplication), Eigen provides distinct types for component-wise operations; the are called "arrays" and subsume Eigen::Array<...> instantiations as well as array expressions. You can a...
69,442,554
69,454,708
How to find all the available filter for CPPLINT.cfg file?
I'm using EditConfig to enforce 2 spaces indentation. root = true [*] indent_style = space indent_size = 2 continuation_indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true I start using cpplint for static analysis, everything worked well until I found that some...
The solution was so easy, I just need to look carefully on the error message, it shows the name at the end of the message between "[]" LinuxFilesManager.hpp:7: private: should be indented +1 space inside class LinuxFilesManager [whitespace/indent] [3] The solution was creating the CPPLINT.cfg file like this: set nop...
69,442,663
69,443,472
Is it possible to convert a UTexture2D to an OpenCV::Mat
I am an developer that works with plugin development for unreal (C++), and I have been tasked with integrating openCV into unreal engine for a project. I was able to handle getting the std:: issues solved, but I am stuck and frustrated with trying to get a UTexture2D to be converted into an opencv::Mat. I have a C++ fu...
Use correct constructor of cv::Mat that takes a data pointer. That Mat object will not allocate or free its own memory. It will use the memory it was given. Such a Mat will not be resizable and it will only be valid as long as the given memory is okay to access. https://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html...
69,442,698
69,442,769
why does the "If GetAsyncKeyState" sends Button infinitely?
I wanted to make a macro that sends space infinitely only if I press it, the problem is that it's sending it even after I left my finger of the button. DWORD WINAPI BhopThread(LPVOID lp) { while (true) { if (bhop) { if (GetAsyncKeyState(VK_SPACE)) { Sl...
You have to check the most signifcant bit of the return value of the GetAsyncKeyState() function to determine if they key is currently pressed or not. GetAsyncKeyState() function If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the ke...
69,442,953
69,443,000
How to include <numbers> header file and use std::numbers
running on version 11.1.0 of gcc and g++. Every time I run this code I run into issues it says std::numbers was not declared. I tried running g++ randomCodeWhileReading.cpp -o main-std=c++20 within my terminal (im running ubuntu linux) and still no change. Here is the code in question: #include <iostream> #include <num...
You need to compile with the extra flag -std=c++20. Moreover, there is an error in your code: pi and pi2 are declared const, hence you cannot modify them after they are initialized. Use this instead: #include <iostream> #include <numbers> int main() { const long double pi = std::numbers::pi_v<long double>; con...
69,443,156
69,443,305
Subtracting 1 vs decrementing an iterator
In the accepted answer to "Iterator to last element of std::vector using end()--" @barry states: Note that if vector::iterator is just T* (which would be valid), the first form above is ill-formed. The second two work regardless, so are preferable. referring to his code: std::vector<int>::iterator it = --container.en...
For any standard library container, the member function end() returns an r-value. It's a "temporary" until you assign it to a variable. The decrement operator -- is not required to work on r-value iterators. You would be modifying a temporary, which C++ historically has taken measures to avoid. Therefore, --container...
69,443,252
70,283,588
Problem with QT QGraphicsView on Jetson Xavier
I am having a weird issue, and I'm not really sure where to start on figuring out the issue or even what to search for this. Hopefully someone will have seen this before and can help! I have created a QT application in QTCreator/C++. I developed the app on a Ubuntu 20.04 machine which has QT version 5.12.8 (the default...
This isn't a strict answer, but I eventually found a workaround that mitigates this issue. After a bit more investigation I found the problem to be specifically related to the Event Filter, and 'installEventFilter'. I'm not sure what the problem is still. The workaround I found was rather than using an event filter, I ...
69,443,360
69,443,412
how is the address changed when passing a pointer to a pointer in function
I am a beginner to c++ and I've written this example code to help myself understand pointer to pointer as well as call by reference. I understood pretty much everything except for myFunc: cout << &ptr << endl; // 0x7ffeefbff4d8 I was hoping to get some clarification on this line. Since we are treating the address passe...
When you declare a function such as void myFunc(int** ptr) …you actually declare an argument which, even being a pointer to pointer to an int, remains passed by value. Consequently, it's treated like a local variable that would be declared at top of your function. This variable is therefore declared in the stack, and ...
69,443,433
69,443,748
identifier "numIDs" is undefined while inside of scope
I am coding a small app thats supposed to take a string of numbers from a text file then save them into an array, and finally print the array through iteration, the file should be in this format: 10 0 1 2 3 4 5 6 7 8 9 The first number being the amount of numbers or "IDs" that should be in the array, the rest being th...
Variables placed inside a loop will not be visible outside the loop. So to fix your problem, declare numIDs outside the loop instead of in it. Also, from the looks of it, you would want to put the second loop in the first. Original: int numtest = s[0]; for (int i = 0; i < numtest; i++) { string currLine; getli...
69,443,809
69,451,827
"Downcasting" a std::atomic_ref<T>
Is it possible to downcast between std::atomic_ref<T> and std::atomic_ref<U> where U is a subclass of T? I tried the following code which didn't work. template<typename T> std::atomic_ref<T> World::getComponentByID(componentInstanceId uuid) const { static componentTypeId key = stringHash(typeid(T).name()); retu...
Usage of atomic_ref this way does not make sense. (Even in lock_free cases that make sense in assembly language, the ISO C++ standard doesn't expose that functionality.) As @Igor Tandetnik pointed out, "No subobject of an object referenced by an atomic_ref object may be concurrently referenced by any other atomic_ref ...
69,444,901
69,444,959
Value not updating in class C++
I'm writing an assignment program which implements OOP principle which is meant to simulate an election. I have a class Party: class Party{ public: Party(){}; ~Party(){}; Party(std::string name, int budget){partyName = name; electionBudget = budget;} std::string getPartyName(){return partyName;} std...
for(Party p : partiesVector) is receiving the Party object by value, thus a copy made. Any updates to p will update the copy, not the original. Make sure such loops receive the Party by reference instead: for(Party &p : partiesVector) You should do this anyway, even for read-only loops. More importantly, your display...
69,445,747
69,449,681
What is "int (*arr)[cols]" where "cols" is a variable, in C++?
I am reading this to consider about how to dynamically allocate memory for a two-dimensional array. I notice that a variable value cols can be used as size to define int (*arr)[cols], as C language has variable-length arrays(VLA) feature, then I try modifying the code into C++ like: #include <cstddef> #include <cstdio>...
-std=c++11 doesn't mean "compile strictly according to C++11" but "enable C++11 features." Just as -std=gnu++11 (the default setting) means enable gnu++11 features, which is a superset of C++11. To get strictly compliant behavior, you must use -std=c++11 -pedantic-errors. And then you get this: error: ISO C++ forbids ...
69,446,555
69,446,660
Is reading a variable outside its lifetime during constant evaluation diagnosable?
Shall one expect a reliable failure of in constant evaluation if it reads a variable outside of its lifetime? For example: constexpr bool g() { int * p = nullptr; { int c = 0; p = &c; } return *p == 0; }; int main() { static_assert( g() ); } Here Clang stops with the error read of ...
GCC dropped the ball. [expr.const] 5 An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following: ... an operation that would have undefined behavior as specified in [intro] through [cpp]; ... Indirect...
69,447,075
69,447,138
Assignment operator is not calling parameterized constructor while copy constructor present in code
CASE 1: When I create a object of class with an assignment operator , it calls parameterized constructor if there in no copy constructor in code. Below code is without copy constructor: class Test{ public: int a; Test(int a){ this->a = a; } }; int main(){ Test x = 6; cout<<x.a; retur...
I think this: Test(Test &b){ this->a = b.a; } Should actually be this: Test(Test const &b){ this->a = b.a; } Copy constructor should get a const reference, and they should copy the parameter content into the current object content, not the other way around..
69,447,591
69,447,827
Write calculation output in a txt file
This a very beginner question. I'm trying to create a simple c++ switch case based console calculator that creates a txt file and writes the output to it. I have very little experience with OOPS or C++ so I have no clue on how to make this work. This snippet creates a text file and writes to it: #include <iostream> #in...
The scope of a variable declared inside a switch is the entire switch-block - a case is not a separate scope. This leads to two problems: Multiple declarations of the same variable name, and Jumping across a variable initialization, which you're not allowed to do. The trivial fix is to wrap each case in a pair of cur...
69,447,701
69,448,017
How do I find same lines in two files C++?
I need to write a program for my school project, which compares lines from two large files, one approx. 1.5G(40kk lines), and other one is approx. 5gb(100kk lines) to find duplicate lines and write those lines to new file. I've already tried writing those programs in NodeJs and Python, however, they weren't able to com...
You have multiple options to go about this and none of them are pretty. I believe, one of the more efficient options goes about something like this: #include <iostream> #include <fstream> #include <map> int main() { std::ifstream firstFile("firstFile"); std::ifstream secondFile("secondFile"); if (firs...
69,447,778
69,451,722
Fastest way to draw filled quad/triangle with the SDL2 renderer?
I have a game written using SDL2, and the SDL2 renderer (hardware accelerated) for drawing. Is there a trick to draw filled quads or triangles? At the moment I'm filling them by just drawing lots of lines (SDL_Drawlines), but the performance stinks. I don't want to go into OpenGL.
SDL_RenderGeometry()/SDL_RenderGeometryRaw() were added in SDL 2.0.18: Added SDL_RenderGeometry() and SDL_RenderGeometryRaw() to allow rendering of arbitrary shapes using the SDL 2D render API Example: // g++ main.cpp `pkg-config --cflags --libs sdl2` #include <SDL.h> #include <vector> int main( int argc, char** ...
69,447,813
69,447,847
Returning objects created within the called function's context
I remember reading somewhere that we should avoid returning objects that are created locally within the called function (i.e. only dynamically allocated objects may be returned). However, I am not sure if that is sound advice because when dealing, for example, with overloaded operators we may have code like the followi...
I remember reading somewhere that we should avoid returning objects that are created locally within the called function (i.e. only dynamically allocated objects may be returned). You remember wrong. You should not return pointers or references to local objects: int& foo() { int x = 42; return x; // DONT DO ...
69,447,994
69,450,073
Getting wrong answer for sorting linked list using merge sort
I tried writing a custom version of merge sort in which the sortList function is recursive but the merging function is iterative. I have tried dry running but unable to figure out the problem. This one is a custom testcase which is also resulting in Wrong Answer. Your input: 5 4 3 1 2 6 Your function returned the follo...
The merge function I was trying to implement was wrong. Here is the correct code. ListNode* Solution::sortList(ListNode* A) { ListNode * head = A; if(!(head) || !(head->next)) { return head; } ListNode * slow = head, * fast = head; while((fast->next) && (fast->next->next)) { ...
69,448,172
70,651,010
Can we run the openGL project from server using node.js child process?
I have been trying to automate the launching of OpenGL Project from server using node.js The problem is like whenever new client join in (create a window in browser) I want to launch the .exe file. .exe file is an OpenGL Project which renders different shapes using openGL and then send’s rendered data to the browser to...
Yes we can definitely run the openGL standalone application/project from node server using node's child process. The mistake in my application was, directory of the shader program was not relative with the child process directory.
69,448,623
69,448,794
Executing a generic function every N times with a static variable
I am trying to write a wrapper function that executes a given function every N times (something similar to Google logging's LOG_EVERY_N). What I have done so far is: #include <cstddef> #include <functional> #include <utility> template<size_t N, typename Callable, typename... Args> void call_every_n(Callable&& c, Args....
Every lambda expression is of different type, hence you can use it as a tag: #include <cstddef> #include <functional> #include <iostream> template<size_t N, typename Callable,typename Dummy, typename... Args> void call_every_n(Dummy,Callable&& c,Args&&... args) { static size_t counter = 0; if(counter == N - 1)...
69,449,383
69,449,415
Adding new item in C++ array
I am pretty new to c++ and was trying to add a new string in C++ array. In Python we can add new items by .append(). Is there any function like this in C++?
in C++ arrays are of a static size. I would recommend including the vector header and replacing the array with a std::vector. vector has a function to add a new entry
69,449,781
69,552,515
<utility> not necessarily included when swap() is performed - How can this become a problem?
Reading C++ named requirements: Swappable I've come across the following note It is unspecified whether <utility> is actually included when the standard library functions perform the swap, so the user-provided swap() should not expect it to be included. Suppose I have a user-defined type class Foo with a user-provide...
Let's try to understand the note you quoted from cppreference. It is unspecified whether <utility> is actually included when the standard library functions perform the swap, so the user-provided swap() should not expect it to be included. E.g., std::sort may perform the swap. To use std::sort, you need to include <al...
69,449,788
69,451,505
Get path of a known HWND
I'm trying to make an app that will run something only if in the moment that the dll is called, the window that is focused in that moment has the same path as a values that is given. That being said, the following code will be added in a dll which will have a function with the path value as it parameter that returns tr...
To get the result I wanted, I switched to QueryFullProcessImageName (like CherryDT suggested to take a look at), but you have to be careful, you need to run it with Admin rights to get the path for some apps like I encountered with Task Manager, maybe because it is an Windows app, not sure and you'll have to do some re...
69,449,981
69,450,190
What is the relation between C storage-class and C++ destructor
I am very new to C/C++ programming. Storage class in C signifies the visibility and life cycle of a variable. In C++, Constructor and Destructor are used to initialize & release-resources the object occupied. Yes, constructor helps reducing much of repetitive code but destructors are used to release and/or free res...
For C Storage classes see: https://stackoverflow.com/a/2661411/8740349 Let's not talk about implementions, as each compiler works differently, but if you ask about C++ spec, most keywords mean the same. Except that: register keyword was removed since C++17 (after being deprecated in C++11), without any alternative. au...
69,450,046
69,450,757
How to call function that use part of template parameter pack in c++?
I have following problem: I want to create variadic template class, that must call lambda, that may take first N parameters of template parameter pack (N may vary from 0 to the size of parameters pack and differs for different lambda). I think, that recursive template helper function, that will check if lambda is invok...
You might use std::index_sequence as helper: template <typename Callable, typename Tuple, std::size_t... Is> constexpr std::size_t is_invocable_args(std::index_sequence<Is...>) { return std::is_invocable_v<Callable, std::tuple_element_t<Is, Tuple>...>; } // Helper to know max number of args to take from tuple temp...
69,450,122
69,450,308
I want to make a static library for other programs to use, but I don't know why it failed
This is the source code of the file: fileselector.h: #ifndef FILE_SELECTOR #define FILE_SELECTOR const char *open_file_dialog(); const char *save_file_dialog(); #endif linux/fileselector.cpp: #include <cstring> #include "../fileselector.h" #include <iostream> const char *open_file_dialog() { ... } const char ...
You defined a set of C++ functions but are using them from a C program. Function names in C++ are mangled during the compilation phase to allow for multiple functions with the same name but different signatures to exist. C programs don't do name mangling, so the compiled name of the library functions don't match the p...
69,450,136
69,562,210
Different behaviours when initializing differently
When trying to initialize a Vector using the result of some operation in Eigen, the result seems to be different depending on what syntax is used, i.e., on my machine, the assertion at the end of the following code fails: const unsigned int n = 25; Eigen::MatrixXd R = Eigen::MatrixXd::Random(n,n); Eigen::VectorXd b = E...
The "official" answer by Eigen maintainer Antonio Sànchez is the following: [...] In this case, the triangular solver itself is taking slightly different code paths: the comma-initializer version is using a path where the RHS could be a matrix the assignment version is using an optimized path where the RHS is known t...
69,450,317
70,093,969
Group .ui files in project tree when using CMake
I have a simple gui project in QtCreator, which consists of several .cpp .h and .ui files and using CMake as a build system. The problem i face is that .ui files, as oposed to .cpp and .h files, aren't grouped under corresponding header in project tree. They are just shown on the same level as .cpp and .h headers (see ...
You can use source_group in your CMakeLists.txt to group *.ui files as a source group in QtCreator or another IDE file(GLOB_RECURSE UI_SRC "*.ui") source_group("Ui Files" FILES ${UI_SRC}) This also works for .qml files for example.
69,450,456
69,450,501
sscanf converting from octal: How does it know?
I have this code which converts a string to an int unsigned int formatInt(char *ptr) { int res; if (sscanf(ptr, "%i", &res) == -1) exit(-1); return res; } I fed it a char * pointing to the first char of "00000000041". Conversion to int returns me 33 (Implicit Octal to Decimal conversion) "00000000041" is a...
Recognizing the string as octal is a function of the %i format specifier to scanf. From the man page: i Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in...
69,450,645
69,450,701
How to provide a default parameter argument when the type of that parameter is a template type?
template <class V, class K> class Pair { public: Pair(const K& key, const V& value = initial) { // what should "initial" be here? // ... } } For example if I use the class like this: int main() { Pair<int, std::string> p1(21); // p1 should be {21, ""} as the default value of a string is "". ...
Try V() like: template <class K, class V> class Pair { public: Pair(const K& key, const V& value = V()) { } }; Or: template <class K, class V> class Pair { public: Pair(const K& key, const V& value = {}) { } }; Note that a default constructor is required (which is callable without arguments).
69,450,654
69,469,099
Iterating C array-type container class from Lua using LuaBridge
This may be a newbie question, but I have not been able to find an answer with web searching that will even help me get started. I have a container class that at heart is a C-style array. For simplicity, let's depict it as this: int *myArray = new int[mySize]; With LuaBridge we can assume I have successfully registere...
I'm answering my own question, because I have figured out that the question makes some incorrect assumptions. The existing code I was working with was a true iterator class (which is what it is called in the Lua docs) implemented in c++. These cannot be used with for loops, but that's how you get a callback function in...
69,450,682
69,452,567
Flatten nested for loops with C++20 ranges
Sometimes I need to "double for loop" and since I do nothing in outer for loop for first loop variable beside passing it to inner for loop I wonder if it can be done elegantly with C++20 ranges. Example of nested for loops I would like to "flatten". struct Person{ std::string name = "Bjarne"; }; std::vector person...
Yeah, what you propose is correct. Except it can still be a range-based for statement, you don't have to switch to an algorithm: for (const auto& ch : persons | std::views::transform(&Person::name) | std::views::join) { // ... } Most languages use the name map instead of tr...
69,450,804
69,450,951
what does variable != 0xFF mean in C++?
I have the following if function that has a condition on an array of a data buffer, which stores data of a wav file bool BFoundEnd = FALSE; if (UCBuffer[ICount] != 0xFF){ BFoundEnd = TRUE; break; } I was just confused on how 0xFF defines the condition inside the if function.
what does variable != 0xFF mean in C++? variable is presumably an identifier that names a variable. != is the inequality operator. It results in false when left and right hand operands are equal and true otherwise. 0xFF is an integer literal. The 0x prefix means that the literal uses hexadecimal system (base 16). The...
69,450,988
69,451,032
Vector elements to a string
I'm trying to turn a vector<int> into a string, with a '[' at the beginning, and a ',' between each element of the vector, and a ']' at the end. But my output is [,,,,] (wanted output [6,4,3,2,1]). Can you explain to me what i'm doing wrong? Here's what I tried: int main() { std::vector<int> elements = {1,2,3,4,6};...
std::string::push_back adds a single char to the string and you tripped over the implicit conversion of int to char. The low values correspond to non-printable characters, thats why you don't see them in the output. You can use operator+= and std::to_string: #include <vector> #include <string> #include <iostream> int ...
69,451,487
69,452,392
How to control implicit conversion from long to int?
I am working on this LeetCode problem to take an integer and reverse it, given that the reversed in is within the signed 32-bit range, in which case we should return 0. and this code is doing just that, even with numbers like 1534236469/-1534236469. Except when it comes to tricky numbers like -2147483648 where its not ...
[...] when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0. That number is "tricky" because it's equal to std::numeric_limits<int>::min() in your environment and given a two's complement representation of type int, it happens that std::abs(-21...
69,451,793
69,452,137
Explicit template instantiation example
I am currently reading a book and it has the following example: //ch4_4_class_template_explicit.cpp #include <iostream> using namespace std; template < typename T > //line A struct A { A(T init): val(init) {} virtual T foo(); T val; }; //line B //line C template < class T > //T in this line is template...
Maybe this help you to unsderstand. From the C++ 20 (13.9.2 Explicit instantiation) 2 The syntax for explicit instantiation is: explicit-instantiation: externopt template declaration There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An...
69,452,280
69,452,781
Win32 unicode swprintf_s call generates buffer overrun warning
I'm writing a small application to target Win32 using C++. The compiler is set to support unicode and I'm compiling in x64 mode. I'm using Visual Studio 2019. Everytime I call swprintf_s, like below: wchar_t buff[500] = { 0 }; swprintf_s(buff, sizeof(buff), L"Could not free DLL handle: 0x%X\n", GetLastError()); OutputD...
As commented by van dench, the second parameter is the number of chars, not the size of the buffer in bytes. Correct code: wchar_t buff[500] = { 0 }; swprintf_s(buff, 500, L"Could not free DLL handle: 0x%X\n", GetLastError()); OutputDebugString(buff);
69,453,193
69,453,307
Remove '+' after the last output
I have a C++ code that calculates change. It takes input, and returns output by how change will be received. I need to remove the + sign after last change output. Is there a way to do this? My code: if (n500 > 0) { cout << n500 << " x 500 + "; } if (n200 > 0) { cout << n200 << " x 200 + "; }...
I would do the other way: put the separator " + " when previous display has already be done: const char* sep = ""; if (n500 > 0) { std::cout << sep << n500 << " x 500"; sep = " + "; } if (n200 > 0) { std::cout << sep << n200 << " x 200"; sep = " + "; } if (n100 > 0) { std::cout << sep << n100 << " x...
69,453,247
69,453,490
How to properly call destructors when exiting within a thread?
Context: I'm working with with a project composed simplistically of three layers, an application layer, an interface layer, and a middleware layer. The interface layer provides additional functionality on top of the middleware layer, and is responsible for managing threads running the middleware application. My issue i...
It is the thread that calls exit that does all of the cleanup. Several cleanup steps are performed: The destructors of objects with thread local storage duration that are associated with the current thread, the destructors of objects with static storage duration, and the functions registered with std::atexit are exec...
69,453,363
69,454,312
C++11 Simple Producer Consumer Multithreading
I am trying to teach myself multithreading and I followed this tutorial here: https://www.classes.cs.uchicago.edu/archive/2013/spring/12300-1/labs/lab6/ If you scroll all the way to the bottom there is a sample snippet of a producer-consumer and it asks us to solve the race conditions found in this code: #include <iost...
Producer: thread producer([&]() { for (int i = 0; i < 500; ++i) { { // Just have a lock while interacting with shared items. unique_lock<mutex> lock(mtx); goods.push(i); c++; } cond_var.notify_one(); } // Lock to update shared ...
69,453,511
69,493,622
Can't QOverload private signal, using Qt docs example
Here in the Qt documentation is written: Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user. Note: Signal activated is overloaded in this class. To connect to this signal by using the function pointer syntax, Qt provides a convenient helper for obtaining the function...
If you can use C++14 you can use a helper function: template<class T> auto privateOverload(void ( QSocketNotifier::* s)( QSocketDescriptor,QSocketNotifier::Type,T ) ){return s;} and then you can use QObject::connect(socketNotifier, privateOverload(&QSocketNotifier::activated),/*...*/); If you can use C++20 you can al...
69,453,770
69,454,188
How to invoke cmd.exe /c cls from within VS Code tasks.json?
I have a simple HelloWorld.cpp file and I want to run it with the following steps, each is run one after the other as follows. Compile Clear Integrated Terminal Run the produced executable. Unfortunately I fails to setup the second step (clearing the console window). What is the correct setup? { "version": "2.0.0...
Aha. I found the solution: Add "type": "shell" to the CLEAN step as follows. { "type": "shell", "label": "CLEAN", "command": "cls", "dependsOn": "COMPILE" } The complete tasks.json. { "version": "2.0.0", "tasks": [ { "label": "COMPILE", "command": "cl.exe", ...
69,453,972
69,453,973
Get all non-zero values of a dense Eigen::Matrix object
Asuming you have a dynamic size Eigen::Matrix object and want to do some computation on only non-zero values, how can you get a vector or list representation of all non-zero values? Matrix3f m; m << 1, 0, 0, 0, 5, 6, 0, 0, 9; VectorXf v = get_non_zero_values(m); cout << v; should give you 1 5 6 9 How can th...
After a lot of research in the web and inspired by this stackoverflow post I came up with my own solution template <typename T> Eigen::Matrix<T, Eigen::Dynamic, 1> get_non_zeros(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& _input) { Eigen::Matrix<T, Eigen::Dynamic, 1> reduced(Eigen::Map<Eigen::Matrix<T, Eigen:...
69,454,584
69,454,726
How to read from file in c++ and insert data from file into vector thats is type of an class?
Like the title says I need to insert data from file into vector that is a type of class I created. Here is my code: #include <iostream> #include <fstream> #include "Film.h" #include "Comedy.h" #include <string> #include <vector> using namespace std; Comedy k; Film f; int main() { vector <Comedy> comedy; i...
Assuming Film has a constructor that takes a std::string, I suggest adding it to the derived classes: Example with Comedy: class Comedy : public Film { public: using Film::Film; // add the `Film` constructor(s) // ... }; Then adding a new Comedy can be done using std::vector::emplace_back: komedija.emplace_bac...
69,454,621
69,454,787
Why does x have an unexpected value after trying to initialize it with x, y = a, b?
#include <iostream> int main() { int x, y; x, y = 10, 20; std::cout << x; return 0; } I expect 10 as output but 16 is coming. What's the reason? Can someone explain that behavior in c++ please?
x, y = 10, 20; is interpreted as (x), (y = 10), (20);. The three expressions are just executed sequentally. x and 20 do nothing, and y = 10 does what it says on the tin. x remains uninitialzied, and reading it is undefined behavior. There is a way to do what you want, but it's a part of the standard library (#include ...
69,454,875
69,455,048
C++ how to input by word and count how much word i input
i did try using this program #include <iostream> using namespace std; int main() { string x; string a = "black"; string b = "red"; string c = "white"; int e, f, g = 0; //e = black; f = red; h = white; cout << "input car color :"; cin >> x; if (x == a) { cout << "continue inpu...
You need to use a loop to continue prompting the user for more inputs. And you need to increment your integers on each matching input you detect. Try something like this: #include <iostream> #include <iomanip> using namespace std; int main() { string input; int num_black = 0, num_red = 0, num_white = 0; ...
69,455,254
69,691,399
Writing a unit test in gtest for a function returning an nlohmann::json object
This is my function that I would like to create a test for: static nlohmann::json parse_json(const std::string& file_path) { std::ifstream i(file_path); nlohmann::json j = nlohmann::json::parse(i); return j; } I understand this type of test: TEST(FactorialTest, HandlesZeroInput) { EXPECT_EQ(Factorial(0),...
General answer : a good unit test follow the rule AAA Arrange : place where you prepare things that will be tested Act : function call under test Assert : Assert that the function call gives you the right result. So in your case you have to prepare / or better generate a file containing json data. (Arrange). Call the ...
69,455,319
69,456,438
how to detect atomic types using enable_if
Is it possible to detect my atomic type is being detected a if a type is atomic using enable_if ? Currently, my atomic type is anyway to distinguish being detected as a class type is there anyway to distinguish it as an atomic type
You don't even need enable_if in this case, specialization is enough: // By default, types are not atomic, template<typename T> auto constexpr is_atomic = false; // but std::atomic<T> types are, template<typename T> auto constexpr is_atomic<std::atomic<T>> = true; // as well as std::atomic_flag. template<> auto const...