question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
64,466,642
64,467,072
C++20 Concepts: Element iterable concept
I am trying to create a concept ElementIterable which can determine the type is nested ranges or not. For example, the elements in std::vector<int> is not iterable, but the elements (std::vector<int>) in std::vector<std::vector<int>> is iterable. The idea about using std::iterator_traits<T> comes up in my mind and the ...
If you want to ask if a type is a range which itself contains a range, that's simply applying the std::range type twice: template<typename T> concept nested_range = std::ranges::range<T> && std::ranges::range<std::ranges::range_value_t<T>> range_value_t extracts the value_type from the iterator type of the range. Here...
64,467,261
64,468,275
VSCode C++ c_cpp_properties.json "defines" does not define the symbol on ubuntu
I have a main.cpp thus: #include <stdio.h> int main(){ #if defined(_LINDEBUG) #if defined(VSCODE) printf("VSCODE defined"\n); #else printf("VSCODE not defined\n"); #endif #endif } My c_cpp_properties.json file in .vscode/ folder is thus: { "configurations": [ { "name": "Linux", ...
Per the documentation [link]: defines A list of preprocessor definitions for the IntelliSense engine to use while parsing files. Optionally, use = to set a value, for example VERSION=1. So, it seems that you would only add some defines there for the sake of helping out the Intellisense engine. Some quick testing coul...
64,467,375
64,478,161
catching signals in different threads in gtest
I'm having a multi-threaded application and I want to test the behaviour of sending specific signals to these threads (ie. to verify that the EINTR-errors are occuring on blocking functions). In the thread I set something like: struct sigaction sa {}; sa.sa_handler = func; sigemptyset(&sa.sa_mask); sa.sa_flags = ...
In principle this works. I did not set the sa_handler correctly!
64,467,398
64,468,115
Preprocessor initialize array
How, if necessary, using boost preprocessor, initialize the array as follows: INIT_ARRAY(plus,minus) //extract to std::array<std::pair<char const *,std::string>, 2> array{{ {"plus", std::string("plus")}, {"minus", std::string("minus")} }}; INIT_ARRAY(plus,minus,multiply) //extract to std::array<std::pair<char const ...
You can use BOOST_PP_COMMA_IF for conditional commas, and BOOST_PP_VARIADIC_SIZE to work out the size beforehand. This should work (for non-empty arrays): #include <boost/preprocessor/punctuation/comma_if.hpp> #include <boost/preprocessor/seq/for_each_i.hpp> #include <boost/preprocessor/stringize.hpp> #include <boost/p...
64,467,502
64,467,546
split a word into letters in c++?
how can to split a word in a string into the letters. for example "hello" to "h", "l", "l", "o" and store them in an array.
Just use the string as if i would be a array. In a c++'s std::string if example equals "Hello world!" then example[0] equals 'H', example[1] equals 'e' and so on. If you really need to copy the string to an array of chars for some reason, you can use the strcpy function from the string.h library. Here an example: #incl...
64,468,036
64,468,195
How can I make a generic function that prints to any output stream?
I am trying to create a generic function, print_if(start, stop, condition, out), that will print all of the elements that satisfy the unary predicate condition to the output stream out. I know the body of the function still needs work, but I can't come up with how to make the stream generic. Here is what I have: templa...
The error you're asking about is because you're passing std::cout by value. You can't copy the standard output stream. The key fix is I've identified out as passed by reference (Stream&). There were other errors (all marked). Roughly 30 years ago I made the same error in my first outing with C++ - tried to pass the out...
64,468,100
64,471,083
How to read a large, and growing, file efficiently
An existing application writes an output file constantly as it runs. I want to be able to read this file in another (C++) application, line by line, for external processing. A realistic scenario is the existing application has been running for some time. My new application is launched and works through the output file,...
There are a few issues to be aware of when reading a growing file line-by-line: The producer may not necessaraly write a line into a file atomically. std::getline/gets strip off trailing \n, so your don't know whether it read the full line or EOF was hit. There are no facilities in C++ standard library to wait on a fi...
64,468,119
64,468,540
DXGI desktop duplication, capture only a particular RECT
Is there any way that we could crop a particular RECT from the image captured using the Desktop Duplication and renders it back to the window after applying some effects. please have a look at this picture: Take notepad as the example ,so as per the above picture i want to capture the red rectangular area (the window ...
The API is designed in such way that you capture composed image for the entire monitor with a really small processing overhead. There is no option to capture a region of interest (ROI), and there is no much sense in this either: you would gain nearly nothing, specifically there would be no performance benefit. When you...
64,468,726
64,468,847
Why isn't shared_ptr to Derived implicitly converted to shared_ptr to Base
I do not understand why in the following code, the shared_ptr<Derived<int>> isn't implicitly converted to a shared_ptr<Base<int>>: #include <memory> template <typename T> class Base { }; template <typename T> class Derived : public Base<T> { }; template <typename T> T foo(std::shared_ptr<Base<T>>) { ...
The reason for this behavior is the fact that foo is a template. Note, that everything works correctly if foo is not a template: int foo(std::shared_ptr<Base<int>>) { return int{}; } However, when foo is a template, the compiler first needs to instantiate foo, and it wants to be able to instantiate an exact match,...
64,468,921
64,469,035
Issues and Err0r Levels
I'm building an GUI application. When there is an issue and something happens, I can log the issue and present it to the user. If the error is FATAL, then the app quits and doesn't show anything. If it is ERROR, then I just present the issue to the user. My question is in some code like this: char* data = static_cast<c...
Like this person said, if your app is known to use lots of memory and failed allocation is recoverable, then carry on. Else if your app doesn't allocate many large buffers, than I would crash the app.
64,468,936
64,469,802
python subprocess running c++ task reading file error
I have a c++ task which reads a file and process it: // A.m.cpp std::string filename = "myfile.txt"; std::ifstream file(filename.c_str()); std::ifstream file1(filename.c_str()); std::string line1; while(getline(file1, line1)){ // process some logic } for(;;){ file.getline(...
You should put the .eof() break after the processing: for(;;){ file.getline(buffer); // buffer is "testdata" // process some other logic if (file.eof()) break; } You'll want to process the data even if EOF is hit after it's read. Note that this can give you empty strings in buffer, so you might want to han...
64,469,680
64,469,767
The CUDA compiler is not able to compile a simple test program
I created a template Clion project in CUDA and it does not seem to work at all. The only thing which I changed is this line in CMakeLists.txt: set(CMAKE_CUDA_COMPILER "/usr/local/cuda-10.1/bin/nvcc") So it looks like this: cmake_minimum_required(VERSION 3.17) set(CMAKE_CUDA_COMPILER "/usr/local/cuda-10.1/bin/nvcc") ...
It started working when I changed the default system gcc alternative from version 9 to 8. (Ubuntu 20 default gcc version is 9) sudo update-alternatives --config gcc
64,469,841
64,494,965
Constexpr: Convert a list of string views into a list of char arrays
I came across an interesting constexpr problem that haven't been able to fully crack. The last piece of the puzzle that I'm missing is the following // Given a constexpr array of string views constexpr std::array<std::string_view, X> views = ...; // Convert it to a list of char arrays constexpr std::tuple<std::array<c...
So long as views is a variable with static storage duration (rather than a prvalue created by a constexpr function call), you can implement this with the usual auto& template parameter and std::index_sequence tricks: #include<array> #include<string_view> #include<tuple> #include<utility> #include<type_traits> #include<...
64,470,088
64,470,118
3 argument minimum comparison issue c++
I am attempting to find the minimum cost path of an array. The code works when restricted to moving either down or to the right, but not diagonally. Issue: return min(findMinCost( cost, m - 1, n), findMinCost(cost, m, n - 1), findMinCost(cost, m - 1, n - 1)) + cost[m - 1][n - 1]; I added the th...
In c++ min can take 2 arguments. You should calculate the min like this, return min( min(findMinCost( cost, m - 1, n), findMinCost(cost, m, n - 1)), findMinCost(cost, m - 1, n - 1)) + cost[m - 1][n - 1]; That way, you will at first find the minimum between findMinCost( cost, m -...
64,470,174
64,470,527
How to pass multidimensional Numpy arrays to C function using CFFI?
I am trying to speed up my Python program by implementing a function in C++ and embedding it in my code using CFFI. The function takes two 3x3 arrays and computes a distance. The Python code is the following: import cffi import numpy as np ffi = cffi.FFI() ffi.cdef(""" extern double dist(const double s[3][3], cons...
The types double[3][3] and double *[3] are not equivalent. The former is an 2D array of double 3x3, stored as 9 contiguous double. The latter is an array of 3 double pointers, which is not how 2D static arrays are implemented in C or C++. Both numpy arrays and C++ static arrays are represented in memory as a contiguous...
64,470,331
64,470,938
How to capture variadic arguments with lambda and pass them to inner scope
I have the following structure that lets me bind the virtual functions of ExampleInterfaceClass to a class that implements the virtual functions from ExampleInterfaceClass: struct ExampleStruct { ExampleInterfaceClass *instance = nullptr; ExampleInterfaceClass *(*InstantiateScript)(void); void (*DestroyScr...
You can capture variadic arguments in the same way you would capture any other arguments. However, care must be taken to not capture them by value, as it will make them const qualified. Here is an example: #include <utility> struct L {}; void k(L&& ); template<class... T> void foo(T&&... t) { auto l = [&t...]() {...
64,471,026
64,518,217
Does std::vector.reserve() erase existing values?
If I have a vector full of, idk lets say Rectangles with type x,y,w,h. And now I want to add 10000 more to my existing 10000, will calling vector.reserve(20000)delete my existing 10000 rectangles?
No, it won't delete any of the previous values. You can use it as you like (before or after the assignment of first 10000 values).
64,471,081
64,471,700
Most efficient algorithm to find if a path exists
I'm looking for an algorithm that tells me whether a path between point A and point B exists. I don't need to know what the path actually is, I just need to know if it exists or not, and execution time is key. The base grid had either empty fields or walls, just those two. Could you guys suggest something? EDIT: I thou...
If you have only 2 points A and B to check for in your 2D grid, you can adopt depth first search or breadth first search to check if the path exists. If you are given the grid and several pairs of points to check against in the form of queries, you can adopt the below approach: We iterate over the 2D grid cell by cel...
64,471,435
64,489,890
What data type is used on variable names? And how can I shortcut assignments to multiple variables? C++
I was wondering if there is a way to shortcut this: int main(){ int number1,number2,number3,number4,number5,number6; number1=0; number2=0; number3=0; number4=0; number5=0; number6=0; } If variable names were strings I would do something like this: int main(){ int number1,number2,number...
Don't think in terms of variables with related names, think in terms of data structures, where in this case you mean array: std::vector<int> number(6, 0); Where that creates an array with 6 entries, each containing 0. You can use these like: number[i] Where i is just an index between 0 and 5.
64,471,652
64,490,331
libcurl HTTP request set content-disposition and content-type in MIME data
I'm trying to upload an image on twitter using libcurl, I used the twurl command line tool to generate an HTTP request and see how it should look like, what I get is this: POST /1.1/media/upload.json HTTP/1.1 Accept: */ Content-Type: multipart/form-data, boundary="00Twurl342528555775455418lruwT99" Authorization: OAuth ...
how do I specify Content-Type and Content-Disposition ? Just read the fine manual (which you can navigate to from the fine example postit2.c) CURLcode curl_mime_type(curl_mimepart * part, const char * mimetype); curl_mime_type sets a mime part's content type. CURLcode curl_mime_filename(curl_mimepart * part, const...
64,471,672
64,472,000
Can you install winegcc/wineg++ on Mac OS?
I am writing a c++ program specifically for Windows operating system. However, I am writing it on a Mac OS. I know it seems counter productive, but I have my reasons that would take the next paragraph to explain. What I want is to be able to compile it on my Mac, and turn it into a .exe file, but I won't be running it ...
This will allow you to import windows.h on a Mac OS, you just won't be able to run it on a Mac OS The comment that said to install MinGW worked great. I just ran brew install mingw-w64 in terminal, then this example command worked on a mac and compiled a windows executable file: i686-w64-mingw32-g++ shell.cpp -o shellv...
64,471,758
64,473,893
How to count the total number of valid pointer elements in a C++ template function?
I recently started learning C++ after significant experience in C# and Python. I'm attempting to create a function template that accepts a pointer parameter, then iterates through its values until the next pointer element is no longer valid. Ideally, I would like the function to accept one generic pointer parameter. It...
What you are attempting to do with your len() function looking for a nullptr element is only possible with a null-terminated array of pointers, eg: int* arr[3]; arr[0] = ... some pointer ...; arr[1] = ... some pointer ...; arr[2] = nullptr; size_t arr_len = len(arr); // returns 3 Fail to include that terminating null...
64,471,889
65,827,382
UE4 - How do I get actors of an array to follow the previous actor like in Snake?
I am new to C++ and even newer to UE4. I am trying to create a Snake game but I am having trouble getting the body segments of the snake to move like they should in Snake. Like a train of actors. How do I get the body to move like a train/snake in the Snake game? I've made a gif to try and show the problem (sorry if it...
SOLVED! For anyone having this problem, I managed to find a really simple solution in a video on YouTube for this. My code now looks like this: void ASnake::UpdateTailSegmentLoc() { if(!TailSegment) { return; } if(TailSegment) { for (int32 i = 0; i < TailSegmentArray.Num(); i++) ...
64,472,211
64,508,139
Python argument types did not match c++ signature - Boost.Python
I am just starting to explore using Boost.Python to wrap some c++ code. I am starting with a toy problem to work out the basic issues but don't understand the error I'm getting. #include "pch.h" #include <boost/python.hpp> #include <boost/python/def.hpp> #include <boost/python/args.hpp> class Parameters { public: ...
Your python code is invalid. my_lib.Parameters.a = 9 creates static variable in class Parameters that is why it "works". Then you try call static method add which doesn't exists, add is instance method so you need instance of Parameters to call it. So this should work: import sys import my_lib import ctypes if __name...
64,472,686
64,475,920
Activating the system menu
I have created a custom window with no title/caption bar. I have added a system-menu icon/button to the custom menu bar. Here is the code that handles the command from that button, where I attempt to access the system menu: case ID_MENUBAR_SYS: HMENU hSysMenu = GetSystemMenu(hWnd, FALSE); TrackPopupMenu(hSys...
According to the document: hWnd A handle to the window that owns the shortcut menu. This window receives all messages from the menu. The window does not receive a WM_COMMAND message from the menu until the function returns. If you specify TPM_NONOTIFY in the uFlags parameter, the function does not send messages to the...
64,473,084
64,476,626
How to change a normal method to a static method in an inherited class in c++?
Exist a way to change a method of a base class, to be the same method but just with the modifier static? I'm searching in all the questions but only find the inverse question (static to non static). My "solution" until now, was to copy and paste all the method in the derivated class but with the static modifier. Exist ...
A non-static method must be called on an actual object. Here, this can be done in one of two ways. Create a temporary A object when calling A::method. class B : public A { public: static bool method(){ return A().method(); } }; Define a dummy A object (otherwise unused) just for calling A::method. class B ...
64,473,377
64,473,378
How to set "user data" for a body in PlayRho?
How can I associate "user data" - i.e. arbitrary data for my application - with bodies in the PlayRho 0.10.0 physics engine? In the Box2D 2.4.1 physics engine, I can associate "user data" with bodies, using the userData field of a b2BodyDef instance that I pass to the b2World::CreateBody function and get the value back...
Possible Solution: In your application, you can use an array whose elements are your user-data values and whose indices match the underlying values returned from creating your bodies in PlayRho. For example, a simple/naive implementation for any void* compatible user data might be like: int main() { struct MyEntity...
64,473,429
64,474,786
C++ writing JSON with JSONCPP
I was trying to use the JSONCPP library to work with JSON documents in C++. Reading another question here, I saw this example and tried to implement: #include "json/json.h" int main(){ Json::Value event; Json::Value vec(Json::arrayValue); vec.append(Json::Value(1)); vec.append(Json::Value(2)); vec....
It’s all about how you build/install the library and specify the headers in the source. Since you didn’t mention what method you took to build the library, I’ll demonstrate three solutions I got to work on Ubuntu 20.04 LTS. Install the Package Most straightforward way is to install via apt: $ sudo apt-get install libjs...
64,473,551
64,567,587
Compile errors when building a project using fbx SDK in Visual Studio/C++
I am trying to build a project about loading fbx objects in OpenGL. I used this resource's codes: https://github.com/sho3la/FBX-Loader-OpenGL-C- But I got these compile errors: 'GetCacheChannel': is not a member of 'fbxsdk::FbxVertexCacheDeformer' 'IsActive': is not a member of 'fbxsdk::FbxVertexCacheDeformer' 'lHasVer...
AutoDesk has changed its libraries. Therefore for using these functions in those errors, instead of using FBX SDK 2020, I used FBX SDK 2014.2.1 VS2012, and it works for me.
64,473,795
64,505,776
boost::multiprecision and rocksdb::Slice string interaction c++
Hi can someone explain what is happening here to me? Version: librocksdb-dev/bionic,now 5.8.8-1 amd64 [installed] librocksdb5.8/bionic,now 5.8.8-1 amd64 [installed,automatic] boost-cpp 1.74.0 #include <iostream> #include <string> #include <boost/multiprecision/cpp_int.hpp> #include <rocksdb/db.h> int m...
This snippet is undefined behavior: rocksdb::Slice dbkey = check.str(); /* ... */ std::cout << dbkey.ToString() << std::endl; rocksdb::Slice is a "fat pointer" with a data pointer and a size, like C++20's std::span or C++17's std::string_view. It has no ownership of whatever you assign to it. The result of check.str()...
64,474,157
64,474,237
Expose a private std::bitset field that is inside a class for modification
I'm coding in a C++ project that hasn't advanced beyond C++11 yet. Let's say I have an enum class as follows: enum class Weekdays { kSunday = 0, kMonday, ... kSaturday, }; I want to create a class that has a private std::bitset field which keeps track of which weekdays are special. This class does lots...
The operator[] for bitset returns an std::bitset::reference. So if you have your function return that, you can modify the values in the bitset directly! For example: enum class Weekdays { kSunday = 0, ..., kSaturday, COUNT }; class Foo { private: std::bitset<(ulong)Weekdays::COUNT> weekdayF...
64,474,438
64,474,574
Document distance algorithm with C++ vectors
Iam trying to build Document distance algorithm with C++ vectors, the algorithm is working fine the similiary vectors and give me output 0, which mean the vectors are same 100%, but when i try it with very difference strings it gaves me value like one point some decimals, the value should be 90 or nearby it when it dif...
frequencyD1 , frequencyD2 = 0; This is a comma operator expression evaluated as (frequencyD1) , (frequencyD2 = 0); which is equivalent to frequencyD2 = 0; and leaves frequencyD1 unchanged. To reinitialize both variables to 0 use the following, instead. frequencyD1 = frequencyD2 = 0; [ EDIT ]   Also... the value...
64,474,452
64,476,249
Reading Items inside of an array in an array C++
I have a very quick question... I'm using nlohmann's json library. My issue is that when I go to print a element, the program stops responding. My json file { "Consoleprinting": false, "Input" : [{"Code" : [{"Name": "EC", "Keybind": "VK_NUMPAD1"}] }] } What I have tried. nlohmann::json jsonData = nlohmann::json::p...
array["Code"] is an array containing a single collection of key-value pairs, so you need to write: std::cout << array["Code"][0]["Name"] << std::endl;
64,474,494
64,475,016
Linking a class when used inside another class
When I have a class I want to use somewhere else, such as Secondaryfile.cpp, I can import it fine into another file where I create a new class, as long as I do the class definition, etc inside the .cpp file, not the header file, otherwise I get linking errors. I have tried adding things like extern "C" in the Secondary...
There are many problems with your code. In Mainfile.cpp you didn't specify the return type of Mainfile::getDoubleX()(it should be int) You can only specify static member functions inside a class definition(in Mainfile.cpp, the function getObj has that qualifier). Also it should have a class scope, so the correct way ...
64,474,665
64,474,729
Terminated due to timeout: Where is the scope of optimization?
I was solving a problem in Hackerrank which is as shown below: Given an array a of n integers and a number d, , perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. Here is my very simple solution: #include<iostream> using namespace std; int m...
Since only the program output is interesting, you don't need to perform the real rotation in the array. #include<iostream> using namespace std; int main() { int n,d; cin>>n>>d; std::vector<int> arr(n); for(int i = 0; i < n; i++) cin>> arr[i]; for(int i = d; i < n; i++) cout<<arr[i]...
64,474,717
64,568,568
How to implement OOBE complete notification in c++?
I want to do a win32 implementation of RegisterWaitUntilOOBECompleted API for my app. The goal is to detect OOBE complete and perform specific operations. However, I don't quite understand how to implement it in c++ code. I spent the past 6 hours looking for sample implementation but to no luck. Can anyone explain how ...
For anyone in the future who might be looking for sample implementation of this API, here's how I did it. This sample code is not intended to compile though. Header file #include "Oobenotification.h" class MainClass { // put constructor here // destructor ~MainClass(); // OOBE notification ...
64,475,009
64,475,268
How to implement a map with three keys in C++ STL?
So, I have a class class table() { public: string product, region, province ,price; }; so i have an array of objects of the above shown class and my objective is to write a function with input as product, region, province the function searches this in the array and returns the price. Now to search efficiently with...
Yes you can do this with std::unordered_map, and it isn't as difficult as it may first seem. All a std::unordered_map cares about is: The key type must be hashable using either a default hash algorithm or one provided to the container as a template-parameter type or a construction instance. The key type must support e...
64,475,348
64,475,803
what is the difference between 'grid.size()' and 'grid[0].size()' in C++
I have question in C++ 2D array. what is the difference between grid.size() and grid[0].size() in C++ in the code below? public: int minPathSum(vector<vector<int>>& grid) { for(int i = 0; i < grid.size(); i++) for(int j = 0; j < grid[0].size(); j++) { if(i == 0 && j == 0) continue; i...
grid[0] returns the first row of this two-dimensional vector so grid[0].size() returns size of first row of that matrix and grid.size() return number of rows in the matrix.
64,475,407
64,475,706
Projecting on a std::map with std::ranges::min
Is it possible to project on a std::map? I tried to use std::ranges::min with a projection, but it seems to throw errors that I can't interpret why its not liking things. #include <set> #include <iostream> #include <ranges> #include <vector> #include <iostream> #include <map> #include <algorithm> int main() { std...
Instead of std::ranges::min you can use std::ranges::min_element like this: auto lowest = *std::ranges::min_element(std::move(usage_table), {}, &std::map<int,int>::value_type::second); Also, it's unclear why you are moveing the map, it d...
64,475,978
64,476,134
Is using if (0) to skip a case in a switch supposed to work?
I have a situation where I would like for two cases in a C++ switch statement to both fall through to a third case. Specifically, the second case would fall through to the third case, and the first case would also fall through to the third case without passing through the second case. I had a dumb idea, tried it, and i...
Yes, this is allowed, and it does what you want. For a switch statement, the C++ standard says: case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a switch, see break. [Note 1: Usually, the substatement that is the subject of a switch is ...
64,475,997
64,476,273
Passing Type Into Lambda Function In C++ Template
I am trying to use std::transform in template function. Because there are various types which need to be handled by the template function, the key part is the design of the lambda function in std::transform. I want to pass the base type of the iterable T to construct a lambda function. The experimental code here use ty...
The problem is the rigidity of CLang compilers with respect to the standard. The problem is not the type(that is correct), the problem is that you have to put typename before template dependant types. However the best solution is to use auto to let the compiler deduce the type itself.
64,476,062
64,476,103
Multiple VBO(s) in one VAO
How would you have, an example an VBO for position, an VBO for texture-coords and lastly a VBO for normals? Currently I can only create one VBO for one VAO, and I have no idea how to make it multiple VBO(s) float vertices[] = { // Pos 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0...
The buffer object which is currently bound to the ARRAY_BUFFER is associated to the vertex attribute (index), when glVertexAttribPointer is called. A reference to the Vertex Buffer Object (object id) is stored in the state vector of the Vertex Array Object. Just bid the proper VBO, before specifying the vertex attribut...
64,476,366
64,477,272
Implementing Queue Using Two Stacks Time Limit Exceeded
ERROR: type should be string, got "https://www.hackerrank.com/challenges/queue-using-two-stacks/problem\nThe above question requires implementing a queue using two stacks.\nSo what I am supposed to do is answer to 3 types of queries\n\nEnqueue\nDequeue\nPrint Top\n\nMy code is as follows:\n/*\n #include <iostream>\n #include <stack>\n using namespace std;\n \n class QueueTwoStack{\n stack<int> s1;\n stack<int> s2;\n public:\n void enqueue(int x);\n void dequeue();\n int Front();\n };\n void QueueTwoStack::enqueue(int x){ //ENQUEUE\n while(!s1.empty()){\n s2.push(s1.top());\n s1.pop();\n }\n s1.push(x);\n while(!s2.empty()){\n s1.push(s2.top());\n s2.pop();\n }\n }\n void QueueTwoStack::dequeue(){ //DEQUEUE\n if(!s1.empty())\n s1.pop();\n }\n int QueueTwoStack::Front(){ //RETURN FRONT\n return s1.top();\n }\n int main() {\n QueueTwoStack Queue;\n int q,ch,x;\n cin>>q;\n while(q--){\n cin>>ch;\n if(ch==2)\n Queue.dequeue();\n else if(ch==3)\n cout<<Queue.Front()<<endl;\n else if(ch==1){\n cin>>x;\n Queue.enqueue(x);\n }\n }\n return 0;\n }\n*/\n\nNow This Code passes 25% of test cases and giving \"Time Limit Exceeded\" verdict. Any Help on inefficiency\nin code or approach?. Also I want to ask that does using classes slow down the code?\n"
You are maintaining a fully sorted queue in stack s1, enqueuing elements by shoving all of s1 into s2, adding the next element, and then shoving all of s2 back into s1. This is not very optimal. Let us instead call the stacks in and out. In the beginning both are empty: in: <top> out: <top> Enqueuing elements just ad...
64,476,812
64,476,879
Can I use 2 loop statement in one loop?
is this loop statement is correct? if not correct then what alternative way? I am trying to o(n) loop statement like this- for(int i=0 ; i<n ; i++ , j=n ; j<n*2 ; j++){ continue; }
The construct is wrong, you cannot you two loops in one construct, but you can have more than one variable controlling the iteration. For example, you can have Two (or more) variables, i and j, initialized with certain values. A loop controlling statement, involving operation and condition check on i and j (and others...
64,476,946
64,477,060
no match for operator '=' (std::array<T, 3> and std::initializer_list<T>)
I have a template vec<T> class for math vectors with constant length is equal to 3. It looks like this: template <typename T> class vec{ public: vec() { /**/ } vec(std::initializer_list<T> list) { /**/ } private: std::array<T, 3> data; }; I know, that it is possible to initialize std::array with an std::...
Why can't I initialize std::array with initializer list in such a way? Braced-init-list and std::initializer_list are not the same thing. (Even std::initializer_list could be constructed from braced-init-list.) std::array is an aggregate and could be aggregate-initialized or assigned by braced-init-list as std::array...
64,477,810
64,478,734
Understanding how to use typedef void function with pointers as params
I'm trying to understand a firmware written in C that drives a chip for ultrawideband connections. The firmware does heavy use of typedef and pointers. I've understood most of the idea behind the firmware but there's a typedef void function I can't understand. Basically, the firmware creates a structure to hold the dev...
To make it more clear let's assume that there is a function declared like void f( int *x ); The type of the function is void( int * ). You can introduce an alias for this function type like typedef void Func( int * ); and declare (but not define) the function using the alias Here is a demonstrative program. #include ...
64,478,149
64,478,224
Reding some lines of input in cpp
I am trying to read the following input: 1.first line is some natural number q; 2.next q lines are either '+' or '-' or 'insert'+space+somecharacter the cin doesn't work here of course because of space so i tried to use getline in the following way: int q; cin>>q; getchar(); while(q--){ string s; getline(c...
You don't necessarily need to look for spaces, you may just read first thing, and if it's insert then you read once again: int q; cin>>q; while(q--){ string s; cin >> s; if (s == "insert") { char c; cin >> c; // do something with s == "insert", c == 'h' } else { // do som...
64,478,456
64,478,593
Errors when I test my DLL in a test client project
I created dll project and compile it. Then I created test client project and try to use DLL as described here https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=vs-2019 Some error occures when I include header file into test client project: Severity Code Des...
Seems you havn't add path of opencv2 to your client project's IncludePath.If you do not want to do this ,you should avoid to include opencv2 files in header files that your client project include.
64,479,106
64,479,449
How to create member objects by class constructor?
In my example I created a class Person which has a member object: struct data. This object contains data about person. Each time a Person-Object is created, also the data-object shall be initialized. Observation: When adding object initializer to code (1) at class constructor I get failure message: incomplete type is ...
You should put the definition of data inside the definition of person if you want a member of it. Something like this. #include <string> #include <iostream> class person { public: struct data { std::string name = "John"; int age = 42; int weight = 75; }; // This is just the definiti...
64,479,123
69,106,392
Change blobFromImage dimensions order in OpenCV
I faced a problem with C++ blobFromImage function in OpenCV. I trained a CNN-network in Keras which takes a 4-d blob as input (common practice, nothing special). The problem is that my blob order is NHWC (where Channle size is always 6) but blobFromImage returns only NCHW. There is no any trouble to reshape numpy-blob ...
It seems like you received an answer to your question in the OpenCV forum assuming, you have 2 (float) images A and B of equal size, 3 channels each, you could first merge them like this: vector<Mat> v = {A,B}; Mat C; merge(v, C); now C has 6 interleaved channels, and we need to add the "batch" dimension: int sz[] = ...
64,479,759
64,481,519
How to filter a constexpr `std::array` with a `UnaryPredicate` lambda?
Given a constexpr std::array and an UnaryPredicate pred, how can I filter the array to return a new constexpr std::array which all of its elements meets pred(e)? struct foo { int f1; int f2; }; static constexpr std::array<foo, 5> arr{ foo{1,1}, {2,2}, {3,3}, {4,4}, {5,5} }; int main() { // will result in {...
it's definitely that, dependent type, the type that depends on a value, is impossible in present-day C++. you can't decide the size M of result type std::array<T, M> by only the function arguments, which means M must be a template argument. so you have to provide an additional template argument M for the result type, b...
64,479,879
64,480,380
C++ using 'this' keyword in member initialization list
I was writing an Integer struct struct Integer { int value; Integer(int value_) : value(_value){ } }; This works fine but instead I wanted to use value name for the parameter too and this causes a name clash. That's why I tried to use this keyword like below struct Integer { int value; Integer(int valu...
This works fine but instead I wanted to use value name for the parameter too and this causes a name clash. No it doesn't. Integer(int value) : value(value){ } This is just fine (if a little confusing to some). It is simply not permitted in the language grammar to write this-> there, probably because it would make no...
64,479,982
66,425,994
C++: Include directory, but only allow one folder to be visible (for Eigen)
Suppose one wants to include a large open-source project as a submodule in a repo (myrepo). For this example, let's take Eigen. No problem, I can git submodule add https://gitlab.com/libeigen/eigen.git This creates an eigen subdirectory which contains a lot of subfolders: myrepo/ eigen/ bench blas ...
You can create a separate, empty directory include and put a soft link Eigen pointing to myrepo/eigen/Eigen. Then add that include as a search directory, instead of myrepo/eigen. Git tracks soft links "as is", storing the path of the link in the repository, and recreating the link when cloned. It makes no attempts to v...
64,480,450
64,483,008
How to make slot work at time when calling function?
I have a function and connection between a slot and a signal. Check the code below: void NetworkAccessManager::sendPOST(QString url) { QNetworkCookieJar *cookieJar = new QNetworkCookieJar(manager_); manager_->setCookieJar(cookieJar); QNetworkRequest request(url); QByteArray postData; postData.appen...
I have found a couple of problem solutions. First one I am saving the cookie in a file. Here's the code: void NetworkAccessManager::replyFinishedSlot(QNetworkReply *reply) { ... QFile cookieFile("cookie.txt"); if (cookieFile.open(QIODevice::WriteOnly)) { cookieFile.write...
64,480,690
64,482,549
Why QTextDocument background color changes only once?
I am using TextEditor from the example provided with Qt (https://doc.qt.io/qt-5/qtquickcontrols1-texteditor-example.html). Here is the complete code https://code.qt.io/cgit/qt/qtquickcontrols.git/tree/examples/quickcontrols/controls/texteditor?h=5.15 I have created a custom method void DocumentHandler::setBackgroundCol...
Cause The documentation of QTextDocument::setDefaultStyleSheet says: Note: Changing the default style sheet does not have any effect to the existing content of the document. You try to overcome this by calling setHtml after setDefaultStyleSheet like that: m_doc->setHtml(m_doc->toHtml()); However, this does not produ...
64,480,952
64,481,169
How are Missing Template Arguments Deduced when Function Argument is a 2D Array
Consider #include <iostream> // Print n x m - Matrix A template<typename T, size_t N, size_t M> void printMatrix(T (&A)[N][M]) { for(int i=0; i<N; ++i) { // Rows for(int j=0; j<M; ++j) { // Columns std::cout << A[i][j] << " "; } std::cout << "\n"; } } int main() { int A...
To better understand the situation, let's use lower-case variable names: template<typename T, size_t N, size_t M> void printMatrix(T (&a)[N][M]) { for(int i=0; i<N; ++i) { // Rows for(int j=0; j<M; ++j) { // Columns std::cout << a[i][j] << " "; } std::cout << "\n"; } } int m...
64,481,481
64,481,641
How to avoid `std::to_string()` making a very small double number to 0?
I have a requirement to store very small double numbers into a string format and then later reverse them. However, when I try to run std::to_string() on a small number like 4.7816457028269855e-143 then it simply makes it 0. I referred Set precision of std::to_string when converting floating point values and its linked ...
No, the problem is not precision, but the format. You want to print in scientific format (with exponent) but std::to_string() uses the fixed format by default and I'm not aware of any way to change this. However, streams use scientific if appropriate or you can force it with std::scientific: std::ostringstream oss; oss...
64,482,245
64,525,590
Visual C++. LNK2011: precompiled object not linked in. But I linked
I'm trying to use precompiled headers for the first time. Using command line. Here is it: cl /Yu"pch.h" src/main.cpp src/shader.cpp src/camera.cpp /std:c++17 /MT -EHsc glfw3.lib glew32.lib GlU32.lib OpenGL32.lib -I include /link "pch.obj" /LIBPATH:"C:\Users\yuryi\Desktop\C++\CMDOGL\lib" "kernel32.lib" "user32.lib" "gdi...
I solved this by this sequence of commands: cl /c /Yc"pch.h" src/pch.cpp /std:c++17 /MT -EHsc -I include /link /nologo cl /c /Yu"stdafx.h" src/main.cpp /std:c++17 /MT -EHsc -I include /link /nologo cl /c /Yu"stdafx.h" src/camera.cpp /std:c++17 /MT -EHsc -I include /link /nologo cl /c /Yu"stdafx.h" src/shader.cpp /std:c...
64,482,435
64,482,649
Thread Ordering Service isn't enabled
I am studying the Thread Ordering Service of Windows. So, I have written the following code to test how TOS works really? But it doesn't work and it gives me an error. #include <windows.h> #include <process.h> #include <iostream> #include <avrt.h> #include <stdio.h> #pragma comment(lib, "Avrt.lib") #define _100NS_IN_1...
The links here and here, explain that Windows Thread Ordering Service is not on by default: The thread ordering service is off by default and must be started by the user. While the thread ordering service is running, it is activated every 5 seconds to check whether there is a new request, even if the system is idle. T...
64,482,698
64,482,809
C++: My program only read the numbers I input as hundreds though I typed it as thousands
Here's the given of my assignment: Compute for the cash value of a P 25,000 Savings Bond at any time according to the following: If the Bond is less than 6 months old, the interest is zero percent. If the Bond is between 6 and 12 months old, the interest rate is 1 percent. If the Bond is between 13 to 18 months old, ...
Looks like you have some misunderstandings about how conditional expressions work in C++. If the Bond is between 6 and 12 months old, the interest rate is 1 percent In C++ that is written like this else if (Age_Bond >= 6 && Age_Bond <= 12) You have some other issues int Age_Bond = 6 && 12 && 13 && 18 && 19 && 24; in...
64,483,031
64,483,203
Overloading << operator to print vector<MyClass>
I'm trying to overload the << operator to print a vector that contains elements of type Position (vector). I managed to overload the << operator for type Position, but I can't figure out how to do it for vector. Can you help? //position.h #ifndef POSITION_H #define POSITION_H #include <iostream> // using IO fu...
I'm sure there's a duplicate on StackOverflow somewhere, but I cannot find it. I'm a bit surprised about this question, as I don't really see a critical issue at first sight. Did you get a compiler error or segmentation fault? Every time you assign to Placeholder, you make a copy. This is not necessary at all: you can ...
64,483,040
64,484,331
Resolve ambigus function call when the only difference is a parameter passed by reference or by copy
Say I have a class implementing these two methods : void foo(const int a); void foo(const int & a); How do I resolve ambiguous call like : int bar = 42; foo(bar); EDIT Both methods are virtual pure inherited from two different parents, doing different things. I would like to have the ability to choose one at call. Bi...
The usual solution to this kind of problem is to use a pair of intermediate classes to rename those functions. struct intermediate1 : base1 { virtual void f(int x) = 0; void foo(int x} { f(x); } }; struct intermediate2 : base2 { virtual void g(const int& x) = 0; void foo(const int& x} { g(x); } }; Now...
64,483,167
64,483,266
Got undeclared identifier error for a function argument (C++) in Linux, but not in Windows
I have written these codes: #include <iostream> #include <limits> #include <string> #ifdef _WIN32 #include "WinSock2.h" #include "WS2tcpip.h" #pragma comment(lib,"ws2_32.lib") #elif __linux__ #include <sys/socket.h> #include <arpa/inet.h> #define SOCKET socket #else #error Compiler cannot interpret plat...
What socket() in Linux returns is int, not socket nor SOCKET. You are using #define SOCKET socket in Linux mode and it will have it put function name where type name is expected like this: int hoge(){ return 0; } int fuga(hoge& x) { // error return 0; } This error is not produced in Windows because the problemati...
64,483,538
64,483,814
Apple clang and C++20 operator ambiguity with inherited comparison operator
Upgraded Xcode today (and underlying clang went up to clang-1200.0.32.21), and started getting ambiguous comparison errors like described here. But in that example the lack of const was evident, while for me the issue seems to be an inherited comparison operator. Here is a minimal example: struct Bar { bool operato...
It's the using declaration. If you omit it, everything works as expected. The operator defined in the base class is found by name lookup, provides a single candidate (same implicit conversions, with the order reversed) and all is well. Here's what the using declaration does [over.match.funcs] 4 For non-conversion func...
64,483,879
64,485,303
C++ adding 2 3D vectors returns garbage value
I am very new to c++ and just started to learn operator overloading. Here is my attempt class Vector { public: float x=0,y=0,z=0; Vector(float x, float y, float z) :x(x),y(y),z(z) {} Vector(Vector& copy) :x(copy.x),y(copy.y),z(copy.z){ std::cout << "Copy Created" << std::endl;} //Testing if any new objects were cr...
Operators +, * and - conventionally return a copy not a reference: Vector operator+(const Vector& v1) const //^^ no & //^^ added const //^^ added const { Vector v(this->x+v1.x,this->y+v1.y,this->z+v1.z); return v; } Also you should declare the method as const...
64,484,121
64,484,914
Implementing efficient insertion on a custom unordered_map container in C++
I am creating a custom C++ STL Container library and I have a question that concerns efficient insertion both in code size and execution time (avoiding as many copies as possible). I want to write an insert (same applies for find/erase) function (_insert_unique) that can be called from other insert-like functions and a...
If I understand correctly, you are trying to preserve the value category of the argument There is two ways to do that: Overloads: void myFunc(const Object& obj) { handleObject(obj); } void myFunc(Object&& obj) { handleObject(std::move(obj)); } Forwarding references template <typename T> void myFunc(T&& obj) { hand...
64,484,247
64,598,679
CLIPS system halted and not continuing to execute
I am integrating CLIPS expert system following APG docs, Thanks for the great docs, I am successful at integrating CLIPS to my C++ project, My Application runs continuously and feed the Facts to CLIPS system using EnvAssert method and invoke EnvRun, everything works fine until i receive this error. [PRNTUTIL7] Attempt ...
Fixes for resetting the error flags for API calls have been checked into the subversion repository on sourceforge: https://sourceforge.net/p/clipsrules/code/HEAD/tree/branches/
64,484,835
64,484,836
How to setup one shared OpenGL contexts per thread with SDL2?
When I implemented parallel initialization and update of procedural objects in my OpenGL game, I had to create multiple OpenGL contexts with shared objects, and bind one per thread, so I could create/update the VBOs in parallel. I got the idea of how to do that from this blog post, and made my first implementation like...
I don't know if the solution we found will work on every platform supported by SDL, but it at least works on both Windows and Linux/X11. The issue was that SDL_GL_MakeCurrent() is not thread-safe in general (it seems to be thread safe on Linux/X11, but that is by chance, since SDL is a multiplatform library (and the pr...
64,485,316
64,486,253
Problem in arduino if run system how to fix
Hello i have problem : state sensor = sensor steps "IF" anyone "steps now = impulse " = all code run"perfect good work im happy" but if sensor LOW a did not detect any motion while loading the code = broke stop all , even if it is at the end close or halfway, it will stop when there is no traffic "" (stage_sensor == ...
What you could do is set up a global "stage" variable: #include <AccelStepper.h> //accelstepper library const byte limitSwitch_1 = 26; const byte limitSwitch_2 = 25; bool switchFlipped = false; bool previousFlip = true; int switchCounter; int newSpeed; int stage; AccelStepper stepper(1, 22, 23); void setup() ...
64,485,354
64,492,992
Is it possible to hook to WinLogon proc when logon to window?
I need to develop a dll which will be called whenever somebody logon to window. This dll will hook to the WinLogon proc and do something, the WinLogon process will be suspended until the dll done their work. I tried to take around stackoverflow as well as msdn but I can't find the relevant article. Is there anyone here...
In Windows 2000,Windows XP and Windows Server 2003, you could use Winlogon Notification Package. But in Windows Vista and later, Winlogon notification packages are no longer supported, see Winlogon Notification Packages Removed: Impact on Windows Vista Planning and Deployment. You can use the alternative solutions list...
64,485,854
64,486,469
Why can't my str string be identified in sub scope?
First to all, I found this source to get path of all files(Unicode) and it doesn't belong to me, I defined a string ( string str = "test"; ) and it's not detectable(cout << str;) in the function why is that happening? #include <atlstr.h> #include <iostream> #include <string> #include <functional> #include <io.h> using...
Because str is not known in the scope where it is used. string str = "test"; Unknown: enumsubfiles(L"B:\\", L"*.txt", -1, ENUM_FILE, [](const std::wstring& dir_with_back_slant, _wfinddata_t& attrib) -> bool { // str is unknown in this scope wcout << dir_with_back_slant << attrib.name << '\n'; cout << str; ...
64,486,361
64,486,642
Why is my code taking so long to run and why are there big changes in its runtime?
#include <iostream> struct IntVector { int N; int* dimensions; IntVector(int N): N(N) { dimensions = new int[N]; for(auto i=0; i<N; i++) dimensions[i] = 0; } IntVector(const IntVector& other) : N(other.N), dimensions(other.dimensions){} ~IntVector() { ...
As pointed out in the answer given by Anonymous1847, your program exhibits undefined behaviour (which can include taking a long time to do something obscure ... sometimes), because you are deleting the allocated pointer multiple times when the three class objects are deleted (immediately before the program exits). This...
64,486,389
64,575,998
CMAKE Could NOT find PythonLibs (missing: PYTHON_INCLUDE_DIRS)
I am trying to run cmake in our school project, the CMakeList.txt looks as follows: cmake_minimum_required(VERSION 3.0) project(nagata) FIND_PACKAGE( OpenMP ) if(OPENMP_FOUND) message("OPENMP FOUND") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") se...
It looks like I got the flags' names wrong. Calling the cmake with the following flags solved the problem for me: cmake -DPYTHON_LIBRARY=$(python3-config --prefix)/lib/libpython3.8.dylib -DPYTHON_INCLUDE_DIR=$(python3-config --prefix)/include/python3.8 .. It finds the PythonLibs successfully now.
64,487,132
64,487,884
How to read from a text file and split it into values in C++
This is my text file (mytext.text): rho_0,10 kp_0,8 Beta_kp,6 x_min,5 x_max,8 y_min,9 y_max,5 z_min,4 z_max,7 I want to read from this text file line by line, and store each value in the parameter at the same line. For example, for the first line, store 10 in rho_0. I have written this code: #include <iostream> #incl...
You'll want to use a map data structure of some sort to store parameter values. You'll probably want std::unordered_map for this. Like @user4581301 said, you can use std::getline with a specific delimiter, like a comma. std::unordered_map<std::string, float> params; std::ifstream myfile("mytext.txt"); std::string param...
64,487,289
64,487,392
Difference between `closed_iota` and `iota`?
What is the difference between closed_iota and iota, from the ranges-v3 library?
The second one follows the standard C++ way of expressing a range - defaulting to right-hand side open range. The first one is inclusive. iota takes two arguments: start and end. It produces elements from start to end without including end. closed_iota takes two arguments: start and end. It produces elements from start...
64,487,920
64,488,108
How to move past the linking information when using gdb's `starti`?
Some debuggers (like pdb) automatically break at your first line of code, then allow you to add breakpoints as needed. I'd really like to have that functionality with gdb. (I need to trace code execution through a huge codebase, and none of my guesses as to where to set a breakpoint have been correct, so the program ju...
Use start, not starti. start puts a temporary breakpoint on your main() function and begins executing. It should start at the beginning of your program proper.
64,487,926
64,487,995
Changing value of variable passed by reference outside function call does not change value inside function
Whereas using a pointer argument instead of a reference has different behavior in a multi-threaded scenario. It that the value does change in the middle of the function call when altered in a separate thread. I'm looking for an explanation as to why the behavior is different between a pass-by-reference and a pass-by-po...
std::bind will copy anything being passed as references. You need to use std::reference_wrapper and/or std::ref, e.g.: std::thread t(std::bind(&PrintValue, std::ref(a), &condVar));
64,488,186
64,488,304
Why does strcmp() in a template function return a different value?
I am reading again "C++ Primer, 5th edition". In chapter 16 about templates, there is an example of "template Non-type parameters": template<unsigned N, unsigned M> int compare(const char (&p1)[N], const char (&p2)[M]) { return strcmp(p1, p2); } int main() { cout << compare("hi", "mom") << endl; cout << s...
This is a compiler optimization applied when strcmp is passed literal parameters, even on -O0. See this compiler explorer link: https://godbolt.org/z/T4EKxr #include <cstring> template<unsigned N, unsigned M> int compare(const char (&p1)[N], const char (&p2)[M]) { return strcmp(p1, p2); } int a() { return com...
64,488,810
64,488,949
Pointer Arrays and Functions CPP
I wonder If there's a way to assign a dynamic array (C style), values like in the case of a non dynamic array (instead of matrix[0][0] = ...), e.g.: int n = 3; int ** matrix = new int*[n]; for(int i = 0; i < n; ++i){ matrix[i] = new int[n]; } matrix = {{1,1,1},{2,0,2},{3,3,3}}; And how would I pass the non dyn...
I wonder If there's a way to assign a dynamic array (in c), values like in the case of a non dynamic array (instead of matrix[0][0] = ...) For 2D arrays, only on declaration, e.g.: int matrix[][3] = {{1,1,1},{2,0,2},{3,3,3}}; Or int matrix[][3]{{1, 1, 1}, {2, 0, 2}, {3, 3, 3}}; Value initialization of arrays is all...
64,488,899
64,489,165
Remove n characters from string c++
I'm having some trouble removing characters from a string. In my function, I have an int (n) and a string (str). I need to enter an int, then remove the first n characters of that string. For example: int n = 2 string str = hello output: llo I'm not allowed to use any string functions other than size(), otherwise I ...
if you don't want to modify input string string removeFirst(string str, int n){ //input: a string (str) and an integer (n) //output: a string with all but the first n characters of str string rv = ""; if (n >= str.size()) { return rv; } for(int i = n; i < str.size(); ++i){ ...
64,488,910
64,488,953
Segmentation error while using stacks in c++ stl?
I was trying to write this code for converting infix expression to postfix expression but I'm getting a segmentation fault for some values. Code is : #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stack> #include <bits/stdc++.h> using namespace std; int pre...
Firstly, the iteration should be just in the strings. This means that for(int i=0;i<21;i++){ should be for(int i=0;i<s.size();i++){ Secondly, you forgot to check if the stack is empty in the loop. This means that while(prec(st.top())>=prec(s[i])) should be while(!st.empty() && prec(st.top())>=prec(s[i]))
64,489,028
64,492,867
How to ignore an OPENSSL_ENGINES environment variable in my app?
I'm using openssl library in my C++ app. I've found out how to ignore an OPENSSL_CONF environment variable. It's possible by specifying of my own config file: OPENSSL_config("openssl.cnf"); But what about an OPENSSL_ENGINES environment variable? How can it's value be ignored in my app? How to prevent loading the engin...
OpenSSL does not seem to expose a proper way to ignore that environment variable. As a workaround, you could set that environment variable yourself to some bogus value before invoking ENGINE_by_id(), like this: putenv("OPENSSL_ENGINES=/dev/null"); You will have to be a little careful that the bogus value you choose do...
64,489,052
64,490,856
problem with function on the lside of an assignment
I have this tuple defined inside a test case, std::tuple<int, string, string, double> t1 = { 1321, "xxxx", "xxxx", 1.68 } and i have to write a function unpack where i should be able to do this: int key; string first_name; string last_name; double height; unpack(key, first_name, last_name, height) = t1; I can't chang...
I have to write the function because the definition of the tuple and the assignment are in a test case and i can't modify that. template <class... Args> constexpr decltype(auto) unpack(Args&&... args) noexcept { return std::tie(std::forward<Args>(args)...); }
64,489,118
64,490,243
Why QCustomPlot is too slow in ploting large data?
I want to plotting some large chunk of data (3k) which is coming every 100ms. I tried QCustomPlot and Qwt with exact 3k points and i got really good performances in plotting with Qwt and really bad performances with QCustomPlot. And i think i behave wrongly with QCustomPlot, i used this code for plotting in QCustomPlot...
I guess that the root of the problem is the code itself. You are updating points in the wrong way. You have to delete the below line from your code std::srand(std::time(nullptr)); This line will force the rand()'s seed to be fixed for a deterministic time(if I want to be precise your seed value is fixed for 1 second),...
64,489,529
64,491,173
How to avoid reinitializing a vector every time though an openmp for loop?
I have a for loop that looks like this: for (int i = 0;i<N;i++) { vector<double> vec; //then do work on vec, such as resize or push_back } This is inefficient because every time through the loop, vec is resized, and this may force a dynamic memory allocation every time through the for loop. So an easy optimiza...
It's actually very simple. #pragma omp parallel for is a compound statement - you can split that: #pragma omp parallel { std::vector<double> vec; #pragma omp for for (int i = 0;i<N;i++) { vec.clear(); //then do work on vec, such as resize or push_back } } This will work just fine as you...
64,489,621
64,556,343
Setting different RTP SSRCs with GStreamer and multiudpsink
In a C++ program I'm using a GStreamer pipeline to generate an RTP stream and send it to two destinations at the same time with a multiudpsink element. This works fine, except that both streams have the same RTP SSRC. Is there a way to set different SSRCs for the two streams ?
The solution I found was to use a tee element and have multiple legs that each have their own RTP encoder (in my case rtpopuspay) and multiupdsink element. That way each feeds gets a different SSRC.
64,489,777
64,490,273
can not use auto for declaring variables
Why in the code below I can not use the auto keyword? I am not sure if this is a Qt related problem or a c++ thing? #include <QFile> void foo(const QString& path) { auto f = QFile(path); // Error: QFile is marked as deletet here QFile file(path); // works fine!!! }
In a variable declaration, auto deduces the type from the initializer value. If you can't specify an initializer, then you can't use auto. In C++17 and later, there is guaranteed copy elision, so auto f = QFile(path); will get deduced as QFile f = QFile(path); as expected, and then it will be optimized further to just ...
64,489,929
64,490,472
C++ variables passed to constructor are not being passed correctly
I am just trying to get set up with some simple classes in C++. I am trying to create an Order type that takes in a price (double), quantity (int) and a style (std::string) Here is my order.h #ifndef ORDER_H #define ORDER_H #include <string> #include <iostream> class Order { private: double limit_price; ...
In your constructor the name of the parameters shadow the members: Order::Order(double price, int quantity, std::string style){ limit_price = price; quantity = quantity; style = style; } What do you think quantity is in the second line? Why should it something different on the left hand side than on the ri...
64,490,194
64,490,420
assigning and changing data type during compile time ( c++ )
okay this is just a wild idea. Can you put variable type in a variable during compile time? type contains int, and then you change it to char And you decide to change it again! type contains class object. just keep changing it And it can be used like type = int; type var = 5; ( when type was assigned to int ) type = s...
You can do it using macros. #undef type #define type int type var = 5; #undef type #define type char type var2 = 'a'; However, this will be extremely confusing, I strongly recommend against it.
64,490,447
67,461,217
how to work with std::thread on freeRTOS?
I'm using freeRTOS on an stm32f407 with keil ide and arm compiler version 6 and g++17 and I don't like to work with freeRTOS threading APIs. instead, I want to work with std::thread c++ native library. but when I include #include <thread>, keil throws this error: error: <thread> is not supported on this single threaded...
Keil throws that error because you are linking your application against a library that does not support the API. There's a freeRTOS POSIX threading wrapper you can possibly evaluate to use, or you could create another abstraction layer on top of CMSIS OS API. There is also a C++ wrappers project, freeRTOS-addons, that...
64,490,492
64,517,750
C++ shared object initialization constructor destructor
I'm working on a Shared Object compiled with g++ that serves as a logging API. I've written a little utility to exercise the library, but I've found that the shared object constructor/destructor are called every time the program starts and exits. I'd like to be able to maintain the state of any variables/objects in the...
I'd like to be able to maintain the state of any variables/objects in the .so file, even if there are no active applications linked. Is there a mechanism for accomplishing this? In a modern OS, everything that is in memory "belongs" to one or more processes, and there is no such thing as ".so without an active applic...
64,490,515
64,490,553
SDL: Is defining the event struct with every iteration of the event loop inefficient?
This is the example given on the wiki and the way every tutorial I've seen does it... while (1) { SDL_Event event; while (SDL_PollEvent(&event)) { /* handle your event here */ } /* do some other stuff here -- draw your app, etc. */ } If I have this kind of event loop within an update functi...
First, the variable event is declared on the stack, this costs basically nothing. Since it is a POD type, there is no constructor and/or destructor that has to be run. Also, the lifetime of the variable ends at the end of the loop iteration, and will start again at the start of the next iteration. The compiler will see...
64,491,455
64,491,757
Calling a lambda for each nth argument of multiple tuples?
I am trying to write a code that invokes a lambda with input arguments extracted from a variadic set of tuples. However, my attempt does not compile: #include <iostream> #include <tuple> #include <utility> #include <type_traits> template <typename ...> struct first_of; template <typename T, typename ... Args> struct ...
The easiest way to do this is to just add another layer of indirection, having run_impl delegate to another function that does the actual calling. I took the liberty of renaming your function to call_transposed(): template <std::size_t I, typename Fn, typename... Tuples> void call_with_nth(Fn&& fn, Tuples&&... t) { ...
64,491,468
64,491,542
What is the simplest and most elegant way to wrap a function that generates a random number?
The function is the following: float random_float(float min, float max) { std::random_device rd; // obtain a random number from hardware std::mt19937 gen(rd()); // seed the generator std::uniform_real_distribution<> distr((...
As always the answer is: it depends. It depends on the architecture of your program. One good way would be to have an object responsible for generating sequences of random numbers and having references to it through it your program. A quick dirty trick to make it easily available is to make it a singleton. A simpler, e...
64,491,655
64,501,960
Multiple link errors building Qt 5.15 application for Android
Application builds fine with Qt 5.12.9 for Android. However fails with 5.15.1 on linking phase (compiles fine as deprecated Qt API was fixed). Building for arm64-v8a ABI only: qmake ANDROID_ABIS="arm64-v8a" ... Have multiple link errors like this: ~/Qt/5.15.1/android/include/QtCore/qobjectdefs_impl.h:415: undefined re...
Problem was in -nostdlib++ hack fix in the following line: QGCCommon.pri#L60 QMAKE_LINK += -nostdlib++ # Hack fix For 5.15 need to remove it and patch AndroidManifest.xml to correctly build APK. This line could be removed for 5.12 as well as it was ndk20 problem while currently Qt Creator installs and uses ndk21 by de...
64,491,678
64,492,791
How to change default project build options?
How I could change this option to default: release x64? I have my source on a folder and i have it as Release x64, but when i make a copy of this folder and open the project from this copied folder its set to Debug Win32. Do someone know in what file the current option I'm using is saved?
You could set MachineX64(/MACHINE:X64) in Properties->Linker->Advanced->Target Machine. Apply it and select x64. Then, the default platform is x64 next time you open. Also, if you want to permanently change the default platform, you could replace Win32 with x64 in the following three files. C:\Program Files (x86)\Mic...
64,492,425
64,492,487
Views of Container Types
According to http://eel.is/c++draft/range.view#concept:view , a view of a range is satisfied only when the range allows constant time move construction, move assignment, and destruction. However, I'm wondering how a container item, such as std::map, can be converted to a viewable_range. The time complexity of the under...
The confusion appears to be arising from this line: The view concept specifies the requirements of a range type that has constant time move construction, move assignment, and destruction; ... This doesn't mean that the underlying range that the view is constructed from needs to support constant time operations. It's ...
64,492,633
64,502,444
Automatic Differentiation of functions of complex variables
I was wondering if it is possible to apply boost's automatic differentiation library: #include <boost/math/differentiation/autodiff.hpp> to functions which return std::complex<double> values? For instance, consider the multivariate complex valued function: #include <complex> std::complex<double> complex_function(d...
is [it] possible to apply boost's automatic differentiation library to functions which return std::complex<double> values? Not at the present time. A version that did might look something like this: // THIS DOES NOT COMPILE - FOR DISCUSSION ONLY #include <boost/math/differentiation/autodiff.hpp> #include <iostream> ...
64,492,788
64,493,572
In c++'s SetWindowsHookEx function
I'm Korean student. Now this is my first question after signing up. DWORD getProcessId() { PROCESSENTRY32 process_infor; process_infor.dwSize = sizeof(PROCESSENTRY32); HANDLE snap_handle = CreateToolhelp32Snapshot( TH32CS_SNAPALL, //스냅 단계 NULL //스냅할 pid ); if (snap_handle != INVALI...
According to the SetWindowsHookExW: dwThreadId A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the curren...
64,493,219
64,493,287
Is there a more C++ elegant implementation to complete the function jump?
In my daily work, I usually write my code like this: int ret = 0; ret = func1(); if(ret != 0) { return ret; } ret = func2(); if(ret != 0) { return ret; } But this means I need to complete a lot of "if(ret!=0){return ret;}",Is there a more C++ elegant implementation to complete the function jump? By the way, we are...
The shown code seems to be logically equivalent to: int ret; if ((ret=func1()) || (ret=func2())) return ret; Tack on as many additional function calls as you wish, in the obvious manner.