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,178,927
69,179,020
CAN Communication in QT
I have a specific problem with the CAN communication in QT. It is not a problem to send/write CAN messages, but the readFrame() function in QT doesn't load my received frames. If you are implementing a CAN communication in C++ you can use the read() and write() functions. But in QT it is not supported. In general the r...
From the QT docs: Returns the next QCanBusFrame from the queue; otherwise returns an empty QCanBusFrame. The returned frame is removed from the queue. The queue operates according to the FIFO principle. https://doc.qt.io/qt-5.12/qcanbusdevice.html#readFrame Try first calling bool QCanBusDevice::waitForFramesReceived(...
69,179,378
69,179,506
Why use a dynamic array instead of a regular array?
The following code is used to demonstrate how to insert a new value in a dynamic array: #include <iostream> int main() { int* items = new int[5] {1, 2, 3, 4, 5}; // I have 5 items for (int i = 0; i < 5; i++) std::cout << items[i] << std::endl; // oh, I found a new item. I'm going to add it to my ...
You are right, the example you are looking at isn't very good at demonstrating the need for dynamic arrays, but what if instead of going from size 5->6, we had no idea how many items we found until we need to add until the code is actually running? Regular arrays need to be constructed with their size known at compile ...
69,179,467
69,179,855
What does "semantics" mean? and why are "move semantics" named as such, instead of any other term?
In Cpp, the "move semantics" of an object refers to the concept that "move but not copy the object to a newer", but the word "semantics" really confuse me. What is the difference between the "semantics" and "function"? How to use this word correctly? If I realize a method called "max(A,B)", could we say "I realize a ma...
"Semantics" is the meaning or interpretation of written instructions. It is often contrasted to "syntax", which describes the form of the instructions. For example, an assignment foo = bar has the same form in many programming languages, but not necessarily the same meaning. In C++ it means copy, in Rust it means move,...
69,180,773
69,183,872
Specify callback function in enet
The ENet library has packets that can be send, and includes a callback function once it has finished sending that specific packet. http://enet.bespin.org/structENetPacket.html#ad602d6b6b35ef88b2b2e080fa5c9dc3d typedef struct _ENetPacket { size_t referenceCount; /**< internal use only */ enet_ui...
Okay, this is pretty common. First, you can't call a non-static member method this way, not directly. Pain in the ass. But that callback structure has a userData field. And that's what we're going to use. void send(T* data, int32_t length) { ENetPacket* packet = enet_packet_create(data, length, ENET_PACKET_FLAG_R...
69,181,509
69,183,937
Calculating Accumulated Value with C++
I'm asked to write a program that reads in an investment amount, annual interest rate, and a number of years, and displays the future investment value using the following formula. futureInvestmentValue = investmentAmount x (1 + monthlyInterestRate)(numberOfYears X 12) assuming that monthlyInterestRate = annualInterestR...
Let me answer for various use-cases of your question. Answer with a whole number of years You actually do not need the monthly interest rate at all, as accumulatedValue = investmentAmount × (1.0 + 0.01*annualInterestRate)numberOfYears Here, annualInterestRate is multiplied by 0.01, as you asked the user for a percentag...
69,182,016
69,182,295
Returning std::unique_ptr to abstract type with custom deleter from a memory pool
Assume I have a templated MemoryPool class a function create(...) (which returns a pointer to a newly allocated object of type T) and a function destroy(T*) (which destroys and returns the memory back to the pool). I would like to create a std::unique_ptr that "owns" the pointer created by the pool and returns the poin...
The code doesn't compile because std::unique_ptr<ITest> is used by ITestOwner while you to forward it std::unique_ptr<Test, std::function<void(Test*)>>. It obviously doesn't compile because std::unique_ptr<ITest> calls delete on ITest instead of calling some complex arbitrary function. You'd need to use unique_ptr<ITes...
69,182,146
69,184,849
Multi-track audio playback C++ / PortAudio
I am working on a synthesizer/live-coding application where I want to have multiple instances of the engine generate different sounds with different sequences. (aside: I have the synth engine working with MIDI input). Let's say the user input to the console may look something like this: track:1,sound:pad,seq:[70, sleep...
Convert your input data to the same representation as MIDI: event type, track, parameters, time. Then sort the two tracks together by time, and process all the events: grab next event, sleep until the time that event is supposed to happen, repeat. This is really what MIDI is. A scheduled event representation. In MIDI...
69,182,612
69,183,765
Storing a vector of vectors of type int in a Redis cache
I'm using the redis-plus-plus C++ redis client to store data in a redis cache and I would like to know how to store an std::vector<std::vector<int>> object. From the provided examples in the git repository there isn't a similar example. If there is another C++ client that can simplify the storage and retrieval of such ...
There are a few ways. You could serialize this and store a big string. You could use lists. For the double-nesting thing, you'd have to get clever with the keys. What I would do would depend on how I have to access it. But you'll have to code it yourself, somehow.
69,183,044
69,183,099
issue in intialising character array from the structure through an array object
i am getting an issue while initialising the character array in the structure through the structure object #include <iostream> #include <string.h> using namespace std; struct emp { int age; char name[10]; }; int main() { struct emp v[2]; List item ...
For starters there is at least a typo v[0].name[] = "name1"; <-this is where i am getting error ^^^^ v[1].name[]= "name2"; <-this is where i am getting error ^^^^ Arrays do not have the assignment operator. So these assignment statements v[0].name[] = "name1"; v[1].name[]= "name2"; a...
69,183,440
69,183,841
Anonymous implementation of interface in C++
Does C++ support anonymous implementation of interface like Java? Something similar like in following code: Runnable myRunnable = new Runnable(){ public void run(){ System.out.println("Runnable running"); } }
You can get pretty close by creating an instance of an anonymous class that inherits from your defined interface. Example: #include <iostream> struct Runnable { virtual ~Runnable() = default; virtual void operator()() = 0; }; int main() { struct : Runnable { // anonymous implementation of inte...
69,183,632
69,183,703
How can you partially fill an array in C++
I'm working on trying to partially fill an array, however when running, the program continues to run past the limit that was given by the user. Is there another way to partially fill an array? The initial NUM_ROWS and NUM_COLUMNS constants are placeholders until the program work #include <iostream> // Input and output ...
This is your problematic line: for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING And it also demonstrates why single-letter variable names lead to bugs. You cut and pasted this from the previous for-loop, and you didn't change every instance of variable i.
69,184,012
69,184,093
Overload std::unique_ptr deleter method using std::enable_if
I am trying to write a deleter for my std::unique_ptr, and I would like to overload the method for deletion. Here is what I tried, but the compiler complains about the use of std::enable_if_t. Code is compiled using -std=c++20 flag. template <class T> class custom_deleter { public: template <class U, std::enable_if...
SFINAE required a template parameter of the function to be depended on. That means the std::enable_if_t can only be applied for the U not for the class template T. Therefore, you need to include the template parameter T in your operator()s somehow (like class U = T) or just if constexpr the operator() as you are anyw...
69,184,482
69,184,533
C++ How to Save Elements in a Vector from a Function
Consider the following code. In list1 I'm adding elements saved on the heap to a vector and printing. It works as expected. In list2 I'm adding elements onto the vector from a function which also allocates elements on the heap. I understand I have to allocate Node on the heap in addNode as otherwise it would be dealloc...
In addNode(), you are passing the vector by value, thus a copy of the caller's vector is made, and then you are adding the Node* to the copy, the original vector is unaffected. You need to pass the vector by reference instead: Node* addNode(vector<Node*> &list) Same with printVector(). You are passing the vector by va...
69,184,772
69,184,949
_alloca and std::vector of const char*
I did several searches on the _alloca function and it is generally not recommended. I will have a dynamically updated array of strings on which I will have to iterate often. I would like to have each string allocated on the stack to reduce the miss caches as much as possible. Using _alloca I could create a char* on the...
Stack memory allocated by _alloca gets automatically released when the function that calls _alloca returns. The fact that a pointer to it gets shoved someplace (specifically some vector) does not prevent this memory from being released (as you mentioned you assumed would happen, in the comments), that's not how C++ wor...
69,184,830
69,184,996
Is a requires expression an atom when normalizing constraints?
I want to make sure I properly understand the constraint normalization process since cppreference is slightly fuzzy on this topic. It seems that during the normalization, anything that is inside of a requires expression is always considered an atom, no matter how specific/complex. This seems to be supported by the diff...
Yes your understanding is correct. For subsumption (what you denote by <) to occur, there has to be a certain relationship between the normal forms of the constraint expression. And if one examines the constraint normalization process: [temp.constr.normal] 1 The normal form of an expression E is a constraint that is d...
69,184,977
69,185,176
"invalid operands to binary expression" in simple class using memory and addresses
#include <iostream> using namespace std; class Animal { public: string eat() { return "I can Eat"; } string sleep() { return "I can sleep"; } void showData(int *weight, int *age) { cout << "The weight is " << weight << " and the age is " << age << endl...
showData() returns void, ie nothing. So there is nothing to pass to operator<<, hence the error. Simply change cout << an.showData(...) to an.showData(...), since showData() does its own cout statements internally. If you want cout << an.showData(...) to actually display something, then showData() needs to return some...
69,185,315
69,198,495
How to install c++ program into conda environment from source
I would like to compile and then use the scientific project BASS, which is distributed as c++ source code on github. I've set up a conda environment bass to hold everything related to BASS, and I'd like to compile BASS into this environment (so that if I delete the environment, it's cleanly removed). I don't know if I ...
Here's a very basic Conda recipe for the package. Make a folder (say recipe) and put the following two files in it: meta.yaml package: name: bass version: 0.1 # this is totally arbitrary (there are no versions) source: git_url: https://github.com/judyboon/BASS.git requirements: build: - {{ compiler('cxx'...
69,185,463
69,199,226
How do I get cppyy to find additional headers?
I have a directory structure: include/foo/bar/header1.h include/foo/bar/header2.h header1.h includes header2.h. However, when I attempt this: import cppyy cppyy.add_include_path('include') cppyy.include('foo/bar/header1.h') I get the error: ImportError: Failed to load header file "foo/bar/header1.h" In file included...
Notwithstanding the conclusion in the comments above, the following is for future reference to aid debugging in case someone stumbles on this question with the same problem. To print the full set of include directories as seen by Cling, do: import cppyy print(cppyy.gbl.gInterpreter.GetIncludePath()) It will show as a ...
69,185,735
69,190,195
Why do we need to check the return value of malloc in C, but not new in C++?
There is a thing that I don't understand in C++. To contrast, in C when we call malloc we check if the allocation failed to then free all the previously allocated memory so as to make a clean exit without memory leaks. But in C++ no one seems to care about that with the new operator. I know that it throws std::bad_allo...
But in C++ no one seems to care about that with the new operator. I know that it throws std::bad_alloc on failure, but if there were previous successful allocations with new we are left with memory leaks upon a thrown exception, aren't we? Only if you're writing very bad C++, in which case you should stop that. This,...
69,185,909
69,239,894
EasyHook stop catching some messages
As soon EasyHook EasyHook64.dll intercepts the first DefWindowProcW message, and from it starts a thread, it does not catch any DefWindowProcW anymore: |___ DefWindowProcW (caught) |-- |-- |-- |-- DefWindowProcW (don't 'intercept' anymore) |-- ... It stops 'catching' all DefWindowProcW messa...
There is no elegant solution for this in EasyHook, however if you are happy to install as many intermediate hooks as you need for the nesting levels you can chain them together. The outermost hook will be the only one enabled initially. It will first ensure all innermost hooks are disabled, then enable the next hook. T...
69,186,023
69,200,905
Clion `cout` and `cin` combination causes console to not work properly
I've recently started trying out CLion for C++ programming. I wanted to test a sample application (below): #include <iostream> int main() { std::cout << "Please enter a number: "; int x; std::cin >> x; std::cout << "Your number was " << x << "!\n"; return 0; } This is what I was expecting (the nu...
After some more searching, I came across this StackOverflow post, which led me to this issue (upvote it!) which finally led me to do what was told in the comments: Two workarounds are available: Turn off PTY: by disabling run.processes.with.pty option in the Registry (Help -> Find Action -> Registry...) Use Cygwin64 ...
69,186,171
69,188,285
Get all N consecutive characters in string using stringstream in C++
I would like something that can window a std::string object into partitions of length N - for example (using a function update): int main() { std::string s = "abcdefg"; update<2>(s); return 0; } Calling the above should result in: ab bc cd ef fg I have the following version of the update function: template<std:...
With C++17 you can do it like this, which is way more readable: void update(std::string_view s, int size) { const int iterations = s.size() - size; for (int i = 0; i <= iterations; i++) { std::cout << s.substr(i, size) << "\n"; } } string_view is made exactly for this purpose, for fast read access ...
69,186,185
69,186,229
Issue with variadic template template parameter pack
Consider the following example: template< class A, int B, class C> struct Obj { A a_obj; static constexpr int b_value = B; C c_obj; }; template< template<class... > class ... Templates > struct Foo; template<> struct Foo<Obj> { Obj<void*, 5, float> obj; }; int main() { Foo<Obj> foo; }; This is failing on me (g...
int B is a non-type template parameter. You have to declare Templates as template<class, auto, class> class if you want it to work with that particular class template, or redefine Obj to take a std::integral_constant to pass a value encapsulated in a type: template<class A, class B, class C> struct Obj { A a_obj; ...
69,186,440
69,188,796
Using a signal listener thread - how do I stop it?
A snippet from my main method: std::atomic_bool runflag; // ... std::thread signaller([&]() mutable { while (runflag) { int sig; int rcode = sigwait(&set, &sig); if (rcode == 0) { switch (sig) { case SIGINT: { // handle ^C } } } } }...
You can use the sigtimedwait() function, which returns after a timeout given as a parameter. You will need to check the return value from sigtimedwait() to check if it finished because of timeout or the signal arrived and then depending on this value you will need to handle signal or just check runflag and run again si...
69,186,560
69,187,368
Mergesort not working as intended with linked list
Preface: I do not care about the viability of my particular merge sort algorithm. That is not what the question is about. I am curious as to why the program I have already written behaves the way it does, not about why I should use the STL or whatever. This is for learning purposes. Question: I have a linked list struc...
A few issues: merge returns the last node of merged list instead of the first. So change: return tmp; to: return head->next; In msort the return value of the recursive call is ignored, but it is important, as it represents the first node after the sort operation. So change: msort(left); msort(right); to: left = ms...
69,186,891
69,186,939
Why does std::regex_match generate different results
I'm trying to use std::regex to validate some variables from a file in my c++11 project. For now I need to validate if a string is a valid URL or not. Here is my code: https://godbolt.org/z/4Pn9eYEce As you see, it works as expected. It returns a true. However, when I run the same code on my server, it returns a false....
Must be a compiler thing, compiling on gcc5.4 with -Wformat -std=c++17, and then running it also returns 0. https://godbolt.org/z/a8o9x9nWP Probably best if you update your compiler to a newer version.
69,187,604
69,187,727
C++ Nesting SFINAE Template Produces Compilation Error
I'm trying to create an addition operator for a custom template class, where the first argument is allowed to be either an instance of my class or a basic numeric type. My operator has a definition similar to the example code below: #include <type_traits> template<typename T> struct MyTemplateStruct { T val; }; ...
You need to make MyCommonTypeT<T, U> (i.e. MyCommonType<T, U>::type) itself invalid, it's not enough that std::common_type_t<T, U> is invalid when declaring type in MyCommonType. For example you can specialize MyCommonType, when MyTemplateStruct is specified as template argument, type is not declared. template<typename...
69,188,266
69,188,715
Cumulative product of an array: std::accumulate vs loop
Let's say I want to compute the cumulative product of the first k elements of an array. int arr[8] = {3, 5, 7, 4, 8, 9, 1, 2}; int k = 3; Which one is the best option in terms of performance? Option 1. Ordinary for loop int result = 1; for (size_t i = 0; i < k; ++i) { result *= arr[i]; } Option 2. Accumulate resu...
Both approaches are fine; neither is bad. The choice between them is matter of opinion. The latter is hardly "fancy C++11", since the only meaningful C++11 feature used is the lambda which can be replaced with std::multiplies or in general case with a function object in "fancy C++98". (Yes std::begin was added in C++11...
69,188,984
69,189,158
How to change value of array using pointer?
I am making a program which asks user for input and then separates it from comma and adds all separated values to an array. But as you can see, when I print the first value of the array, it doesnt print anything. Im a beginner. #include <iostream> #include <string> #include "Header.h" #include "Windows.h" #include <arr...
On this part you should use another int value to set your pointer values : else { (*ptr)[i] = value; value = ""; } This should work for you like this : std::string value; int length = input.length(); int j = 0; for (int i = 0; i < length; i++) { if (input[i] != ',') { value += input[i];...
69,189,157
69,189,206
PX4 Multi-Vehicle Simulation with Gazebo : What is No ROS?
https://docs.px4.io/master/en/simulation/multi_vehicle_simulation_gazebo.html What is the meaning of No ROS in that link and what is the difference between No ROS and simulation with ROS?
The text at the very top of the page explains that they use different commands depending on whether you are using ROS or not. A different approach is used for simulation with and without ROS. There is a separate section further down about how to do the same thing with ROS.
69,190,349
69,190,668
Pass data from object in class A to class B
New to classes and objects in c++ and trying to learn a few basics I have the class TStudent in which the Name, Surname and Age of student are stored, also I have the constructor which is accessed in main and inserts in the data. What I want to do is: having the class TRegistru, I have to add my objects data in it, in ...
Hence the question is about passing data from A to B, I will not comment on the file handling portion. This can be done in multiple ways, but here is one of the simplest and most generic. By calling TRegistru::toString() you serialize every TStudent added to TRegistru into a single string which then can be easily writt...
69,190,364
69,190,542
Looping back near the beggining using std::vector iterators
I have an iterator that needs to loop near the beginning of the vector whenever it reaches its end, for the amount it went over the end, like so: std::vector<int> vec = {...}, vec1; std::vector<int>::iterator it = vec.begin(); for(;vec.size() != 0;){ it += k; //k is a const integer if(it >= vec.end()){ it -= items.en...
XY-solution: I recommend keeping an index instead of an iterator and use the remainder operator. for(std::size_t i = 0; vec.size() != 0;){ i = (i + k) % vec.size(); vec1.push_back(vec[i]); vec.erase(vec.begin() + i); } So perhaps I increment vec{1,2,3,4,5} by 3, it should first remove 3 This doesn't matc...
69,190,488
69,192,221
IContextMenu::QueryContextMenu not called by Shell (Win10)
I have a class called ValidatorContextMenuHandler that implements the IShellExtInit and IContextMenu interfaces. My DLL is being referenced in the Registry, and gets loaded into Windows Explorer correctly. I check this by creating MessageBoxes whenever a method is being called. When I right click on a file, I also get ...
I found out why it wasn't working. A lot of frustration for nothing. In my ValidatorContextMenuHandler.cpp file, I did a simple mistake. When queried for the IContextMenu interface, I accidentally cast this to IClassFactory when I should cast it to IContextMenu. Mistyped it. Before: else if (IsEqualIID(riid, IID_IConte...
69,190,783
69,193,688
Pass templated parameter pack to callback function (also a templated function)
Currently in my code I have a function, that takes various arguments, and a callback object (which is instance of a simple class with a Callback(void) function). This works perfectly fine now, but it clutters code because I have quite a few of these classes, and in most of them their variables are used only by the Call...
template <typename... TArgs> bool Function(CallbackFuncType<TArgs...> Callback, TArgs&&... Args) Have several issues, the main one is that TArgs should be deduced exactly identically in both place. Issue with template <typename... TArgs> using CallbackFuncType = bool(T& Data, TArgs&&... Args); is that it can only mat...
69,191,069
69,191,115
How can I initialize an array in C++ with a size that is given to the constructor?
I have a C++ class with a member that is supposed to be a two dimensional array. I want to declare my array as a member in the header file of the class. Then in the constructor of my class I want to initialize my array with a size (given to the constructor) and fill it with zeros. I have a working example of what I wan...
std::vector is the best match here. (As you said, in most cases raw arrays and pointers could be avoided. Also see How can I efficiently select a Standard Library container in C++11?) And you can initialize the data member directly in member initializer list instead of assigning in the constructor body after default-in...
69,191,363
69,193,867
32-bit malloc() return NULL when opening many threads?
I have a sample C++ program as below: #include <windows.h> #include <stdio.h> int main(int argc, char* argv[]) { void * pointerArr[20000]; int i = 0, j; for (i = 0; i < 20000; i++) { void * pointer = malloc(131125); if (pointer == NULL) { printf("i = %d, out of memory!\...
As noted in a comment by @macroland, the main thing happening here is that each thread is consuming 1 MiB for its stack (see MSDN CreateThread and Thread Stack Size). You say malloc returns NULL once the total you have directly allocated reaches 200 MB. Since you are allocating 131125 bytes at a time, that is 200 MB ...
69,191,499
69,191,786
Is possible to get type a child class type from base class?
I need something like this: template <typename T> class A { public: T commonData; TYPEOF_CHILD_CLASS *test(T data) { return new CHILD_CLASS(data); } }; template <typename T> class B : public A<T> { public: T bdata; B(T data) { bdata = data; } }; template <typename T> cl...
Thanks @Some programmer dude @463035818_is_not_a_number. In according to this link it works. template <class T, typename TT> class A { public: TT commonData; T *test(TT data) { return new T(data); } }; template <typename T> class B : public A<B<T>, T> { public: T bdata; B(T data) { ...
69,191,540
69,191,987
Scope rules of `for` loop different in C++ than in C?
I noticed that the scope rules of the for loop are different for C and C++. For example, the code below is legal in the C compiler, but not legal in the C++ compiler. for (int i = 0; i < 10; ++i) { int i = 5; } The above code is valid in C, but gives a redefinition error in C++. My guess is that the C compiler tre...
As far as standards go, for loop scopes are indeed defined differently in C and in C++. In C they are defined as follows: 6.8.5.3 The for statement The statement for ( clause-1 ; expression-2 ; expression-3 ) statement behaves as follows: ... with no specific reference given to limitations on variable declarations in...
69,192,537
69,194,649
{fmt}: Will a named argument be ignored if it doesn't exist in the formatting string?
The following code compiles just fine and produces the string "abc": fmt::format("abc", fmt::arg("x", 42)); godbolt So it looks like named arguments that are missing in the format string are just ignored. My question is: Is that by design or is it a bug? I'm asking because I'm having a use case for this "feature". So ...
This is by design. Unused formatting arguments are essentially the same as unused arguments to any other function and are not an error. This is the case in {fmt} and Python's str.format it is modeled after as well as printf.
69,192,689
69,194,429
Execution time overhead at index 2^21
What do I want to do? I have written a program which reads data from binary files and does calculation based on the read values. Execution time is most import for this program. To validate that my program is operating within the specified time limits, I tried to log all the calculations by storing them inside a std::ve...
I was able to solve my problem by reserving memory by using std::vector::reserve() before the time critical part of my program. Thanks to all the comments. Here the working code I used: std::vector<std::string> myLogVector; myLogVector.reserve(12000000); //...do time critical stuff, without reallocating storage
69,193,300
69,389,108
How much memory(MB) can the vector variable occupy in enclave of Intel sgx?
I want to immigrate PageRank algorithm in the sgx enclave. The algorithm uses vector to save the edge relationship and matrix. vector<size_t> num_outgoing; // number of outgoing links per column vector< vector<size_t> > rows; // the rowns of the hyperlink matrix map<string, size_t> nodes_to_idx; // mapping from string ...
All seems like you are running out of memory. The memory limits (stack and heap) are set in the config file using StackMaxSize and HeapMaxSize (see Developer Reference for details). The size of the EPC (128MB or 256MB) has nothing to do with it. Here, you are not bounded by the EPC size but by the heap and stack. Incre...
69,193,308
69,193,741
Storing virual functions in Array/Vector container
I have a base class with common behavior and derived classes with override virtual functions. But if tried to save the function pointer as std::vector I will get the error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. I need s...
You get a "pointer" to a member with the syntax &Class::Member (Class::Member is the "qualified" name of the member). These are pointers only in an abstract sense, and need to be dereferenced relative to an object. You do this with the ->* or .* operator, depending on whether the left-hand side is a pointer or not. Not...
69,193,405
69,193,874
How to find the greatest number among the numbers given input?
I'm a beginner in programming and as you can see, I created a program where the user is asked to input three numbers. It will display the greatest among the numbers given. But after I finished the code, a question came into my mind, what if the user was asked to input a hundreds of numbers and should display the greate...
With the program below, you can get as many numbers as you want from the user and find the largest of them. #include <iostream> int main() { int size=0, largestValue=0, value=0; std::cout << "Enter total numbers you want to add :" << "\n"; std::cin >> size; for (i...
69,193,573
69,265,126
Not receiving data in LCP(PPPoS) phase over UART(ESP-32 -> Sim7600)
On my ESP32 I am having trouble creating a working PPP interface to my ISP. I am using an ESP-32 Ethernet kit and have it hooked up to a Simcom EVB Kit with a Sim7600G chip. With this hardware I am using ESP-IDF in combination with LWIP to get the PPP connection going. At first I have to send all the corresponding AT c...
I have not found the solution to this problem with the mentioned frameworks. Instead I reverted to another dependency from the ESP-IDF: esp-modem. I managed to get a working solution by following the pppos-client and modem-console examples within my current software.
69,193,728
69,194,610
Get Name List of all running processes windows
I want to get list of all running processes like following example.exe example2.exe so on... heres code what ive tried WCHAR* GetAllRunningProccess() { PROCESSENTRY32 pe32; HANDLE snap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); pe32.dwSize = sizeof(PROCESSENTRY32); Process32Firs...
The code you have written does not work like a generator function to yield multiple values. It just exits when returning the first value. You cannot return from a function more than once. do { return ...; // This will both exit the loop and exit the function. } while(...); Although, coroutines offer co_yield to a...
69,193,825
69,193,929
how delete class variable in struct?
InitMyObject(MyObject* ptr) { *ptr = MyObject(); } struct Data { MyObject obj; }; extern Data data; // ... InitMyObject(&data.obj); delete &data.obj; // ? is this ok How I can delete (call deconstructor) data.obj, I also try Data::obj as pointer (nullptr default) then pass the pointer but crashed on Ini...
How I can delete (call deconstructor) data.obj The destructor of data will destroy its subobjects. Since data has static storage, it is automatically destroyed at the end of the program. delete &data.obj; // ? is this ok No. You may only delete the result of a non-placement new expression. You may not delete a poi...
69,194,075
69,194,245
Structural tuple-like / Wrapping a variadic set of template parameters values in a struct
I find myself wanting/needing to use a variadic composite type as a template parameter. Unfortunately, std::tuple<> is not a structural type, which makes the obvious approach a no-go: #include <tuple> template<typename... Ts> struct composite { std::tuple<Ts...> operands; }; template<auto v> void foo() {} int main...
Create your own structural tuple-like class? Something like: template <std::size_t I, typename T> struct tuple_leaf { T data; }; template <typename T> struct tag{ using type = T; }; template <typename Seq, typename...> struct tuple_impl; template <std::size_t... Is, typename... Ts> struct tuple_impl<std::ind...
69,194,230
69,194,881
What is the purpose of `operator auto() = delete` in C++?
A class in C++ can define one or several conversion operators. Some of them can be with auto-deduction of resulting type: operator auto. And all compilers allow the programmer to mark any operator as deleted, and operator auto as well. For concrete type the deletion means that an attempt to call such conversion will r...
But what could be the purpose of operator auto() = delete? What would be the purpose of the following function? auto f() = delete; As per the grammar functions, [dcl.fct.def.general]/1, the function-body of a function-definition may be = delete; e.g., it is syntactically valid to define a function as deleted. C++14 ...
69,194,439
69,194,666
Why does this merge sort code keeps giving me this weird output?
I wrote the count sort code but it is showing me weird output, can you tell where I am wrong ?? #include <bits/stdc++.h> using namespace std; void CountSort(int a[], int n, int k) { int count[k + 1]={0}; int b[n]; for (int i = 0; i < n; i++) { ++count[a[i]]; } for (int i = 1; i <= k; i...
Your code have two fault. print array method is wrong. third loop is wrong in CountSort. this loop working only once. There is fix result. void CountSort(int a[], int n, int k) { int count[k + 1]={0}; int b[n]; for (int i = 0; i < n; i++) { ++count[a[i]]; } for (int i = 1; i <= k; i++...
69,194,553
69,194,598
Differences between compare and == for std::string
I am getting different results when using == or std::string::compare between two strings. This is the code I am executing. #include <iostream> #include <string> int main() { std::string str1 = "W"; char tmpChar = 'W'; std::string str2(1, tmpChar); bool equalCompare = str1.compare(str2); bool e...
Differences between compare and == for std::string The difference is in what they return. == returns true when the strings compare equal and false otherwise. compare returns negative integer when *this is before the argument, zero when strings are equal, and positive integer when the argument is before *this.
69,194,685
69,195,109
c++ program crashing after reading a file the second time
Basically, the problem is already described in the title: When starting the program first time ( meaning that the new file is created then ), it works perfectly and it doesn't crash, but when trying a second time ( meaning that the file already is there ), it crashes. Question is: Why does it crash and how do I prevent...
After reading a second time your code I realised that the way you try to read and write a vector was plain wrong: vector <TStudent> students; ... ifstream file2; file2.open(file_name, ios::in); file2.seekg(0); file2.read((char*)&students, sizeof(students)); // WRONG!!! A vector does store its data in a...
69,194,690
69,195,699
Compare named requirement expressed with C++20 concepts
I am writing a sorting algorithm, that takes a comparison function, similar to std::sort: template <class RandomIt, class Compare> void sort(RandomIt first, RandomIt last, Compare comp); It seems to me that the template parameter Compare perfectly matches the Compare named requirement. I am trying to understand how to...
In C++, named requirements are wider in capabilities than concepts and constraints. For example, I can have a named requirement that some algorithms halts. On the other hand, there is no way to make a concept that requires an algorithm halts. Concepts can check some things, but they cannot check everything. So the na...
69,194,777
69,195,146
C++ Swapping pointers - can't reproduce auto type by defining type explicity
Doing exercise 6.22 in C++ Primer, a function swapping two pointers: void swap(int*& a, int*& b) { auto temp = a; a = b; b = temp; } int main() { int a = 15; int b = 4; int* p1 = &a; int* p2 = &b; cout << "p1 address: " << p1 << "; p1 value: " << *p1 << "\np2 address: " << p2 << "; p2 v...
As mentioned in the comments, temp is of type int*, not int*&. If you want it to be a reference to a pointer, you can declare the type explicitly or use auto&. However, what you really want is int* anyway. Think about how you would write this if you were swapping two ints instead: void swap(int& a, int& b) { int te...
69,195,122
69,195,443
Qt Application exits with 0 when QMainWindow is minimized
This Qt project https://github.com/AmonRaNet/QGeoView exits when the main window is minimized ??!!?? Can someone give me an explanation please, I never saw that in my life with Qt. I'm using Windows 10 and I'm using the last version of Visual Studio 2019 C++ compiler. I have also used different Qt versions (the last ve...
From mainwindow.cpp: void MainWindow::hideEvent(QHideEvent* /*event*/) { QApplication::quit(); }
69,195,269
69,196,719
Template metaprogramming recursive evaluation
template<typename T> struct rm_const_volatile { using type = T; }; // Call this (partial)specialization as "1" template<typename T> struct rm_const_volatile<const T> { // remove topmost const and recurse on T using type = typename rm_const_volatile<T>::type; }; // Call this (partial)specialization as "2" ...
I would like to know why the compiler reports template instantiation as ambiguous C++ considers const volatile int and volatile const int to be the same type. They are interchangable and mean the same thing. Some other ways to spell this one type: int const volatile int volatile const const int volatile volatile in...
69,195,593
69,228,948
Would compiler optimization remove try/catch block if catch does nothing?
I am working with code that has a lot of try catch blocks in but most cases the catch blocks do nothing. As in the code below fib function is throwing invalid_argument exception. The function call in main is in the try block but the catch block does not do anything, except catching the exception. I am wondering if the ...
I am wondering if the compiler might trim away this kind of exception handling during code optimization, or not? TL;DR: No, a compiler cannot and must not optimize away such exception handling. As mentioned in the comments, an empty catch block is not the same as not having try ... catch blocks. In your example, alt...
69,195,929
69,200,969
What will happens to a local pointer if thread is terminated?
what happens to data created in local scope of thread if thread is terminated, memory leak? void MyThread() { auto* ptr = new int[10]; while (true) { // stuff } // thread is interrupted before this delete delete[] ptr; }
Okay, my perspective. If the program exits, the threads exit wherever they are. They don't clean up. But in this case you don't care. You might care if it's an open file and you want it flushed. However, I prefer a way to tell my threads to exit cleanly. This isn't perfect, but instead of while (true) you can do while ...
69,195,933
69,196,640
error: passing 'const S' as 'this' argument discards qualifiers
Here is an simplified version of the problem from ported from large code base. I've solved the issue, but I don't like the way I solved it. The problematic code that doesn't compile is this I'm starting with: #include <iostream> #include <cstdlib> #include <vector> #include <cassert> #include <algorithm> #include <cmat...
Elements of a std::set<T> are unmodifiable - set_of_S.begin() returns a constant iterator: cppreference Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member func...
69,196,221
69,199,146
"This library now requires a C++11 or later compiler..." when compiling 'number_base.hpp' of boost library
I have a c++ project using boost 1.77.0 library. The compiler is g++ 4.8.5, and as I know it supports the c++11 standard. The following command is used to compile the project: g++ -std=c++11 main.cpp Logger.cpp MOCMesh.cpp Mesh.cpp CFDMesh.cpp Solver.cpp -o main -I../tools -I/usr/code/include -I. -L/usr/code/lib -lgmp ...
Use an older version of boost from that time period
69,196,433
69,196,868
C++ program for Gauss Jordan elimination returning a very small value but not 0
I made a program to solve linear equations using Gauss Jordan elimination method. The program is working correctly but in some cases instead of giving the answer as 0, it returns a very small value. #include<iostream> #include<iomanip> #include<cassert> #define N 10 using namespace std; //printing out the array void p...
The value 2.3842e-08 should be a zero. Is it because of the precision of the floating point in C++ ? Yes, it is. If so, what should I do in order to round such low values to 0 without loss of data ? You can use an epsilon value to decide whether a float value is considered to be 0: const float epsilon = 0.000001; /...
69,196,563
69,196,777
How to find largest and smallest value from a file using loop
I am running into this issue where I want the largest and smallest value of id from a file that I am reading. This file contains other information as well. I am successfully able to identify the largest value but the smallest is just being set to the last value that gets read, which is not the smallest in the file. Her...
You don't check for error states. What about the situation were there are no values in the file. Or only one value in the file. You make assumptions about the size of largest and smallest values by using magic numbers. if (theFile >> firstName >> lastName >> id) { // You have at least one value it is the largest an...
69,196,888
69,197,911
Accessing the same folder from different cpp files relative to the Project folder
If my project has the following folder structure: Project ├───build ├───images ├───include ├───Apps ├───Models ├───source └───tests what is the best way to make the folder "images" accessable to all .cpp files inside build, tests, apps and src without using the absolute path. So every image created inside this project...
If I am understanding your question correctly you want to access the images from the "images" folder, right? You should be thinking about the path from the point of the final executable and not the source files. If the executable will be in the build directory then you simply need to write "../images", the 2 dots mean ...
69,197,072
69,197,231
WINAPI GetRawInputData gives an error because of wrong parameters
GetRawInputData() returns -1 (error) and GetLastError() returns 87 which is "The parameter is incorrect.", the first call to the function to get the data size succeeds but the second one, where I try to actually get the data, fails. UINT DataSize; if (GetRawInputData((HRAWINPUT)Message.lParam, RID_INPUT, NULL, &DataSiz...
As @dialer mentioned in a comment, the closing parenthesis are wrong in your 2nd call to GetRawInputData(): if (GetRawInputData(..., sizeof(RAWINPUTHEADER) == -1)) You are comparing the result of sizeof() to -1, and then passing the result of that comparison (0 or 1) to the cbSizeHeader parameter (and then checking wh...
69,197,173
69,197,289
confused about max size of std::vector
I ran into an issue in my code with std::vector, giving me: vector<T> too long. I'm using a vector of char in this case. The code is treating 3D (tomography) images, so I have a lot of voxels. I have exactly the same issue on windows using the VS compiler as on Mac using CLANG, not tested gcc yet. To inspect the issue,...
Why is the max value so small? it looks like the max of an uint32. That is to be expected on 32 bit systems. I was expecting it to be more in the range of size_t, which should be 18446744073709551615, right? If PTRDIFF_MAX is 4294967295, then I find it surprising that SIZE_MAX would be as much as 184467440737095516...
69,197,246
69,199,709
Initializing smart pointers in a tuple without knowing the type
I have a tuple of smart pointers (as a member of a class template) that I need to initialize. I use std::apply to iterate over tuples elsewhere, but how do I initialize them with new objects without knowing their type? Running the code below with a debugger tells me the elements in the tuple are still "empty" afterward...
As noted in the comments, you can apply decltype to ptr to get the type of the unique_ptr, then apply element_type to it: std::apply([](auto &... ptr) { ((ptr = std::make_unique<typename std::remove_reference_t<decltype(ptr)>::element_type>()), ...); }, my_tuple ); (I've replaced new with make_unique, and moved .....
69,197,293
69,200,568
Is it really possible to separate storage allocation from object initialization?
From [basic.life/1]: The lifetime of an object or reference is a runtime property of the object or reference. A variable is said to have vacuous initialization if it is default-initialized and, if it is of class type or a (possibly multi-dimensional) array thereof, that class type has a trivial default constructor. Th...
If that is so, is it really possible to separate storage allocation from object initialization? Yes: void *ptr = malloc(sizeof(int)); ptr points to allocated storage, but no objects live in that storage (C++20 says that some objects may be there, but nevermind that now). Objects won't exist unless we create some the...
69,197,306
69,198,259
Sending a file via multipart using libcurl in C++
I am trying to upload a file via a POST request to a remote location using libcurl and C++. However, I think I am doing something wrong because I am told that the file doesn't arrive on the other side. I am using the following code: #include "curl/curl.h" using namespace std; size_t WriteCallback(void * buffer, size_...
DO NOT add a Content-Disposition request header to the headerlist of the HTTP request, it does not belong there. It belongs inside each MIME part instead (ie, you should be using CURLFORM_COPYNAME, "file" and CURLFORM_FILE, ImageName.c_str()). I would expect curl_formadd() to handle the Content-Disposition for you, you...
69,198,007
69,198,042
What are the options for safely modifying and reading a boolean across multiple threads and cpus?
I have some C++ code that contains roughly this logic: class wrapper_info { public: bool isConnected(); void connectedHandler(); void disconnectedHandler(); protected: bool _connected; } void wrapper_info::connectedHandler() { _connected = true; } void wrapper_info::disconnecte...
What potential issues could actually arise from separate threads polling and modifying the value of _connected? It's Undefined Behavior, no matter what. What options are there to prevent these? A common solution is to use std::atomic<bool> instead of bool. There are fancier (and much more complex) ways to ensure sy...
69,198,166
69,199,810
How do I fill an array in c++ using a class?
This is a part of my assignment that I was given in my college CSCI course using C++ Create a class Array, representing an arran of size n, with the private properties: class Array {private: double * a {}; int n; Constructor by default Constructor by specifying the size of the array Constructor by specifying the size ...
You are calling the wrong constructor you need to call this one: MyArray(int size, double def_val) not this: MyArray(int size); like this: int main(){ MyArray a(5,5); a.display(); } you will get the output as 0,1,2,3,4 But I don't think this is what the assignment wants you to do As you said it should "Const...
69,198,680
69,198,951
How can I pass variables from Python back to C++?
I have 2 files - a .cpp file and a .py file. I use system("python something.py"); to run the .py file and it has to get some input. How do I pass the input back to the .cpp file? I don't use the Python.h library, I have two separate files.
system() is a very blunt hammer and doesn't support much in the way of interaction between the parent and the child process. If you want to pass information from the Python script back to the C++ parent process, I'd suggest having the python script print() to stdout the information you want to send back to C++, and hav...
69,198,682
69,198,758
Issue using FILE* with std::getline()
I would like to get some advice on an issue I've encountered once working on small adjustments to an existing program. The program itself has to: Open a file and read it line-by-line preferably Pack the lines into istringstream and then split to 2 strings on a ':' separator Insert those 2 strings line1 and line2 into ...
std::getline() expects an std::istream-derived class, like std::ifstream, so you simply can't pass your own FILE* to it (unless you wrap it inside of a custom std::streambuf-derived object assigned to a standard std::istream object. std::ifstream uses std::filebuf, which uses FILE* internally, but you can't supply it w...
69,199,129
69,199,965
Casting derived template class from virtual class
In my code, I have one abstract class and ~8 child classes. I want to ask, is it possible in C++ to cast typename and return the calling class? I need something like separate A<int> as A and int. I need something like this: template <typename T> class Base { T data; virtual void setData(T p_data) = 0; virt...
If I'm reading your D code correctly, you are basically: taking the ClassType of the this object that is being converted, pattern-matching it to make sure it is a template with 1 argument, and then extracting the type of that template, casting the this object's data member to a specified input type, returning a new ob...
69,199,708
69,199,802
SetEnvironmentVariable() does not seem to set values that can be retrieved by getenv()
I have an EXE which, at startup, sets an environment variable (ie: MAGICK_CODER_MODULE_PATH=xxx) via the Windows API SetEnvironmentVariable(). When I look in Process Explorer (from SysInternals) at the list of environment variables set to my EXE I can see the environment variable I just set before (MAGICK_CODER_MODULE_...
You're mixing APIs: Windows' SetEnvironmentVariable bypasses the C++ runtime, so that the copy of the environment that is stored in your program is not updated. The later getenv call looks into this copy and doesn't find your change. Use the same API level for both calls. Either getenv and _putenv, or use the Windows A...
69,200,251
69,200,274
arduino mqttclient callback which is a class method function
I'm using the following Arduino MQTT library (https://github.com/256dpi/arduino-mqtt) which apparently supports passing a callback which is a method of a class and not of a free function via: void onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb); // Callback signature: std::function<void(MQTTClient *client, cha...
A pointer to a member function is a fundamentally different type than a pointer to a free function. Adding static to the member function would work only if it doesn't access any instance data. If that's actually the case, you need to add static to the class body's declaration, and not the full definition of the functi...
69,200,506
69,200,636
Identical code using more than double the RAM memory on different computers
I'm creating a Minecraft clone in C++ with OpenGL. I noticed today that when debugging the program on my laptop, the RAM usage is way higher that the RAM usage on my desktop PC (~1.3gb vs ~500mb). I'm getting these memory numbers from Visual Studio's diagnostics tools. I'm using GitHub and even with the same branch, sa...
Many laptop architectures use something called unified memory. That is to say, there is only one big pool of memory that is shared between the CPU and GPU (or the equivalent portions on an APU). On such architectures, allocating video memory is essentially the same thing as allocating RAM. It's all hidden away by the g...
69,200,640
69,200,701
Class reference member - Not an error in a class with synthesized constructor but error in user defined constructor
Below errors out. Understood. class a { int b; int &c; // uninitialized a(int x): b(x) {} }; Below uses synthesized constructor. Why no error below? How does the synthesized constructor initialize the reference or will it even do that? Reference has to be user initialized from what I understand. class a { ...
The error in your first class comes here: a(int x): b(x) {} // error This is because you've defined a constructor that doesn't initialize the reference member c. This is an ill-formed constructor, and so the compiler gives an error. In the second class, the compiler will synthesize a constructor, so there's no error....
69,200,663
69,200,843
Static method in base class reflect the derived class name
Here is base class: class Product { public: static void RegisterClass() { string b = __FUNCTION__; }; } and here is the derived class. class Milk: Product {} in the main function I call the static method this way: main(){ Milk.RegisterClass(); } Then it writes value Product::RegisterClass into va...
The fairly constrained scenario presented by OP can be achieved reasonably well with the use of CRTP. As pointed out in the comments, type_info::name() is fraught with uncertainty, so a better approach would be to explicitly state the string to use: #include <string> #include <string_view> #include <iostream> template...
69,200,846
69,200,947
copy assignment operator implicitly deleted because field has a deleted copy assignment operator
I'm getting this error as soon as I define a destructor, but without that the compilation succeed, but I badly want to define destructor to debug some seg faults. class Socket { private: seastar::output_stream<char> socket; public: std::string peer; public: Socket() = default; ...
Add Socket(Socket&&)=default; Socket& operator=(Socket&&)=default;
69,201,102
69,201,162
In C++ is there an optimal way to run down a pointer chain to the value?
Lets say I have a program and a value like int finalValue = 1234;. Next there are pointers that point to finalValue. For Example: int *p = &finalValue; int **p2p = &p; int ***p2p2p = &p2p; If I wanted to create a function that ran down the pointer chain till it got to the finalValue (1234) what would be the most optim...
If you have c++17, you can use a recursive function like so: template<typename T> constexpr auto get_pointer_value(T v) { if constexpr (std::is_pointer_v<T>) { if (!v) { // Optional error handling if you can't trust the caller. throw std::invalid_argument("Pointer v cannot be null"); } ...
69,201,244
69,233,940
Creating a makefile for a C++ Project
I'm currently trying to write a Makefile which searches the current directory and all sub-directories for C++ files, then compiles them one by one (if they haven't already been compiled or edited since the last time it was compiled) into an individual Object file at the location ./Objects, before finally using the Obje...
For anyone in the future wondering how to setup a makefile, here's my final makefile. Appname := App #Output Dir for Object and dependency files ObjectsDir := ./Objects #Find all the source files SrcFiles := $(shell find . -name "*.cpp") #Create a variable holding all the objects Objects := $(patsubst %.cpp,$(ObjectsD...
69,201,433
69,201,526
Finding the maximum value in a vector using recursion C++
I am trying to find the maximum value in a vector using recursion but I keep on getting a segmentation fault. I can't figure out the issue. Does anyone know why? int find_max(vector<int> integer_array, int i) { //variable i just keeps track of the index starting at 0 if(i == integer_array.size()-1) { ret...
I am assuming the vector always has elements. In the return statement, should be i+1 instead of i++: return max(integer_array[i], find_max(integer_array, i+1));. The problem with i++ is that this form would pass the value i to find_max for the second argument, and then increment. So you end up calling either return m...
69,201,644
69,202,331
a protobuf problem about descriptor and reflection
I have a problem. I want to make a very high frequency use of FieldDescriptor so I want to save FieldDescriptor address instead of calling FindFieldByName every time. I found that the same protobuf object would share the same meta, they have the same FileDescriptor object and FieldDescriptor object. Can I do that? ente...
Yes, this is safe (unless you are doing something funky). When working with the interfaces generated by protoc, descriptors can safely be treated as permanent global variables, shared across messages. It's a different matter when you are dealing with descriptors that come from other sources, like gRPC's reflection serv...
69,201,935
69,238,031
OpenCV segmentation fault when converting video to PNG sequence
Converting to webm first causes the frame of segmentation fault failure to move to frame 1308, instead of 1301. My code: #include <iostream> #include <stdio.h> #include <stdlib.h> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> using namespace s...
The segmentation fault actually happened in a following function. I thought I had exactly 1340 frames in this render, but it turns out some got lost in some processing I did, so the code in the original question was 100% correct. The segmentation fault was caused by a failure to read a file, ( I had forgot to pad zer...
69,202,158
69,202,462
Need help fixing this C++ code (Quadratic Formula solver)
When I execute the problem, the results often end up as "-nan' or "nan" I am new to programming so this is a bit confusing. Could use some help ` #include <iostream> #include <cmath> using namespace std; //Quadratic Equation int main() { //Variables double a,b,c,n,z,x1,x2,r; //Input cout<<"Quadartic Equat...
std::sqrt() in the <cmath> header expects its argument to be a positive number, in case it isn't, it will return nan which is what you are facing. It also raises the FE_INVALID floating point exception which you can verify after calling the std::sqrt() function using std::fetestexcept(FE_INVALID). In actual math, squar...
69,202,252
69,217,967
ncurses library I want to know why colors cannot be drawn
[I'm Japanese using google translate] The presentation code is void Renderer (); the function part, why can't I draw the color? I don't know the cause. Also, the addch (); function can draw colors normally. OS: Ubuntu Reference site A: https://www.linuxjournal.com/content/programming-color-ncurses Reference site B: htt...
wattron(window,COLOR_PAIR(stage->at((y * size.x) + wattroff(window,COLOR_PAIR(stage->at((y * size.x) + When using windows, it was necessary to use the wattron() and wattroff() functions instead of the attron() and attroff() functions. The code inside the comment part of the question sentence needs to be modified as ...
69,202,767
69,211,237
Can imdecode be used to clipboard image?
I want to use the Windows clipboard image data in OpenCV without using a temporary file. Can I use imdecode for this? I tried this but Mat was empty: if(!IsClipboardFormatAvailable(CF_DIB)) return; OpenClipboard(NULL); HGLOBAL clipboard = GetClipboardData(CF_DIB); if(clipboard){ char* data = (char*)GlobalLock(cli...
You should be able to use CF_BITMAP to get the handle to HBITMAP. Then use GetDIBits to copy HBITMAP to cv::Mat memory. If for some reason CF_BITMAP is not available, see this example for CF_DIB backup, or check to see which format is available. void copy() { cv::Mat mat; HBITMAP hbitmap = nullptr; if (!::...
69,203,198
69,203,277
error: expected ‘#pragma omp’ clause before ‘{’ token
I have a stack. Each time I pop one element from it, handle this element and determine whether the element should be pushed back to the stack according to some results. The code is like the following. I used the OpenMP task construct to achieve parallelism because the handling processes of different elements are indepe...
In OpenMP specification you can read The syntax of an OpenMP directive is as follows: #pragma omp directive-name [clause[ [,] clause] ... ] new-line Please observe the new line at the end of the directive, so { have to be in a new line: #pragma omp parallel { #pragma omp single { or #pragma omp parallel #pragma o...
69,203,400
69,215,303
Return without memory leak
I try to write a function which converts a char* to a wchar_t* to simplify multiple steps in my program. wchar_t* ConvertToWString(char* str) { size_t newStrSize = strlen(str) + 1; wchar_t* newWStr = new wchar_t[newStrSize]; size_t convertedChars = 0; mbstowcs_s(&convertedChars, newWStr , newStrSize, st...
Classic. Use the C++ power ! ... Destructors freeing allocated memory Instead of your wchar_t buffer [1024]; why not declare and use a Wstr class, looking approximately like this (maybe malloc and free to used instead of new and delete ?): class Wstr { public : Wstr () : val_ ((wchar_t*) NULL), size_ (0) {} ~Wstr ...
69,203,795
69,204,105
non-const lvalue reference to type 'pair<...>' cannot bind to a temporary of type 'pair<...>'
I'm trying to get a reference to the emplaced item using auto& syntax, but it fails to compile with above error. How can I get reference to emplaced item in this case? I've attempted to use const auto& but the object seems invoking destructor on my actual app so thus it seems to be a fake reference at best. #include <s...
That's because try_emplace returns a pair<iterator, bool>, which is a temporary, NOT a reference to the inserted element. See description on cppreference After emplacing, you could say auto& elem = connections["test"]; or auto [connection, inserted] = connections.try_emplace("test"); auto& elem = *connection; for exa...
69,204,086
69,205,338
May types be defined in `decltype` or `sizeof` expressions in C++20?
Since C++20 lambda functions are allowed in unevaluated contexts, and in particular they should be allowed inside decltype and sizeof expressions. In its turn, lambdas can define some types in their bodies and possible return objects of these types, for example: using T = decltype( []{ struct S{}; return S{}; } ); [[m...
The restrictions on lambdas in unevaluated contexts that were removed as of P0315R4 means this is not prohibited (albeit a corner case), and thus arguably GCC has a bug here. Particularly the following discussion from the paper is relevant here: Furthermore, some questions were raised on the Core reflector regarding r...
69,204,119
69,208,173
Conversion of date from human-readable format to epoch fails
I'd like to create a program that converts the date of a specific human-readable format to epoch. So far I have the following code the first part of which creates this human-readable format and the second one converts it to epoch. #include <time.h> #include <iostream> #include <ctime> #include <string> #include <cstrin...
The C timing/calendrical API is very difficult to use correctly (which is why C++ is moving away from it). From the C standard: The value of tm_isdst is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and negative if the information is not available. Set tmNow.tm_isdst = ...
69,205,046
69,206,177
How to deal with declaration of the primitive type without the initial value known (C++)?
In some cases it happens for me to declare a variable without knowing its value first like: int a; if (c1) { a = 1; } else if (c2) { a = 2; } else if (c3) { a = -3; } do_something_with(a); Is it the standard professional practice to assign some clearly wrong value like -1000 anyway (making potential bugs more r...
I would introduce a default value. I'm usually using MAX value of the type for this. Shortest you can do this with the ternary operator like this: #include <climits> int a = c1 ? 1 : c2 ? 2 : c3 ? -3 : INT_MAX; do_something_with(a);
69,205,586
69,208,379
Move layout to another layout in Qt5
I have a custom container widget in Qt5 which has a QFrame without a layout. I use setLayout on QFrame which works fine but sometimes I want to transfer an existing layout which contains widgets and other layouts to that QFrame as layout. Is that even possible in Qt5 to transfer layouts already added with addLayout?
No problem. Just make the layout the layout of the target widget with setLayout(). The widgets contained will be reparented automatically. void MainWindow::moveLayout() { // Move the layout from ui->g0 to ui->g1 and vice versa // every time you call moveLayout static int toggle = 0; QLayout* l; QWi...
69,205,644
69,205,673
How to prevent the creation of an object in C++
i'm learning how to make classes and i want to prevent my user from creating an object without providing a variable. The problem is that i don't know how to procede in order to do that. here's my code : class KoalaNurse { public: int id; // the var that i need to provide in order to create a new object if i...
You need to define your own constructor in order for the compiler not to create the default one. KoalaNurse (int some_value) { //your code }; Another option is to use keyword delete in order to prevent creating default constructor: KoalaNurse() = delete;
69,205,683
69,209,650
c++17 how to create a template instance with a non-type template
I want to create a body with a different part, and if I know the part's name, I can create the corresponding instance with a factory.Just as below: template<typename Part> class Body {}; class Part1 {}; class Part2 {}; enum class E { part1, part2, }; template<E e> class Factory { public: static unique_p...
There's nothing here with a non-type template argument, so your title is confusing. I assume your compiler error is complaining about Body<> Well, that's an error. Body is not a type, but a template. It needs an argument and there is no default. The code wants it to be a Body<Part1> or a Body<Part2> but there is no ...
69,205,878
69,206,944
How Do I Sort A Stack Alphabetically in C++?
I'm new to C++, and I do not understand stacks that well. I tried following some tutorials to sort Stack1 using recursion, but nothing has been working or it is solely focused on arrays containing integers. I also tried sorting the Names array directly, but it does not work. How do I go about sorting my Names array for...
If the underlying container for the stack has its data stored in consecutive memory, which is true for a std::vector or a std::deque, the sorting is ultra simple. You can simply sort the underlying container. That is really easy. The std::deque is the default underlying container. So, this approach will work in most ca...
69,205,893
69,206,075
Does c++ standard allow to call std::align with zero size and obtain a past-the-end pointer?
Does std::align allow to be called with zero size and obtain an aligned pointer that may be a past-the-end pointer? For example: #include <cstdio> #include <memory> int main() { alignas(16) char buffer[16]; printf("buffer: %p ~ %p\n", static_cast<void*>(buffer), static_cast<void*>(buffer + sizeof(buffe...
Does c++ standard allow to call std::align with zero size Yes; there is no precondition disallowing zero size. and obtain a past-the-end pointer? Obtaining a one-past-the-end pointer is allowed.
69,206,044
69,281,389
SWIG/Python: Unable to access referenced parameter in Python callback
In SWIG, I've got a wrapped C++ base class that is inherited in Python. The C++ side invokes callbacks on the Python derived class, which works fine. Unfortunately, one of the parameters of the callback is passed as reference. Accessing this reference yields: Fatal unhandled exception: SWIG director method error. Erro...
Ah, I finally figured it out, turned out that the Property class was in a different namespace in the C++ code, but not in the SWIG interface file. By setting the right namespace, a proxy was generated and everything worked fine.
69,206,062
69,206,114
How To Output Characters Using Linked Lists?
#include <iostream> using namespace std; class FloatList { private: // Declare a structure for the list struct ListNode { float value; struct ListNode *next; }; ListNode *head; // List head pointer public: FloatList(); // Constructor void a...
If you wanted to make it work for string types, or char types, you would have to turn your linked list into templated class. Look at your definition of node: struct ListNode { float value; struct ListNode *next; }; You defined float as value, so how do you expect it co hold char ty...
69,206,184
69,206,756
How can I use a QMap to store and look at my data?
I am new to QT started to try out some things with QMap as it seems like a useful tool. I already read some other forum threads but I wasnt able to answer my question. The user is supposed to add and edit different shapes via the GUI. For the shapes I first wrote an abstract base class: #ifndef BASE_H #define BASE_H #i...
You need to declare all the behaviours you need in the base class. I don't see the need to have Base hold the data. E.g. if you need to be able to read and write the UI, there should be methods to do that. class Base { public: virtual ~Base() = default; virtual void toRTC() = 0; virtual QVariantMap properti...