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
74,507,174
74,507,654
Loop through a sequence of characters and swap them in assembly
My assignment for school is to loop through a sequence of characters in a string and swap them such that the end result is the original string in reverse. I have written 3 assembly functions and one cpp function but on the function below I am getting a few errors when I try to run the program and I'm not sure how to fi...
Based on reproducing the symptoms, I diagnose the problem as: this is 32-bit x86 assembly (clearly), but it was treated as x64 assembly, and that didn't work. the .model directive is not valid for x64, so there is a syntax error there. pushing and popping 32-bit registers is not encodeable in x64, so there are invalid...
74,507,255
74,509,046
What is MATLAB's algorithm to calculate histogram with hist function?
I'm working on translation of some old MATLAB code to C++. I have noticed, that my custom function to calculate histogram that supposed to be equivalent to MATLAB [counts,centers]= hist(___) gives different results. I could not find a bug in my implementation, so I used MATLAB Coder to generate C++ function from MATLAB...
That bit of code adds eps to each bin edge except the first and last. It is hard to know why hist does this, they must be working around some edge case they discovered (presumably related to floating-point rounding errors), and figured this was the best or the easiest solution.
74,507,509
74,507,694
Resolve ambiguity in assignment constructor c++
Description I have code that is ambiguous when a certain constructor is present. But, when I comment said constructor out, then the compiler complains that a necessary constructor is missing. Minimum Working Example struct X; struct E{ E(const double& r){ /* important protocol stuff */ } E(const X&); }; struc...
The ambiguity occurs because (in the x = 3.0; line) the compiler can't decide which of the two assignment operators to use: the one with the X& argument or the one with the E&, as both parameter types are convertible from the given double (because both E and X have constructors that take a const double& parameter). You...
74,508,049
74,508,349
How to perfectly forward multiple struct members
I'm looking to get some clarity on the correct way to forward multiple members from the same forwarding reference to a struct. Example Here's an example of forwarding two fields (one_field and another_field) to a class constructor (widget) from a forwarding reference argument info. This is how I previously thought we s...
the forward you have already does the correct thing (i.e. forward the member as Bundle) and access a field is not like to invalidate the parent object. template<typename Bundle> auto make_widget(Bundle&& info) { return widget( std::forward<Bundle>(info).one_field, std::forward<Bundle>(info).another_...
74,508,173
74,508,262
static member definition outside class template template
I'm getting: error: default argument for template parameter for class enclosing 'ticker<T, E, A>::garbage_element' 51 | E ticker<T,E,A> ::garbage_element; | ^~~~~~~~~~~~~~~ l know if I use the keyword "inline" like this: inline static E garbage_element; inside the "ticker" template, ...
When defining the static data member of a class template which has a default argument for one of its template parameter, the default argument should not be repeated. It is needed only once when the class template is first declared/defined. This means you don't need to specify the default argument for parameter A when d...
74,508,184
74,508,360
Emscripten and C++ 20
It looks like emscripten does not support C++ 20 I try to compile this: #include <stdio.h> #include <span> using std::span; int main() { int a[2] = {1, 3}; printf("hello, world!\n"); return 0; } command: ~/emsdk/upstream/emscripten/em++ ~/Documents/helloWord.cpp I get this: error: no member named 'span' in ...
adding the flag -std=c++20 worked Credit: @Someprogrammerdude @MarcGlisse
74,508,332
74,511,659
Boost::program_options how to parse multiple multi_tokens
is it possible to parse multiple mulit-token parameters with the same name? Like: program.exe --param a b c --param foo bar ? I only could get it to work like this: program.exe --param "a b c" --param "foo bar" but then I have to split the parameter myself. [...] options.add_options()("param", po::value<vector<string>>...
I think you want a combination of composing and multi-token: Live On Coliru #include <boost/program_options.hpp> #include <fmt/ranges.h> namespace po = boost::program_options; using strings = std::vector<std::string>; int main(int argc, char** argv) { po::options_description opts; opts.add_options()("param", ...
74,508,448
74,508,489
How to pass the first element of an object to a function in C++?
I am trying to send the first element of an object to a function and modify its attributes and return back. I have already created a Ray object with 20000 rays. Each single ray has its own properties. How can I pass the first ray to a function to modify one of its property since I dont want to pass all rays because of ...
If you want to pass a single Ray, simply do so. If you want to modify it, pass it as reference (non-const), optionally returing reference to original: Ray &hi(Ray &bb) { bb.bounces++; // modify the original, passed as reference return bb; // return reference to original, for convenience } Or, if you don't wan...
74,508,689
74,550,835
C++ quicksort with const unsigned** input pointers
I am currently struggling with Pointers in C++, especially with the input of following function: /* ... there is an immutable array a of unsigned integers that we are not allowed to change In order to sort this array, a second array b containing pointers to the individual elements in a is created. We then sort the poin...
First of all, I know this stuff is really tricky when starting out with c/c++ and I had my fair share of confusion when I did. Therefore I will try to explain it the best way I can: What you are trying to do in your swap function is changing the actual value of the integers behind the pointers by dereferencing two time...
74,508,962
74,508,974
C++ new and delete with structs
I have a customer node and an item node structure and I'm trying to test them. I make a customer node and add some items to its basket. However, when I'm deleting the nodes, the program mostly crashes. I'm trying to first delete the basket and then delete the customer node. The code sometimes runs fine but sometimes cr...
Error here this->itemName = new char[strlen(name)]; strcpy(this->itemName, name); should be this->itemName = new char[strlen(name) + 1]; strcpy(this->itemName, name); The + 1 is required for the nul terminator that C strings have. Without it you are corrupting the heap. Classic symptom of a corrupt he...
74,509,182
74,509,250
How can I pass a function that must be treated as a member function of template type
I have created the following simplified working example - where a class Manager takes a template argument and must invoke a member function get_timestamp against the template argument. class Ex1 { public: int timestamp; int get_timestamp() {return timestamp;}; }; template<typename T> class Manager { ...
You can pass a member function pointer as a template argument: template<typename T, int(T::*FUNC)()> class Manager { public: void process_data(T& type) { (type.*FUNC)(); } }; Manager<Ex1, &Ex1::get_timestamp> mgr; Of course you can also pass it as a runtime argument to process_data(), or to the Manage...
74,509,244
74,509,285
Is referencing a member during Initialization valid?
I have a struct that contains multiple members. these members should be constructed using another member. Is accessing this other member for the initialization of the members valid, or am I invoking UB this way? struct Data { int b; }; struct Bar { Bar(Data& d): a(d.b){ } int a; }; struct Foo { D...
Members are initialized in the order they are declared in the struct/class and you can validly reference other members during initialization, as long as they have already been initialized at that point. This holds regardless of how initialization is performed.
74,509,349
74,510,153
How to fix error invalid conversion from 'char' to 'const char*' [-fpermissive]?
Hi i am a beginner and i have to make a simple phonebook programme in C++ using library . I would definitely use but im not allowed to as it is for an assignment. Below is my code until now and i have 3 errors which i don't know how to solve. I know conversion from char to const char* is not allowed but i really need ...
maybe you don't understand struct well, here is a sample I have revised, you can take it for reference #include <iostream> #include <stdio.h> using namespace std; struct person{ char name[30]; char surname[30]; char phone_number[30]; }; int main() { person Persons[] = { // structure initialization ...
74,509,409
74,509,487
Segmentation fault whrn trying to sort the array by quick sort
I'm making a program of quick sort which prints the sorted elements of the arry but when I run the code I get segmentation fault #include <iostream> using namespace std; int partition(int arr[],int left,int right,int pivot) { while(left <= right) { while(arr[left] < pivot) { left++; }...
Add this to top your quick_sort function if (left >= right) return;
74,509,450
74,509,618
Call a block of code once every 10ms in a while loop without stopping the loop c++
So I'm trying to run a block of code once every 10ms in a while loop without stopping the loop (sleeping). I would like to achieve something like this: while (true) { if (should_run_the_10ms_code) { // some code (once every 10 ms) } // some other code (every tick) }
std::chrono::steady_clock::now gives you the current time from a monotonic clock. Here is a relatively simple way to use it: auto timer = std::chrono::steady_clock::now(); while (true) { auto now = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> timer_diff_ms = timer - now; if (t...
74,509,711
74,511,403
Boost multiprecision cpp_float not working properly when not using cpp_bin_float_(50/100)
I need to do calculations with higher precision than doubles and am using boost::multiprecision for that. This works perfectly fine when I use boost::multiprecision::cpp_bin_float_50 or boost::multiprecision::cpp_bin_float_100. So simply doing something like #include <boost/multiprecision/cpp_bin_float.hpp> // ... boo...
The boost::multiprecision::cpp_bin_float<200> type is a backend type. You want a frontend type, which would be e.g. number<cpp_bin_float<200> > You can compare this with the definitions of the working types: using cpp_bin_float_50 = number<backends::cpp_bin_float<50> > ; using cpp_bin_float_100 = number<backends::cpp_...
74,509,839
74,521,330
How to include Libraries without an IDE
I just downloaded the MingW Compiler and the glfw and glad libraries. i set up Notepad++ to compile with mingW and now i cant figure out how to include the above mentiond libraries. do i have to put the .h files in my folder with my main.cpp file or smth? where do i have to unzip my libraries to. I have absolutly no id...
First of all, consider MinGW-w64, it's much more up to date than MinGW and supports both Windows 32-bit and 64-bit. You can get standalone versions from https://winlibs.com/, or you can install it from MSYS2 using pacman. To use a library you need to do several things: Include the header file(s) in your code using #in...
74,510,107
74,510,449
How to extract a particular line from an external txt file using C++ and then output the line as a string?
This code only works for printing the first line. What should I do to print only the second or third line? #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ string str; string lineFromFile; ifstream myfile("./file.txt"); while(getline(myfile,lineFromFile)){ st...
You can count the lines and equate your expected line number with the counter to output your line as in the below example. #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ int count = 1; int line_count; string str; string lineFromFile; ifstream myfile("./file.txt"); std::...
74,510,288
74,511,189
Implementing Square Root function in C++ not Working
double _sqrt(double n) { double sqrt = 0, c = 0, prec = 1; for (;; sqrt += prec) //increments sqrt per precision { c = sqrt * sqrt; if (c == n) { return sqrt; } if (c > n) // if square is greater then.. { sqrt -= prec; // decrement squ...
Your code has a few problems in it, the first one being that your code may infinitely loop as you try to have an infinite accuracy for a (possibly) irrational number. Although doubles do not have an infinite accuracy, I certainly wouldn't recommend trying to evaluate that function to that high of a degree of accuracy. ...
74,510,609
74,521,895
Do dependent reads require a load-acquire?
Does the following program expose a data race, or any other concurrency concern? #include <cstdio> #include <cstdlib> #include <atomic> #include <thread> class C { public: int i; }; std::atomic<C *> c_ptr{}; int main(int, char **) { std::thread t([] { auto read_ptr = c_ptr.load(std::memory_order_rel...
Your code is not safe, and can break in practice with real compilers for DEC Alpha AXP (which can violate causality via tricky cache bank shenanigans IIRC). As far as the ISO C++ standard guaranteeing anything in the C++ abstract machine, no, there's no guarantee because nothing creates a happens-before relationship b...
74,510,633
74,510,749
How to call EXPECT_CALL gtest macro before the object construction
I have a class that calls a mocked function in the initializer list. I want to use EXPECT_CALL in order to verify that the mocked function is called only once. The problem is that I can't use the macro before the constructor because it's the first function that runs, neither after it because the mocked function is call...
You can defer initialization of Foo by using a pointer: class FooTest : ::testing::Test { public: FooTest() { EXPECT_CALL(m_ui, get_name()); m_foo = std::make_unique<Foo>(m_ui); } protected: std::unique_ptr<Foo> m_foo; MockUI m_ui; }; Or by adding a parent class that will initia...
74,511,091
74,511,130
adding other random characters to the compiled code
enter image description here here is the code in C++ but after compiling and seeing the results, some random characters are added to the characters that the program should display compilation result as above picture why is this happening why those characters that are not declared in the code are added here is my code: ...
So if you want to output your arrays with no random characters outputed(undefine behaviour) you need to use a simple for loop and then you will get the correct output, like this: #include <iostream> using namespace std; int main() { char big_characters[26] = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', ...
74,511,440
74,511,453
Is it possible to declare a pair that contains a pointer to a similar pair
I am looking for something like: pair<int, pair<int, ...>*>*> p; Is it possible to declare such pair? Is there already a data structure for this?
struct A { std::pair<int, A *> p; }; You could also inherit from the pair, but I wouldn't do it to keep the code simpler.
74,511,594
74,512,715
Can one volatile constexpr variable initialize another one in C++?
C++ standard allows constexpr volatile variables per defect report 1688, which was resolved in September 2013: The combination is intentionally permitted and could be used in some circumstances to force constant initialization. It looks though that the intention was to allow only constinit volatile, which was not ava...
Clang is correct. The initialization of j from i requires that an lvalue-to-rvalue conversion be performed on i, but according to [expr.const]/5.9, an lvalue-to-rvalue conversion on a volatile glvalue is never permitted inside a constant expression. Since i is a constexpr variable, it must be initialized by a constant ...
74,512,080
74,512,096
C++ use function's output as functions input n times
I'm sorry for the weird title. I don't know how to word this. If I have function func() How do I do this: func(func(func(func(func(x))))) where it repeats N times? I'm trying to implement Conway's Game of Life. I have a function that takes a vector and outputs another vector, which is the next generation of the input ...
The easy way, simply using for loop: int x = some_initial_value; for (int i = 0; i < NUMBER_OF_ITERATIONS; ++i) { x = func(x); }
74,512,166
74,552,120
Sorting pairs of elements from vectors to maximize a function
I am working on a vector sorting algorithm for my personal particle physics studies but I am very new to coding. Going through individual scenarios (specific vector sizes and combinations) by brute force becomes extremely chaotic for greater numbers of net vector elements, especially since this whole code will be loope...
Thank you to everyone who commented!!! I really appreciate your effort. The solution ended up being much simpler than I was making it out to be. Essentially, from the physics program I'm using, the particles are given in a listed form (ie. 533 e-, 534 p+, 535 e+, etc.). I couldn't figure out how to get range-v3 worki...
74,512,695
74,512,710
C++ move constructor called instead of copy constructor
I have this snippet of code which I'm compiling with g++.exe -std=c++20: #include <iostream> using namespace std; class A { public: A() = delete; A(int value) : value(value) {} // A(auto &other) { // cout << "Copy constructor called..." << endl; // value = other.value; // } void operator=(const auto...
In this case it's not actually a move constructor, it's a constructor with a universal reference, so it takes both lvalues and rvalues. If you want to restrict it to rvalues only, you should use explicit type: A(A &&other) { ... } I am wondering why doesn't the compiler just call a default copy constructor (what ha...
74,512,885
74,512,969
Implementation of std::vector<T>::iterator::operator[]
For this code: std::vector<int> vec{0, 1, 2, 3, 4, 5, 6, 7}; std::cout << (vec.begin() + 4)[2] << " \n"; // prints out 6 std::cout << (vec.begin() + 4)[-1] << "\n"; // prints out 3 It output 6 and 3 as expected. I checked the cppreference, but couldn't find the definition of std::vector::iterator::operator[], so...
std::vector<T>::iterator is a Cpp17RandomAccessIterator, where for an iterator a, a[n] works as *(a + n). And "T*::operator[]" is called the "built-in subscript operator" which, when selected, means pointer[index] is identical to *((pointer) + (index)). It is defined here, satisfying the requirement for Cpp17RandomAcce...
74,512,997
74,513,118
Why is the C++ standard library divided into several components/libraries?
The C++ standard divides the standard library into different distinct components/libraries. Some components are built up of several headers. Why is the standard organized in this way? What practical advantage does this bring us? Why doesn't the standard library only define headers (+ potentially implementations)? I am ...
Separation of concerns, organization, etc. is already achieved with the definitions of the headers. Are they? Consider Chapter 22: Utilities. This chapter covers material defined in 13 separate headers. The standard could have had 13 separate chapters, but like... why? What good is that? Is there some reason advantag...
74,513,172
74,513,292
Understanding C++ function with return type void *
I am working in Unreal Engine C++ and wish to fetch the vertex normals of a static mesh. To do this I am using the GetTangentData() method which belongs to the FStaticMeshVertexBuffer class (link). The GetTangentData() method is defined two ways in the docs (link1, link2): void * GetTangentData() const void * GetTangen...
Q1. What is the reason to have a void pointer return type? A void* is a pointer to something, but that something is not known. Thus, there is a degree of flexibility to void*, resulting in the ability to be cast into many types of pointers. For example, malloc has a return type of void* because it's supposed to be used...
74,513,211
74,513,378
BOOST_FUSION_ADAPT_STRUCT using a recursive struct with a std::vector<self_type> member
I am trying to declare a recursive AST for a spirit x3 parser. The parser grammar is working, and since it is recommended to avoid semantic actions I am trying to adapt the Rexpr official documentation example. In the main documentation, the parsed structure can be represented by a map where keys are strings and values...
I'm not sure I follow the problem, but perhaps this helps: Live On Compiler Explorer #include <boost/spirit/home/x3.hpp> #include <boost/spirit/home/x3/support/ast/variant.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/io.hpp> #include <iostream> namespace ast { using boost::...
74,513,309
74,513,353
Program doesn't execute for loop until the end
I'm writing a code to enter subjects' information where I put void function and array as an object. But not sure when I wanna loop it, it doesn't come until the end. Have a look at the code. void calculateCGPA::getGPA() { cout << "Enter the the name of the subject: "; cin >> subjectName; cout << "Enter the ...
Take note that in C++ 0 is the first element, and n-1 is the last element. By looping to n, you cause a buffer overflow, hence resulting an error. A solution would be as follows void calculateCGPA::getGPA() { cout << "Enter the the name of the subject: "; cin >> subjectName; cout << "Enter the credit hour:"...
74,513,422
74,513,462
C++ Why i'm getting trailing whitespace in the output of this?
This is a solution i've been working on for this codewars problem: https://www.codewars.com/kata/56a5d994ac971f1ac500003e/cpp I want the output to be "abigailtheta". I'm getting the correct output on vscode and the correct output when I compile the code from the terminal as well, but the codewars site shows that the ou...
I think your issue comes from here. for (int y{i + 1}; y < (i + k); ++y) { concChars += strarr[y]; } What happens if i+k >= strarr.size()? what is strarr[y] when y greater than strarr.len()-1? It can be whitespace, or some stranger character, or better, it crashes your program.
74,513,590
74,513,644
Is the content of a predicate in c++ wait_for method mutex protected or not?
Suppose, countMe is a global variable and I am launching 10 threads at the same time to this while loop, is the variable countMe mutex protected in the predicate? I think because when the code reaches to the wait_for it unlocks and releases the lock, the variable countMe isn't mutex protected. Am I right? while (true) ...
Am I right? Nope, you're wrong. I think because when the code reaches to the wait_for it unlocks the lock, the variable countMe isn't mutext protected. No, the mutex is in a locked state when the lambda gets evaluated. Guaranteed. cppreference.com describes the predicate version of wait_for in terms of wait_until, ...
74,513,623
74,514,599
c++ template template syntax: simplicity vs useability why not 'auto'
first code below compiled fine after sweating with the word 'class' five times in one line, and definition in "main" of shelf<std::vector, int> top_shelf; looks too fragmented to me, all of that just extract "class E : value_type" out of container.I needed this type_value so I can keep dummy:garbage_value in case an er...
If T is the vector type, then you can get the value type by T::value_type: template<typename T> class shelf { T::value_type garbage_value; // ⋮ };
74,513,660
74,513,753
Using funcion overload with the different child classes when I only have a list that contains the parent class
First a little explanation of my code to put into context the problem: I have a class that is responsible for drawing stuff on the screen, I use an overloaded function to draw the different types of drawable entities, the fuctions look like this: draw(entityType1* name); draw(entityType2* name); draw(entityType3* name)...
You can use the Visitor pattern to solve this problem. This pattern is delegating the function call to the object itself, so you don't need to use the type of the object to call the correct function. Here is how you can implement it: void Painter::draw(Scene* scene) { std::list<Entity*> drawables = scene->getDrawab...
74,513,805
74,513,888
If allocators are stateless in C++, why are functions not used to allocate memory instead?
The default std::allocator class is stateless in C++. This means any instance of an std::allocator can deallocate memory allocated by another std::allocator instance. What is then the point of having instances of allocators to allocate memory? For instance, why is memory allocated like this: allocator<T> alloc, alloc2;...
The default allocator is stateless, but other allocators may not be. However all allocators should share the same interface. You are not supposed to use std::allocator directly as in your example. You can just use new and delete for direct allocation/deallocation. You use std::allocator indirectly for generic allocator...
74,514,084
74,518,801
How to convert C++17's "if constexpr(std::is_literal_type<T>::value)" to C++11 SFINAE code?
Currently, I have this templated function in my codebase, which works pretty well in C++17: /** This function returns a reference to a read-only, default-constructed * static singleton object of type T. */ template <typename T> const T & GetDefaultObjectForType() { if constexpr (std::is_literal_type<T>::value) ...
As @Igor Tandetnik mentions in comments, static const T _defaultObject{}; works in both cases and performs compile-time initialization when possible. There's no need for constexpr. N3337 [basic.start.init]: Constant initialization is performed: [...] if an object with static or thread storage duration is initialized ...
74,514,368
74,514,459
Why auto cannot be used to define an implicitly deleted constructor
I have this small snippet (compiled with g++) where I have defined a move constructor: #include <iostream> using namespace std; class A { public: A() = delete; A(int value) : value(value) {} void operator=(const auto &other) = delete; ~A() { cout << "Destructor called..." << endl; } A(const auto &other) { ...
Since auto will be resolved to A, what is the reason for which the compiler still deems that particular constructor deleted? Because A::A(const auto &) cannot be a copy constructor as when auto is used in the parameter of a function, that function declaration/definition is actually for a function template. Basically ...
74,514,375
74,514,517
Returning a static cast to a pointer doesn't return a pointer C++
In an "Entity" class, there is a function that takes in a component typename as an argument, and should return a pointer to that component, if found in the component array. Instead it just returns a copy of the component, not a pointer, despite doing this: return static_cast<T*>(ptr) Here is the relevant code: ECS.h (...
Turns out I was returning a reference instead of a pointer in the getComponent() function. template<typename T> T& getComponent() const { // Returns pointer to component return *static_cast<T*>(compArr[getComponentTypeID<T>()]); } // Needs to be template<typename T> T* getComponent() const { // Returns poi...
74,514,777
74,515,495
C++ CString format with %f, double number became very big value
I am maintaining C++ project but i am not family with C++. I am facing an issue, we use CString to convert a double value to String by double Dose; CString Dose2; if(Dose>0) { Dose2.Format("%f",Dose); }else{ Dose2.Format("0"); } When I set break point after format %f line of code, the value before and after to...
I tried to write Dose value to file before format string, it also had big value. FILE *fpversion; fpversion = fopen("doserate.txt", "a"); fprintf(fpversion, "%f", Dose); fclose(fpversion); I take a look at source code set Dose value in another dialog. if(m_MapDlg.GetSafeHwnd()!=NULL) { m_MapDlg.Dose=Result; } I t...
74,514,843
74,521,423
Is concept a variant of SFINAE
SFINAE is a technology that permits invalid expressions and/or types in the immediate context of a templated function while the concept seems to have the same effect since we are only permitted to use expressions and types(in requires-expression) in the constraint-expression of the concept-definition, and the constrain...
They are not equivalent. Concepts can appear in more places and are partially ordered by subsumption. Some examples: 1. Concept subsumption may be used to rank overloads. With SFINAE, this is an error: template <typename T> auto overload(T) -> std::enable_if_t<std::is_copy_constructible_v<T>>; template <typename T> aut...
74,515,060
74,515,135
visibility of a class data member in a nested class?
AFAIK, data member of enclosing class are also visible in nested class. struct A { struct B { int arr[n]; // how come n is not visible here, but it is visible in next statement. int x = n; }; static const int n = 5; }; see live demo here
how come n is not visible here, but it is visible in next statement. Because int x = n; is a complete class context while int arr[n]; is not. This can be understood from class.mem which states: 6) A complete-class context of a class is a: 6.4) default member initializer within the member-specification of the class. ...
74,515,480
74,520,688
Vulkan storage buffer vs image sampler
I am currently building an application in vulkan where I will be sampling a lot of data from a buffer. I will be using as much storage as possible, but sampling speed is also important. My data is in the form of a 2D array of 32 bit integers. I can either upload it as a texture and use a texture sampler for it, or as a...
Guarantees about performance do not exist. But Vulkan API tries not to decieve you. The obvious way is likely the right way. If you want to sample then sample. If you want to do raw access then obviously do raw access. Generally, you should not be forcefully trying to put a square in a round hole.
74,516,708
74,516,760
Passing objects of different derived class as a parameter to a function that expects base object of class
I have a base class Device and inherited class InputDevice. In class XYZ I have a function XYZ::setDevice(int num, Device device) that expects object Device as parameter. When I call the function setDevice() with parameter that is sublclass of Device (InputDevice) it gets converted to Device and I can't access the deri...
I don't see the full code, but instead of storing objects, you should store pointers. Your devices array should be vector or array of Device pointers. Here's a fully working example. #include <iostream> #include <string> #include <vector> using namespace std; class Device { public: virtual string getName() const ...
74,517,642
74,518,599
use promise multiple times
I am trying to signal a function on a seperate thread using a std::promise class MyClass { std::promise<void> exitSignal; std::thread monitorThread; } void MyClass::start() { exitSignal = std::promise<void>(); std::future<void> futureObj = exitSignal.get_future(); monitorThread = std::thread(&MyClass::monito...
I am going to echo the comment by @Homer512 and suggest that you are calling stop() twice. I made a small test using your code: #include <future> #include <thread> #include <iostream> #include <chrono> struct MyClass { std::promise<void> exitSignal; std::thread monitorThread; void start(); void stop()...
74,517,701
74,548,823
PhysX Overlap Scene/Geometric Query for Capsules
I am trying to do a scene query using Capsule colliders and for some reason the overlap function I had returns true even though in the PVD, the capsule are definitely not colliding (they are quite close together though). This is weird because my OnTrigger/onContact functions were called correctly only after an actual c...
I discovered the issue, turns out, the overlap queries do not consider the local transform of the PxShape, thus I solved it using: physx::PxGeometryQuery::overlap(collider->GetPhysXShape()->getGeometry().any(), actor1->GetPhysXActor().getGlobalPose() * collider->GetPhysXShape()->getLocalPose(), collider2->GetPhysXShape...
74,518,289
74,518,325
C++ pointer arithmetic for linked lists
I am just starting out self-learning C++, and as a toy problem, I am trying to do the following - given a linked list, I want to store all nodes that are even into a new list, and return this new list. For context, I come from a Python background. I have the following program - #include <iostream> using namespace std;...
You cannot do dynamic allocation by taking addresses of local variables. When the scope exits the local variable is destroyed and you are left with a pointer to an object which does not exist (known as a dangling pointer). Your code has this problem here node new_node = {.val = runner->val, .next = NULL}; // local vari...
74,518,307
74,518,551
Why q is not equal to 1.0?
I'm a neophyte with c++. I wrote this code but the result for q have to be 1.0, but the code give me, changing the variable's order when I recall function "intercetta", for example -34, 0, 9.75. Why? #include <iostream> using namespace std; float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) { ...
This function float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) { return m = ((y2 - y1) / (x2 - x1)); } has parameters passed by value. It means that it receives copies of the parameters you give. Whatever you do inside the function, cannot alter the parameters passed to it in main(). If ...
74,518,420
74,531,052
Exception in Concurrency task.then.wait affects further call of ::ShellExecuteEx()
Following logic is implemented to open a file by a "filename.extension" in a C++ application using managed-C++: try { CoInitialize(nullptr); auto task = Concurrency::create_task(Windows::Storage::StorageFile::GetFileFromPathAsync(filePath)); // an excpetion is thrown in the next line Concurrency::task_s...
Adding try/catch-blocks to the innermost .wait()-block solved the issue try { concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file)); launchFileOperation.then([&](bool success) { // logic }).wait(); } catch (concurrency::invalid_operation& ex) { ... } catc...
74,519,025
74,519,305
c++20 implement an interface for a vector
I'd like to create a class with can use any Vector. Possible types could be std::vector, boost::vector, etl::vector. All used vector types must implement std::vector member functions. I'd like to create a concept which validates that the used vector type implements all std::vector member functions So far I have come up...
You should do template instantiation of Vector_T like this. template<typename Element_T, IVector_T<Element_T> Vector_T> class TestVector { ... private: Vector_T myVec; };
74,519,642
74,519,715
how do I create an undordered map containing functions?
I have functions that are working with the following struct: struct stm { size_t op; std::string st_out; } and I have declared the signature of the unordered map that will save the references: std::unordered_map<uint64_t, std::function<int(stm&, const uint64_t)> instruction_actions; I wrote the functions of which...
First things first, your function write is missing a return statement. how should I add them in the map? There are multiple ways of doing this as shown below: std::unordered_map<uint64_t, std::function<int(stm&, const uint64_t)>> instruction_actions{{5, write}}; Or using std::map::insert instruct...
74,520,572
74,520,689
how does the compiler write values to the second value of the pair in this construct?
map<int,int> a; pair<std::map<int,int>::iterator ,bool> f; f=(a.insert({0,0})); cout<<f.second; why is it outputting 1? it always outputs 1 for any values in the pair
It's because the bool f.second tells you if insert inserted the pair<int,int> into the map. 1 means that it did insert it. bools are normally printed as either 0 (false) or 1 (true). You can use the I/O manipulator std::boolalpha to make it print true or false instead. it always outputs 1 for any values in the pair N...
74,521,146
74,521,949
Is writing in parallel to the values of a map thread safe?
AFAIK if two unsynchronized threads access the same memory location and at least one tries to write to it, you get a data race. This being said, in the following code sample, what is "the same memory location": std::unordered_map<int, std::string> map{{0, {}}, {1, {}}, {2, {}}, {3, {}}, ...
Most concurrent, non-const accesses to standard library objects do constitute data races. However, accesses through iterators are given an explicit carveout: Operations on iterators obtained by calling a standard library container or string member function may access the underlying container, but shall not modify it. ...
74,522,105
74,522,269
Static priority queue of pointers in c++
I have a class foo, and inside the class, I need a static priority queue bar that holds pointers to some number of foo objects, and the foo object also has a private member buzz that will hold the weight of the objects when compared. So far, I have tried the following: class foo{ private: // some stuff int buzz...
As you can see in the std::priority_queue documentation, the 3rd template argument Compare is: A Compare type providing a strict weak ordering. A function pointer (like you used) cannot be used for the compare type. One way to supply a compare type is via a class with opertor() (preferably a const one): #include <que...
74,522,160
74,522,668
Why does the compiler require return type in the following lambdas
I am implementing recursive DFS as a lambda passing itself as a parameter. If I comment out the logic that checks if the current node has no children, I get build errors saying that the lambda is used before type deduction. #include <vector> int main() { int root; std::vector<std::vector<int>> graph; // ....
Yes, the return; statement is exactly what tells the compiler the return type of the lambda. In this example, the statement says the function return void. Without knowing the return type, the call to self(self, v); is ill-formed, since you're effectively relying on auto being deduced without giving the compiler a way o...
74,522,843
74,544,232
AsyncWait in Lely CANopen is not behaving asynchronously?
I'm trying to perform some tasks using fibers in the Lely CANopen stack. However, I either don't understand the model, or something is broken. What I would like to do is run multiple tasks at different rates. An example based on the tutorial here: class MyDriver : public canopen::FiberDriver { public: using FiberDri...
(Answered here, but repeated below to make it easy to find.) That's because you're scheduling the tasks with Defer() instead of Post(). Defer() submits a task to a "strand" executor. A strand guarantees that tasks submitted to it never run concurrently. So it will only execute task B once task A finishes. This can be u...
74,522,871
74,523,221
Efficient way to repeatedly generate same random number in C++?
I am working on a secure LoRa transmission, where I need to generate the same pseudo-random number on the transmitter and the receiver (it would be part of the encryption algorithm) based on an input counter. So this function should give the same output for a given input, just like a hashing algorithm. As an example he...
You should not use rand for this purpose as it is implementation-defined which presents a couple of issues for your use-case: It may produce different numbers on different targets It is not guaranteed to be cryptographically secure What you describe is a cryptographic hash function. There are many libraries available...
74,522,923
74,523,122
Why does declaring a copy constructor not delete the copy assignment operator and vice versa?
So if I've got a class and declare a copy assignment operator in it, obviously I want some special behavior when copying. I would expect the language to try to help me out by implicitly deleting the copy constructor until I explicitly bring it back, so as to avoid unintended different behavior when doing type instance ...
Them not being deleted is deprecated. E.g. Clang 15 with -Wextra, given struct A { A() {} A(const A &) {} }; int main() { A a, b; a = b; } spits <source>:4:5: warning: definition of implicit copy assignment operator for 'A' is deprecated because it has a user-provided copy constructor [-Wdeprecated-co...
74,523,636
74,526,573
inline const(expr) variables vs functions returning static const(expr) variables - Is there any reason to prefer one or the other approach?
Several times I've seen code like this in a header IMPORTOREXPORT std::string const& foo(); IMPORTOREXPORT std::string const& bar(); IMPORTOREXPORT std::string const& baz(); and the following corresponding code in a cpp file std::string const& foo() { static std::string const s{"foo"}; return s; } std::string cons...
As you note, the inline variable approach guarantees that the variable has a unique address, just like the static local variable approach. The inline approach is certainly easier to write, but: It doesn't work on pre-C++17 compilers. It's more expensive to build: Every translation unit that odr-uses the inline variab...
74,523,718
74,523,855
No matching function when calling the function
I am a newbie to C++ and I wanted to know what should I do. I need to write a program where the user will be filling the 2d array. I need to program to show the 2d array in the form of matrix and do some other things, like counting elements that are not 0. But I am stuck. I can't call functions in main(), because there...
As suggested in the comments better way is to use std::vector, however if you really want to use raw C++ arrays, to have a correctly type passed in, you need to declare a pointer to pointers to dynamically allocated memory: int** arr = new int*[row]; for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) ...
74,523,742
74,530,121
Parsing path in JSON
I'm trying to pass a JSON object containing a path from my frontend (Node) to the backend (C++) using RapidJSON, like so: #include <iostream> #include "rapidjson/document.h" int main() { const char* json1 = "{\"path\":\"C:\\test.file\"}"; // works const char* json2 = "{\"path\":\"C:\\fol der\\t...
If you print your json variables you will get the following (C++ interprets the escape characters): json1: {"path":"C:\test.file"} json2: {"path":"C:\fol der\test.file"} json3: {"path":"C:\fol der\Test.file"} json4: {"path":"C:\few dol\test.file"} json5: {"path":"C:\folder\anotherOne\test.file"} Now you can test these...
74,524,029
74,524,098
What is "%rdi" in assembly and where does it take its value?
Intrigued by this post about UB, I've decided to start reading Jonathan Bartlett's Programming from the Ground Up in order to play around with C++ UB and see what the assembly looks like. But while trying out things I've found something strange in a pretty simple case. Consider this code int foo(int * p) { int y = ...
%rdi is reference to the register rdi. In this case, it appears that the compiler is passing the first parameter in a register instead of on the stack. Parameter passing is basically a convention: as long as the compiler is consistent in how it passes parameters, a compiler can switch from passing parameters one way (...
74,524,080
74,524,511
C++ Convert Unix time (nanoseconds) to readable datetime in local timezone
I have a Unix time (nanoseconds since epoch) and I would like to go back and forth between this and a readable string in a specifiable timezone (using TZ strings), with nanoseconds preserved. I am using C++17 but willing to migrate to C++20 if it would make things much easier. Example: uint64_t unix_time = 166905887011...
Using C++20, this is very easy. Using C++11/14/17 it is harder but doable with a free, open-source time zone library. Here is what it looks like with C++20: #include <chrono> #include <cstdint> #include <format> #include <iostream> #include <sstream> #include <string> std::string convert_unix_to_datetime(std::uint64_...
74,524,472
74,526,685
C++ Function Template is not deducing Eigen vector sizes
I have written a function template <int N> bool checkColinear(const std::array<Eigen::Vector<double, N>, 3>& points) noexcept; which takes three N-D points and returns true if they are collinear within a certain tolerance. Everything works if I call the function and explicitly specify N: std::array<Eigen::Vector3d, 3>...
As mentioned in the comments, this is likely a bug. A workaround is to spell out the full type name for Vector<double, N> as: Matrix<double, N, 1, 0, N, 1> ^ ^ ^ ^ col row/col major max rol max col And your functi...
74,524,907
74,525,011
Why can't i search for vs code extensions?
So i have fresh Manjaro installation and only software i have is ws code and some bloatware. But when i want to search for extesions like C/C++ it find somethink but not what i need. This is what i get my output what i want I find something like product.json but i cannot find its location or anything. I tried reinstall...
What you're using is Code - OSS and not VSCode; they're built from almost the same source except for the telemetry and the part that handles the marketplace (the latter being a proprietary component by Microsoft). As far as I know it's not possible to have VSCode's Marketplace working for another editor. Code - OSS rel...
74,525,865
74,526,081
Which is correct for sizing a vector
Hi I am just starting to learn cpp and I have two examples of getting the size of a vector in the for statements both seem to work but which is right and why? sizeof(vector) or vector.size()? Thanks Brian void print_vector(vector<string> vector_to_print){ cout << "\nCars vector = "; for(int i = 0; i < sizeof(ve...
std::vector<std::string> is a container class, which stores an array of std::strings plus other values to assist with manipulation of the array and providing information about the state of the stored array. When you call sizeof(vector_to_print) you are simply getting the size of the container class not the amount of el...
74,526,201
74,526,329
Defaulted template argument in std::optional constructor
std::optional has the following constructor: template < class U = T > constexpr optional( U&& value ); The question here is: why template parameter U is defaulted to type T? What happens if simply change constructor to following: template < class U /* = T */> constexpr optional( U&& value );
It's so if you give it an initializer list (which doesn't have a type, so can't infer a type for U), it will initialize a T temporary. For example: std::optional<std::vector<int>> opt({1, 2, 3}); // No type deduced for `U`, defaults to `std::vector<int>` struct X { int a, b; }; std::optional<X> opt({.a = 1, .b = 2...
74,526,571
74,540,764
How do I disable Manifest in VisualStudio using C++?
I'd like to have the UI elements switch to the Windows 95 UI for my program. But I am not sure how to disable Manifest in Visual Studio. Setting generate Manifest to off in the Linker doesn't seem to do it. Still new to this, not sure what the process is to shut it off.
Snippet SetWindowTheme(hWnd, L"", L""); SetThemeAppProperties(0); will disable visual style and use classic ui.
74,527,011
74,540,560
How to use Vector Class Library for AVX vectorization together with the openmp #pragma omp parallel for reduction?
I'm using OpenMP to parallelize the loop, that is internally using AVX-512 with Agner Fog's VCL Vector Class Library. Here is the code: double HarmonicSeries(const unsigned long long int N) { unsigned long long int i; Vec8d divV(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0); Vec8d sumV(0.0); const Vec8d addV(8.0); ...
Here is the final solution. It's using automatic reduction and avoids u64->fp conversion by computing divV = startdivV + i * addV only in the first iteration of each loop and then using divV += addV for all other iterations. Runtime to compute the sum of first 9.6e10 elements is {real 9s, user 1m46s} with 12 threads on...
74,527,151
74,534,935
How to connect signal from a different class?
// splashscreen.h class SplashScreen : public QMainWindow { Q_OBJECT public: explicit SplashScreen(QWidget *parent = nullptr); ~SplashScreen(); QTimer *mtimer; public slots: void update(); private: Ui_SplashScreen *ui; }; // app.h #include "splashscreen.h" class App: public QMainWindow { Q...
In App class, s is an instance, not a pointer to an instance. Function connect needs pointer, not reference. Use these syntax should help: QObject::connect(timer, &QTimer::timeout, &s, &SplashScreen::update);
74,527,726
74,527,780
Deduce types of template-defined base class constructor parameters
I have a derived class, Wrapper, that inherits from a template-defined base class. I'd like to configure Wrapper so that if the base class has constructor parameters, Wrapper's constructor also includes the base class's constructor params so that it can forward them to the base class constructor: struct Base1 { Base1...
Instead of having Args as a template parameter pack of the class template, you can make the constructor a template as shown below: //------------------v--------------->removed Args from here template <typename T > struct Wrapper : public T { //--vvvvvvvvvvvvvvvvvvvvvvvvvv----->made this a templated ctor template<t...
74,527,986
74,529,336
Is casting an address by reinterpret_cast an undefined behaviour?
I want to find a way to encapsulate a header-only 3rd party library without exposing its header files. In our other projects, we encapsulate by using void*: in the implementation, we allocate memory and assign to it, and cast to pointer of its original type when we use it. But this time, the encapsulated class is used ...
What you have here is undefined behavior. The reason is when you reinterpret an object to a different type, you are not allowed to modify it until you cast it back to the original type. In your code, you originally have the data as a char[1]. Later, in your constructor, you reinterpret_cast &data as Inner*. At this po...
74,528,017
74,529,354
C++ , cout line in function effects the result, function does not work without cout line
I'm trying to solve Codewars task and facing issue that looks strange to me. Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it. Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6). I wrote some bulky code with supporting functions...
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number. // calculates sum of digits until number has 1 digit ...
74,528,094
74,528,751
Find the number of subarrays whose average is greater than or equal K
Given an array of integers, find the number of subarrays whose average is greater than or equal to K. Constraints: 1 <= N <= 10^5 -10^9 <= A[i] <= 10^9 My solution: If A[i] is prefix sum upto ith index in the array then (A[j] - A[i]) / (j - i) >= K (A[j] - A[i]) >= K * (j - i) (A[j] - K * j) >= (A[i] - K * i) <- Let's...
You're already setting A[i] = A[i] - (K * i), so you need to find all i,j such that A[j] - A[i] >= 0, or A[j] >= A[i] Assuming j>i, the number of valid pairs should just be the total number pairs minus the inversion count. You won't require any special data structure that way (an array would suffice), and inversion co...
74,528,301
74,528,997
Why C-style Arrays performance in O3 is less than no optimization on Quick Bench?
Base on C-style Arrays vs std::vector using std::vector::at, std::vector::operator[], and iterators I run the following benchmarks. no optimization https://quick-bench.com/q/LjybujMGImpATTjbWePzcb6xyck O3 https://quick-bench.com/q/u5hnSy90ZRgJ-CQ75b1c1a_3BuY From here, vectors definitely perform better in O3. Howev...
Your -O0 code wasn't faster in an absolute sense, just as a ratio against an empty for (auto _ : state) {} loop. That also gets slower when optimization is disabled, because the state iterator functions don't inline. Check the asm for your own functions, and instead of an outer-loop counter in %rbx like: # outer...
74,528,443
74,528,889
How to use cmake and vcpkg to import GLAD/GLFW3/ImGUI libraries on MacOS?
My goal is to write a simple, portable application using ImGUI. I also want a platform-agnostic build experience using cmake, and vcpkg to install dependencies. I got the program built and running on my Windows machine, but it's failing on my Macbook (macOS Monterey 12.6). This is my vcpkg.json: { "name": "imguites...
This fixed it: brew install pkg-config I got more descriptive error messages after I deleted the build folder. This error message was hidden when configuring cmake with vscode, but was visible when doing it through zsh terminal. Building glfw3[core]:arm64-osx... warning: -- Using community triplet arm64-osx. This tripl...
74,528,554
74,528,640
Finding the average of a variable belonging to an object in a BST?
I am very new to cpp and am currently facing the following problem. I have csv file filled with Person object class which I need to insert into my BST. class Person{ string name; string job; int age; } I have successfully populated my BST with this Person object. I now need to calculate the ave...
Make the second argument to the BST visitor not a function pointer but a templated argument: template <typename T, typename Callback> void Bst<T>::InOrder(Node<T>* root, Callback&& callback) const { // ... callback(root->getData()); // ... } template <typename T, typename Callback> void Bst<T>::InOrderTraversal(...
74,528,719
74,529,674
Backgammon/Table game in Qt Creator, C++, how can I track the clicked buttons?
I'm trying to program Backgammon in Qt Creator using C++, This is what I got until now, I created diverse Qgroupboxes for example grp_b1, here I have now 5 Buttons which are the black figures in the upper corner. grid = new QGridLayout(); ui->grp_b1->setLayout(grid); feld1=new QButtonGroup; feld1_but...
You can call method sender() in your slot to get a pointer of call object. After that get pointer parent to get widget field. Example: QObject* obj = sender(); QObject* parent =obj ->parent(); And make static cast to widget
74,529,066
74,529,321
How to read the first byte of HAL_UART_Receive?
I'm trying to send a single char ("A") to my STM32 from my ESP32. I can see that the char goes through as I am receiving the char back on the ESP32 in the Arduino serial monitor but I can't seem to understand how to access it for using it to do something else on the STM32. Here is what I've been trying... //STM32 Code:...
To expand on the comment from @πάντα ῥεῖ: "A" is a string literal, with a type of const char[N]. This particular one is the string/array {'A', '\0'} (remember the terminating null-character). So if (RxTx_1[0] = "A") compares your Rx char to a pointer. 'A' is the character A with a char type, and if (RxTx_1[0] == 'A') d...
74,529,584
74,543,844
Protobuf oneof has_field private
I have made a simple protobuf file to reproduce my problem: syntax = "proto3"; package proto; message Test { uint32 test1 = 1; oneof param { uint32 test2 = 2; bool test3 = 3; } } When I generate the c++ code the oneof's has_param() member function is private. Is it normal ? How do I know ...
Refer to the documentation for Protobuf C++ generated code. The generator creates a method param_case(), which returns enumeration type that identifies which field inside the oneof is present. If the oneof is empty, it returns PARAM_NOT_SET.
74,530,070
74,531,099
Seek Highest Column Value From Today (Postgres, C++, QT)
Edit: The below query doesn't work but the concept given in the answer still applies. Check here for how to fix the query sqlite IFNULL() in postgres I have a table in Postgresql called 'transaction'. The primary key of this table is composite with (id, date), where id is an int and date is a timestamp. Every day, the ...
You need to update your sub-select select ifnull(max(id), 0) + 1 from pos_schema.transaction to something like SELECT ifnull(max(id), 0) + 1 FROM pos_schema.transaction WHERE pos_schema.transactiondate.date::date = CURRENT_DATE Please note that your field date should really be of type date instead of tim...
74,530,809
74,531,322
Template that calls member function on argument
I have some code that creates several listeners. Thus I was thinking about adding a template that calls the notify on different types of listeners. However I am not sure how to call the member function (which all have different arguments) in a template. I am using C++17. template <class T> void notifyListeners(std::vec...
template <class T, typename F, typename... Args> void notifyListeners(std::vector<T*> listeners, F f, Args&&... args) { for (auto& listener : listeners) { (listener->*f)(std::forward<Args>(args)...); } } Demo
74,532,771
74,534,804
C++ check input floats (-0.0f, +0.0f)
I am currently trying to build a program which prints an input float value to binary. The first bit is 0 if positive or 1 if negative, but with an input value of e.g.: -0.0g my if statement always prints 1, also for a positive input. How would I check that correctly? string sign = "sign: "; if(value <= -0.0f) sign....
+0.0 and -0.0 have the same value, yet different signs. value <= -0.0f is true for value as +0.0 and -0.0. @MSalters To distinguish the sign, use std::signbit(). @john if(std::signbit(value)) { sign.append("1\n"); } else { sign.append("0\n"); } Note that signbit() also applies to infinities and NaN. Even though ...
74,532,879
74,532,909
Stack problem c++. Error: ‘cin’ does not name a type
This stack program runs correctly for given array size arr[5] or arr[10].But when i take size as input from the user cin>>n it says "Error: ‘cin’ does not name a type." Here is that code: #include <iostream> using namespace std; class Stack { private: int n; cin>>n; int arr[n]; int top=-1; public: ...
There are two problems with this class definition class Stack { private: int n; cin>>n; int arr[n]; int top=-1; //... The first one is that you may not use statements that are not declarations cin>>n; And the second one is that variable length arrays are not a standard C++ feature. You could d...
74,532,913
74,561,679
What is the best way traversing an unordered_map with a starting from a random element in C++?
I have an unordered_map of 'n' elements. It has a some eligible elements. I want to write a function such that each time, a random eligible element is picked. Can this be achieved in the following time complexity? Best case: O(1) Avg case: O(1) Worst case: O(n) Referring - retrieve random key element for std::map in c+...
std::unordered_map has forward iterators, which do not allow random access. Refer to iterator on the documentation page of the container. Assuming all elements are eligible, std::advance() will go through size/2 elements on average. Because you only accept eligible elements, you will go through more than that. If you k...
74,533,641
74,533,817
Global variables in a translation unit, will they be stored contiguous and can pointer arithmetic be done?
Say I have global variables defined in a TU such as: extern const std::string s0{"s0"}; extern const std::string s1{"s11"}; extern const std::string s2{"s222"}; // etc... And a function get_1 to get them depending on an index: size_t get_1(size_t i) { switch (i) { case 0: return s0.size(); case...
Pointer arithmetic on disparate objects yields undefined behavior as per [expr.add]: 4 When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P. (4.1) — If P evaluates to a null pointer value and J evaluates to 0, the result is a null poin...
74,533,928
74,626,521
Upload file to Google Drive folder is failing
I am developing a function "uploading file to Google Drive folder" using c++ / Poco library. File is always getting uploaded to root folder only I have added optional parameter parents as below std::string strParents = "[ { "id": "" + std::string(locationId) + ""} ]" The code that I am currently using is as below and i...
I have found the issue. The issue is with Poco usage. Its for those developers who are struggling like me. "parents" should be added as an array object. Not as a single key-value object if I add as below fileDataObject.add("parents", "[ id ]"); its taking as a single value. When I stringify the post body, parents value...
74,534,000
74,534,176
How to define class attribute after creating class
I am trying to figure out how to define a Variable which is a member of a class in C++, Outside of the normal class body. It may be inside of a Function, or outside of the class. Is this possible. What I need is that the variable should be a member of the class such that if I call Nodesecond.birthdate, it returns the b...
You can do something close to JavaScript objects. #include <iostream> #include <unordered_map> using namespace std; struct Nodesecond { public: int Age; string Name; unordered_map<string, string> Fields; string& operator[](const string& name) {return Fields[name];} Nodesecond() { this->Age ...
74,534,196
74,535,257
linked list destructor with std::move c++
I'm learning data structures in C++; I've written a destructor for a linked list as follows: ~List(){ Node* temporary = new Node; Node* node = head; while(node != nullptr){ temporary = node; node = node->next; delete temporary; } } But then I ...
std::move doesn't do anything by it's own, it only cast something to rvalue. How the rvalue is used is determined by the function that accept it, and assignment of raw pointer does nothing different than copy in that case. But for example, if you're using std::unique_ptr, the operator=(unique_ptr&&) would delete the or...
74,534,510
74,534,683
Deleting items from QT's QListWidget leading to undeletion/corruption of other entries
Disclaimer : I am pretty new to UI and QT. I have UI that have QListWidget comprising of some numbers (1 to 5), now I am trying to delete the item one by one.. Problem : After deletion of all entries are done, I can still see some entries (specifically 2 & 4). Code: File : main.cpp Here I have created one async thre...
The reason is not really related to Qt but has to do with arrays and loops in general. Say, initially, I start with a list: 0. Apple 1. Orange 2. Jackfruit I remove the item at index 0: 0. Orange 1. Jackfruit Now in the loop, we do i++, and then remove the item at index 1. 0. Orange Notice that we completely skipped...
74,534,571
74,534,767
Forward declaration of structure pattern
I am forced to use the architecture which will be presented below. Forward declaration is the pattern I'm trying to implement to counter the issue. Here is what I have so far : class_with_config.h : #include "config_file.h" #include "i_class_with_config.h" class ClassWithConfig : public I_ClassWithConfig { // spec...
Main constraint is that I do not have the right to include config_file.h into side_class.h You can solve the issue by including side_class.h and config_file.h into side_class.cpp as shown below. side_class.cpp #include "side_class.h" //added this #include "config_file.h" //added this SideClass::SideClas...
74,534,852
74,535,116
Storing and using smart_ptr address
I'm trying to pass a shared_ptr to an object around, which may or may not be null: #include <iostream> #include <memory> struct MyObject { int i = 0; MyObject(const int i_) : i(i_) {} }; struct Command { std::shared_ptr<MyObject> cmdObj; Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) { std::cout <...
To store an address, you need a pointer. In this case, a pointer to a std::shared_ptr. struct Command { std::shared_ptr<MyObject>* cmdObj; Command(std::shared_ptr<MyObject>& obj) : cmdObj(&obj) { std::cout << "Store and use this address: " << &obj << std::endl; // [1] } void execute() { if (*cmdObj =...
74,534,956
74,535,009
::tolower using std::transform
Why std::transform doesn't work this way: std::string tmp = "WELCOME"; std::string out = ""; std::transform(tmp.begin(), tmp.end(), out.begin(), ::tolower); out is empty! But this works: std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); I don't want the transformation to happen in-place.
You are writing in out-of-bounds memory, since the range of out is smaller than that of tmp. You can store the result in out by applying std::back_inserter. As user17732522 pointed out, since it's not legal to take the adress of a standard libary function, it's better to pass over a lamda object that calls std::tolower...
74,535,434
74,536,777
ffmpeg set hdr options through av_opt_set
How can I add the following HDR options to a video encoder written in C++, using av_opt_set or similar ? ffmpeg -i GlassBlowingUHD.mp4 -map 0 -c:v libx265 -x265-params hdr-opt=1:repeat-headers=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,1645...
The option name is x265_params, and its value is its arg. av_opt_set(cctx->priv_data, "x265-params", "hdr-opt=1:repeat-headers=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(40000000,50):max-cll=0,0", AV_OPT_SEARCH_CHILDREN);
74,535,578
74,535,845
How to store parameter packed function for later called
I'm building a project with a signal/slot library, and i'd like to be able to execute the slot in a different thread than the signal calling it, like Qt does. To do that, I'm trying to store a function call with parameter pack to allow varying args number : #include <functional> #include <iostream> struct SlotProxy { ...
The problem(error) is that PostEvent is a member function template and when it is used as an argument to std::bind as in &SlotProxy::PostEvent, the type of its template parameter(s) aren't known. This means that we need to either use default arguments or explicitly tell the compiler the type of its template parameters....
74,536,081
74,585,883
Get a vector of map keys without copying?
I have a map of objects where keys are std::string. How can I generate a vector of keys without copying the data? Do I need to change my map to use std::shared_ptr<std::string> as keys instead? Or would you recommend something else? My current code goes like this: MyClass.h class MyClass { private: std::map <std::s...
As suggested by Kevin, std::views::keys was pretty much made for this. The view it produces is a lightweight object, not much more than a pointer to the range argument, which solves the ownership and lifetime issues. Iterating over this view is identical to iterating over the map, the only difference is that the view's...
74,536,489
74,536,521
Can you reuse a std::future once it has already been assigned to std::async()?
I am curious if a std::future is instantiated and used to assign to the value of an std::async() operation, then waited for completion with .wait(), can it be re-assigned to a new async() operation? Take this small code snippet for an example: int fib(int n) { if (n < 3) return 1; else return fib(n-1) + fib(n-2); }...
Yes, it's fine. This is explicitly described in the documentation for operator=: future& operator=( future&& other ) noexcept; Releases any shared state and move-assigns the contents of other to *this. After the assignment, other.valid() == false and this->valid() will yield the same value as other.valid() before the...
74,536,736
74,573,808
Application silently crashes at glfwCreateWindow()
I am making a C++ application using GLFW/GLEW for windowing and graphics: #include <GLEW/glew.h> #include <GLFW/glfw3.h> int main() { // init glfw if (!glfwInit()) { std::cout << "GLFW init failed!: " << std::endl; } // set up window hints glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); ...
Solved. I was building this in Visual Studio under Debug configuration, so it was trying to use the VC++ debug runtime libraries when shared with others. Rebuilding my libraries and application for Release fixed the issue.
74,537,475
74,565,253
SAPI - How to stop all asynchronous speech tasks?
I'm using the Microsoft's Speech Application Programming Interface (SAPI) to enable speech in my app. However, when I try to stop asynchronous speech tasks, they stop, but after a second. In .NET framework, I tried to stop all asynchronous speech tasks, and they stop immediately when I call the SpeechSynthesizer.SpeakA...
Maybe you could construct two ISpAudio interfaces, then switching between them whenever you need to stop speech.