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
71,250,816
71,968,603
CMake - How to handle dependencies of imported library targets with TARGET_RUNTIME_DLLS
In my project I rely on some third party shared library named foo. foo itself is relying on some other third party dll (let's call it bar.dll), which is however neither used by my project nor exposed in the headers of foo. The foo target is created and linked to my project as follows add_library(foo SHARED IMPORTED) se...
Since there seems to be no proper solution to this issue I came up with a (possibly fragile) workaround involving a meta target: # same as before add_library(foo_real SHARED IMPORTED) set_target_properties(foo_real PROPERTIES IMPORTED_LOCATION "${foo_dll_path}" IMPORTED_IMPLIB "${foo_lib_path}" ) # add SHARED IM...
71,251,192
71,251,296
C++ interpreting/mapping getch() output
Consider this program: #include <iostream> #include <string> int main(int argc, char* argv[]) { std::string input; std::cin >> input; } The user can input any string (or single character) and the program is going to output it as is (upper/lower case or symbols like !@#$%^&* depending on modifiers). So, my que...
The following code works: // Code 1 (option 1) while (true) { const int key = _getch(); // Get the user pressed key (int) //const char translated = VkKeyScanA(key); std::cout << char(key); // Convert int to char and then print it } // Code 2 (option 2) while (true) { const char key = _getch(); // Get...
71,251,287
71,251,537
using struct in sets
I am trying to make a set of sets, what is the correct to method to do that in C++. What i am trying to achieve is something like this One = { {"DDD", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64},{"JJ", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64}, {"kk", "Numbers", 0xf, 0xf, 0xf, ...
inline bool operator<(const Config& lhs, const Config& rhs) { return lhs < rhs; } This operator< calls the operator< which calls the operator< which the operator< which the operator< which calls... can you spot the problem? The recursion is infinite and will eventually overflow the stack. What you're probably in...
71,251,402
71,251,508
Initialize priority_queue without constructor
I have a priority_queue with custom comparator: using A = ... class A { public: A() { auto cmp = [](DataPair left, DataPair right) { return left.second > right.second; }; std::priority_queue<DataPair, std::vector<DataPair>, decltype(cmp)> q(cmp); q_ = q; } private: ...
You cannot use decltype(cmp) for the member type when cmp is local to the constructor. You can move the definition of the comparator out of the constructor and use the default constructor of priority_queue which default constructs the comparator: struct cmp { bool operator()(const DataPair& left,const DataPair& rig...
71,252,104
71,257,285
Why is there no (implicit) conversion from std::tuple<Ts...>& to std::tuple<Ts&...>?
As the title states, is there a specific reason why there is no (implicit) conversion from std::tuple<Ts...>& to std::tuple<Ts&...>? In contrast, the tuple implementation of EASTL provides this conversion. #include <EASTL/tuple.h> #include <tuple> #include <type_traits> int main() { using TupleRef = std::tuple<i...
There will be in c++23, as a result of the zip paper (P2321). Generally speaking, it is typical for overload sets to have one overload taking T const& and another overload taking T&&, it's not often that T& is needed as a distinct 3rd option (and T const&& even less so). This is one of those cases that originally had ...
71,252,342
71,252,459
Conversion error while trying to use CreateProcess Windows API
I am trying to run a C++ program that creates a process: int main() { HANDLE hProcess; HANDLE hThread; STARTUPINFO si; PROCESS_INFORMATION pi; DWORD dwProcessId = 0; DWORD dwThreadId = 0; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); BOOL bCreateProcess = NULL; b...
It seems you are compiling with Ansi strings rather than Wide strings, so STARTUPINFO becomes STARTUPINFOA, which is incompatible with CreateProcessW(). When I compile your code, I get error cannot convert argument 9 from 'STARTUPINFO *' to 'LPSTARTUPINFOW', which makes more sense than the error you posted. Either chan...
71,252,430
71,256,817
How to add a String Value/ Name Data pair in Windows Registry Editor key using C++ and Windows Registry API's
I want to add a string name and its value to the Windows Registry using C++ code, to stop browsers other than Firefox stop running. I plan to do the Windows Registry editing in a loop for all browsers, but for now I am implementing it for Chrome only. My current code below is adding a value to the Default string, and i...
KEY_ALL_ACCESS requires admin rights. All you really need in this situation is KEY_SET_VALUE instead. Don't ask for more permissions than you actually need. But, you do still need admin rights to write to HKEY_LOCAL_MACHINE to begin with. So make sure you are running your code as an elevated user. In any case, your ...
71,252,474
71,252,547
Is there a build command for meson?
Well I can init and build a meson with project as: $ cd /tmp/ $ mkdir foobar; cd foobar $ meson init --name foobar -l cpp --build Using "foobar" (project name) as name of executable to build. Sample project created. To build it run the following commands: meson builddir ninja -C builddir Building... The Meson build s...
Once you have configured your build you can do something like: cd build meson compile or meson compile -C build See the docs @: https://mesonbuild.com/Running-Meson.html#building-from-the-source
71,252,828
71,253,083
Base pointer offset adjustment for multiple inheritance question
I know base offset adjustment will happen in this situation class Mother { public: virtual void MotherMethod() {} int mother_data; }; class Father { public: virtual void FatherMethod() {} int father_data; }; class Child : public Mother, public Father { public: virtual void ChildMethod() {} int child_da...
The caller of a function knows exactly what types are involved and does the necessary adjustments. That is, Child c; fun(&c); behaves exactly the same as Child c; fun(static_cast<Father*>(&c)); but the conversion is implicit.
71,252,917
71,253,064
c++ program not giving desired output
disclaimer: i am in 8th grade in school and we are learning the ancient and dead TURBO c++ as our first programming language. I have written around 50 simpler programs so far. here is the most intresting on i am working on. i was writing a program to find sum of n natural number using classes and trying to make it 'fai...
The problem is that the data member s has not been initialized and you're using that uninitialized data member which leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output o...
71,253,245
71,262,875
Enqueue kernel from kernel leads to a misunderstood build error
I need to launch a kernel from another kernel so I read the OpenCL specs and did exactly as mentioned but I got a CL_BUILD_PROGRAM_FAILURE. Maybe my opencl version is less than 2.0 but I have downloaded OpenCL with CUDA so normally the version is upper than 2.0 right? Here is my kernel code : __kernel void funcB(__glob...
You can't use OpenCL 2.0/2.1/2.2 features on OpenCL 1.1/1.2/3.0 devices. Nvidia GPUs only support the OpenCL C 1.2 language standard (you can query this with cl_device.getInfo<CL_DEVICE_OPENCL_C_VERSION>()). Nvidia recently "upgraded" to OpenCL version 3.0, but this is just a new name for version 1.2. OpenCL 2.0/2.1/2....
71,253,815
71,254,011
How can I get double(or bytes) data through PQgetvalue in an efficient way?
I create a table with 3 columns: int8, double and bytea. When query a row of data, I use PQgetvalue to get each column value in a row. But PQgetvalue return a char*, I have to convert text value to corresponding type, like atoi or strtod etc. Is there is a more efficient way to get actual data, avoid converting data e...
There is not much overhead in converting a char * to a number. But you can use binary mode by calling PQexecParams with 1 as the last argument. To retrieve binary data, you have to use PQgetlength and PQgetisnull to get size and NULLness of the datum. Also, the data will be in the binary format used by the database se...
71,253,945
71,254,648
asio socket, split incoming data at a delimitator?
I am reading data from a asio socket in c++. I need to parse the incoming data as json. To do this, i need to get a single json string entry. I am adding a character ';' at the end of the json string, now i need to split at that character on read. i am trying this: int main() { asio::io_service service; asio::i...
I'd use read_until: #include <boost/asio.hpp> #include <iostream> #include <iomanip> namespace asio = boost::asio; using asio::ip::tcp; int main() { asio::io_service service; tcp::socket socket(service); socket.connect({{}, 4444}); std::string str; while (auto n = asio::read_until(socket, asi...
71,254,196
71,254,270
C++ empty iterator with {}
I found this answer on stack overflow for reading a stream into a string. The code std::string s(std::istreambuf_iterator<char>(stream), {}); works just fine for what I was doing, but I was really confused about the {}. As far as I can tell this is using the std::string constructor that uses a begin and end iterator, b...
{} is a braced initialiser list in this context. It is a list of initialisers used to initialise an object. It is used to initialise a temporary object. In this case, the list of initialisers is empty. In such case, the object will be value initialised. In case of a non-trivially-default-constructible class such as std...
71,254,242
71,255,972
Variadic Templates: how to "look ahead" in the arguments
I am implementing a printf version which can also handle std::string arguments. At the heart of it there are these functions: // use sprintf to transform the single format string with the value t template<typename T> std::string simpleFormat(const std::string sFormat, const T t) { size_t required = snprintf(NULL, ...
You can also provide fetchNextParam(/*empty parameter*/) // it's type need to return something since you store the value into value2 int fetchNextParam(){throw std::runtime_error("Wrong number of argument");}
71,254,325
71,255,679
Do Compilers Un-Inline?
It is fairly common knowledge that the most powerful tool in a compilers tool-belt is the inlining of functions into their call sites. But what about doing the reverse? If so, is it done? And when? For example given: void foo(int x) { auto y = bar(x); baz(y); } void bop() { int x; auto y = bar(x); baz(y); } ...
Yes, for example LLVM has a MachineOutliner optimization pass.
71,254,607
71,256,997
Strict alternation for pthreads, c++
I'm new in c++ and trying to get understand a piece of code now. It is about strict alternation for Pthreads. line 1: #include <iostream> line 2: #include <pthread.h> line 3: #include <stdlib.h> line 4: line 5: int count; line 6: int turn = 0; line 7: line 8: void* function(void* arg){ line 9: int actual_arg ...
Why the first for loop use unsigned int(line 10), is that because of the declaration of the pointer value arg in line 9? No particular reason. int or short or unsigned long long or any other integer type would have worked fine for the purpose. I can't speak to the decision process of the author of that code as far ...
71,254,831
71,254,933
const char * is incompatible with parameter of type char *, initgraph()
I have been going through this: https://www.geeksforgeeks.org/draw-circle-c-graphics/ and for some reason it seems to not be working, I'm using vs 2019, I have the dependency's, no errors there, it seems its just the two quotes in initgraph(&gd, &gm, ""); error: E0167 argument of type "const char *" is incompatible wi...
The third argument to initgraph should be a char* but in C++, "" is a const char[1]. void initgraph(int *graphdriver, int *graphmode, char *pathtodriver); You can get around that problem by creating a char[1] and use that as an argument instead: char pathtodriver[] = ""; initgraph(&gd, &gm, pathtodriver);
71,255,783
71,256,150
Creating matrix using array
I made an array matrix and used for loops, the problem is that it only displays my last input. Please refer to the sample result below. #include<iostream> using namespace std; int main() { int x = 0, y = 0; int a[x][y], i, j; cout<<"Enter number of Columns: "; cin>>y; cout<<"Enter number of Rows: "; cin>>x; ...
Just change declaration of array like this: int[x][y] to int[10][10]
71,256,115
71,256,831
How do I write a function that modifies a list such that all odd elements get duplicated and all even elements removed?
I'm trying to write a function that modifies an array list by removing even numbers and duplicating odd numbers. My code works just fine in removing the even numbers. However, it only duplicates some odd numbers. For eg. my list contains: 12 11 13 14 15 13 10 The list L after L.duplicateORremove() should contain: 11 11...
#include <iostream> using namespace std; void duplicateORremove(int list[], int length) { for(int i=0; i<length; i++) { if(list[i]%2==0) { for (int j = i; j < length - 1; j++) list[j] = list[j + 1]; length--; i-=1; } else ...
71,256,813
71,257,473
How should I initialize linked list in C++?
I have an array which I have to initialize into a list What I try to do #include <stdio.h> #include <string.h> struct data_t { unsigned int id_; char name_ [50]; }; struct node_t { node_t * next_; data_t data_; }; void initialize(node_t **, const char **, const unsigned int); int main() { node_...
You need to do something special in the case of 'first' vs 'not first', you knew this but had it wrong. On the first one (i==0) you need to set head so the caller gets the pointer to the first node on subsequent ones you have to set the prior ones next pointer to point at current. For the first one there is no prior ...
71,257,551
71,257,714
why does std::sort not require the user to specify the templated types?
If I understand correctly, in the Standard Library, there exists this definition of std::sort(): template< class RandomIt > constexpr void sort( RandomIt first, RandomIt last ); Suppose I have such a vector that I wish to sort: std::vector<int> data {9, 7, 5, 3, 1}; If this is the case, then why can I just write: st...
or is it being automatically deduced...? Yes. When a template parameter is used for a function parameter, the template argument can be deduced from the argument passed to the function. So, in this case RandomIt is deduced from the arguments data.begin() and data.end().
71,258,146
71,269,964
Unreal Engine: I cant login with EOS
I am giving a shot at trying out EOS. I am running into an error while trying to log in. I have a product and application set up in the online dev portal. Dont know if I have everything right though. I entered all the IDs and secret values into their appropriate places in the EOS plugin area in settings. I have this in...
Turns out you cant be running the game for it to work. Which is what I was doing. Running as a standalone game I was able to successfully log in.
71,258,316
71,259,992
C++ gdb pretty printing in Ubuntu 18.04 visual studio code
I am trying to make pretty printing to work on Ubuntu 18.04 from visual studio code 1.64.2. I tried to follow instructions initially from here and then the answer by Devymex as detailed in here. Then further digging up revealed that the gdb pretty printing itself is not working as I tried to build, make, and run my cod...
I found a solution as posted here. The gdb was not able to find the location where the python printers.py was located. The file was located under /usr/share/gcc/python/libstdcxx/v6/printers.py. What I needed to do is create a .gdbinit file on my home directory including the following lines of code python import sys sys...
71,258,987
71,259,305
compiler gives invalid operands to binary expression error even if there is an overloaded stream insertion operator
I'm trying to learn operator overloading and I get a below error error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Coefficient') cout << (c + 4) << endl ; I mentioned the line that causes the compiler to give an error. (last line in the main) #include <iostream> #include <os...
The definition of your stream output operator accepts a reference to a Coefficient: ostream & operator<< (ostream & output, Coefficient & holder) { output << holder.GetValue(); return output; } This works in the naive case, when you have some variable of type Coefficient and you output it. cout << c; //<-- c...
71,259,085
71,259,127
How to pass values within functions in linked lists C++
I created this code to calculate the sum of the values in a linked list entered by the user, and the expected output is to print the sum but it gives the last value and prints the wrong number of records in linked list Enter a number : 5 Enter [Y] to add another number : Y Enter a number : 1 Enter [Y] to add another nu...
In sumNodes(), you are declaring sum as a null pointer and then dereferencing it, which invokes undefined behavior. double sumNodes(Node** h) { double* sum = 0; // <-- null pointer Node* x = *h; while (x != NULL) { *sum += x->no; // <-- dereference x = x->next; } return *sum; // <-...
71,259,123
71,259,236
Passing a lambda function to a template method
I have the following templated method: auto clusters = std::vector<std::pair<std::vector<long>, math::Vector3f>> template<class T> void eraserFunction(std::vector<T>& array, std::function<int(const T&, const T&)> func) { } And I have a function that looks like auto comp1 = [&]( const std::pair<std::vector<long...
The function call tries to deduce T from both the first and second function parameter. It will correctly deduce T from the first parameter, but fail to deduce it from the second parameter, because the second function argument is a lambda type, not a std::function type. If deduction isn't possible from all parameters th...
71,259,534
71,259,859
Converting WinHttp to WinInet API POST request
I am trying to convert some HTTP request code from using the WinHttp COM interface to using lower-level WinInet calls from <wininet.h>. The COM version is working but I am having difficulty translating the calls into the WinInet API. This code works fine and gets the correct error response (as the request data is empty...
There are some mistakes in your WinInet code: the pszServerName value needs to be just the host name by itself, not a full URL. If you have a URL as input, you can parse it into its constituent pieces using InternetCrackUrlA(). the 3rd parameter of HttpOpenRequestA() is the requested resource relative to pszServerNam...
71,259,676
71,260,193
CLion greys out include
Mycode Why is #include "string.h" greyed out and does it still include it even though its greyed out. This is the only CPP source file in my project and so I know I'm not including it in another file. My TA said that its probably using the CPP version of string but later in the course it'll be a problem because we need...
It’s greyed out if clion detects that you aren’t directly using something from the referenced header. It isn’t always correct in it’s detection process. In this case, it is. There is a difference between string.h and <string> as an include.
71,259,725
71,259,909
Why the program of linked lists in C++ only displays the maximum number and ignores minimum number?
I have written this code using C++ to display the max and min number of the linked list, when I run the code I can get the maximum number but I cannot get the minimum number and its value always zero: #include <iostream> using namespace std; class Node { public: int a; Node* next; }; Node* createNode(int nu...
You must set min to a high value, if you set it to 0 then this is never true if (min > numH2->a) so do #include <limits> .... double max = 0, min = std::numeric_limits<double>::max(); or if you arent allowed to use limits (omg wtf) double max = 0, min = 999999999; actually here is DBL_MAX for you (which is what ...
71,260,420
71,260,486
C++ Structures, file does not compile, vector array has issues
I do not understand what is wrong but it seems like the problem lies with the vector, but after searching on the internet I could not solve this issue. The error from the compiler looks like this: main.cpp:25:21: error: expected primary-expression before ‘&’ token 25 | getdata(student &s,file); | ...
These are not valid function calls: getdata(student &s,file); printdata(student &s,file); They should be: getdata(s,file); printdata(s,file); That will cause other errors because your functions clearly expect a vector<student>, but only take a student. You also cannot pass fstream objects by value. They must be refe...
71,262,277
71,299,743
Is there a way make a std::string that references an externally provided buffer but not own it?
Basically if one has a preloaded buffer for a null terminated string and the length to be referenced, and wants to pass a reference to it into a method that takes a std::string & but not copy the string or have it owned, is it possible to do so ? This would only have a limited lifespan that is managed in such a way tha...
Basically, the answer is no for the non owning string. However, if the non owning criteria is not that important what you could do is to use your own allocator to reference a particular buffer. What you also can do, is to use std::pmr::string which allows you to give a custom memory_resource. The idea is as following :...
71,262,437
71,270,477
unresolved external symbol while loading HDF5 library via vcpkg to C++ vscode project
I am using visual studio project 2019- and vcpkg in order to load data to CUDA 11.6 C++ visual studio project. at the begining of the file i have : // #define H5_BUILT_AS_DYNAMIC_LIB #include <H5Cpp.h> and it do not give any errors - so I assume it was correctly loaded and integrated by by vcpkg. Also as visible at ...
The solution in my situation was simple just reinstall windows - on fresh installation I did steps as mentioned at the begining and all works now
71,262,525
71,263,352
NVidia thrust arbitrary transform with three-dimensional grid
I want to parallelize the following nested for loop on the GPU using NVidia thrust. // complex multiplication inline __host__ __device__ float2 operator* (const float2 a, const float2 b) { return make_float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); } int main() { const int M = 100, N = 100, K = 100; ...
You can simply collapse the nested loop into a single loop and use for_each with a counting iterator. In the functor, you need to calculate the three indices from the single loop variable. #include <iostream> #include <thrust/for_each.h> #include <thrust/iterator/counting_iterator.h> struct Op{ int N; int M; ...
71,263,721
71,263,844
Virtual Inheritance: Interfaces and constructors
I am using C++11. I am trying to declare 2 interfaces: B and C, which each declare some functions to be implemented by the child classes. Both interfaces rely on variables and functions which are declared in the common A class. Even this relatively simple structure leads to the diamond heritance problem.(https://www.ma...
The solutions are: Make B and C abstract classes. Or define a default constructor for A. Or call the non-default constructor of A in the constructors of B and C.
71,264,126
71,264,212
boost::threadpool::pool::wait() doesn't stop
I was trying to write some Task-Management class with C++ boost::threadpool, condition_variable and mutex. It seems the program will stop at boost::threadpool::pool::wait(), but I don't know why this happens. #include <boost/threadpool.hpp> #include <condition_variable> #include <iostream> #include <mutex> using namesp...
You enter the wait call while still holding the mutex. This will prevent other thread's from completing their work. In your particular case, the m_cond condition variable is waiting on that same mutex, so the call to m_cond.wait(lk); will be unable to return as long as the mutex is still being held by the other thread....
71,264,502
71,264,569
What C library provides memcpy?
How to figure out what gcc library provides the symbol for memcpy? memcpy is provided by the header file , but I don't know what library provides the symbol. $ objdump -ax libboost_filesystem.so | grep memcpy 0000000000000000 F *UND* 0000000000000000 wmemcpy@@GLIBC_2.2.5 0000000000000000 F *UN...
what gcc library provides the symbol for memcpy? The C standard library provides memcpy. There are some popular implementations of C standard library, on Linux it is most notably glibc (well, and musl on Alpine Linux). How do I go about getting this information? There are some approaches you can take. You can run s...
71,265,806
71,265,902
Can't find error with my code for sort 0 1 2? Segmentation fault
Could you please tell me what is the issue with my code? I am getting segmentation fault for this specific input (and more) but for few it running fine? What is it that I am missing? void sortArr(int a[], int n) { int x,y; for(int i=0;i<n;i++) { if(a[i]==0) { x++; } ...
Initialize your variables before using them: int x = 0, y = 0; If you don't initialize the variables, then they will have indeterminate values which may lead to undefined behavior, and in some cases, this can also cause errors. (For example with MSVC)
71,265,948
71,277,208
Communication failure RFID reader and Arduino uno wifi rev 2
All similar questions, don't solve my problem its possible that Rfid ≪Mfrc522.H≫ Won't Work With New Arduino Uno Wifi Rev2 ¿? SPI interface is the same that Rev 3 ¿? I have a problem with the RFID reader and Arduino uno wifi rev 2. When I connect and run the program, it says Firmware Version: 0x0 = (unknown)WARNING: ...
I have solved the problem. I will try to explain it as best as possible The location of the SPI interface in Arduino wifi rev 2 is different from versions rev 3 and 1 "One of the significant differences between the Uno and the Uno WiFi Rev2 is that the Uno has the SPI bus pins broken out on pins 11-13 as well as on the...
71,267,644
71,267,851
Conversion to signed type behavior when out of range
Converting an integer to a signed type when the source value can't be represented in the destination type is according to cppreference implementation-defined (until C++20) the unique value of the destination type equal to the source value modulo 2^n where n is the number of bits used to represent the destination type...
Neither of these quotes are meant to say that the original value is taken, the modulo operation applied, and the result used as result of the conversion. Instead they are meant to say that out of all values v representable in the destination type, the (unique) one for which the mathematical equality s + m * 2^n = v ho...
71,268,121
71,268,212
How can I call this template function correctly in main() in cpp which uses chrono library to convert a number to a date?
How can I call this template function correctly in main() in cpp which uses chrono library to convert a number to a date? #include <iostream> #include <chrono> #include <tuple> //using namespace std; // Returns year/month/day triple in civil calendar // Preconditions: z is number of days since 1970-01-01 and i...
The call to the function is not the problem. The error you get (which you should have included in the question) is because there is no predefined output operator for tuples. Though, you can print the individual members: int main(){ auto res = civil_from_days(15432); std::cout<< std::get<0>(res)<<'\n'; std::...
71,269,922
71,270,211
Overloading function where input has certain member function
I'm attempting to overload a function depending on whether the passed in sequence container has push_back as a member function. #include <vector> #include <forward_list> #include <list> #include <array> #include <iostream> template<class T, typename std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::push_...
You could use expression SFINAE for this: #include <iostream> #include <vector> #include <array> #include <forward_list> void has_push_back(...) { std::cout << "No push_back" << std::endl; } template<class T> auto has_push_back(T&& t) -> decltype(t.push_back(t.front()), void()) // ^^ expression SFINAE, only c...
71,269,953
71,270,820
How can I reverse loop over a map by value?
I need to get the pairs of the map sorted by its values, i wonder if it is posible without an temporal declaration. I know i can sort it if i make another map with the keys and values swaped, but i am searching for a better solution. I can't sort the elements afterwards because i only need extract the chars and put the...
This cannot be done with std::map. This template has an optional template argument which allows for a custom sorting, but this sorting can only be done on the map's key: template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class map; st...
71,270,337
71,270,584
Clang warns about potential memory leak when constructor involves recursion
I am writing a class where recursion is a must when writing its constructor, then clang analyzer complains about potential memory leak of this function, although I cannot see why and can guarantee that the recursion will always terminate. Here is the code: VeblenNormalForm::VeblenNormalForm(CantorNormalForm* _cnf) { ...
One problem is with exception safety. Your terms vector stores tuples of VeblenNormalForm*, which you allocate at least the second element with new. Presumably you have corresponding deletes in your destructor, but if an exception is thrown from a constructor, the destructor will not be called. In your case, you could ...
71,270,736
71,271,324
How to append a temporary vector (defined at compile time) efficiently?
I have a std::vector<char> v that is created at runtime, and I would like to append {'a', 'k', 'e', 'e', 'f'} to it. I could just do v.emplace_back on each individual letter, or I can create an l-value vector and store {'a', 'k', 'e', 'e', 'f'} and then use insert with iterators, but I don't like either of these approa...
vector::insert() has an overload that accepts a std::initializer_list as input, which can be constructed from a brace-list, eg: v.insert(v.end(), {'a', 'k', 'e', 'e', 'f'}); Online Demo
71,271,388
71,271,473
Underlining Russian comments in VS code
For me, VS code highlights comments written in Russian. It looks like this: What does it look like for me
You should install russian anguage Pack for visual studio code.
71,271,829
71,271,888
Error while linking static library to test script
I'm building a static library for a small project, and when I compile it with ar, it correctly links. When I go to include the relevant header file and link the test script to the archive; LINK = -lpthread -lcryptopp -L./path/to/archive/ -luttu r: ../inc/uttu.hpp g++ -std=c++20 rnet.cpp -o r.out $(LINK) I get linker...
After reading this SO question, I realized that I had missed an overridden virtual member.
71,271,869
71,272,015
Partial Template Specialization using enable_if
I am trying to understand how to use type traits with std::enable_if to "enable" partial specializations of a class. Here is the example code I am attempting to get workingL #include <type_traits> #include <iostream> class AbstractFoo { public: virtual const char* name() const = 0; }; template <typename T, typen...
In the declaration of Foo the second template parameter defaults to void. That means that the following variable: Foo<MyEnum> v3; is actually Foo<MyEnum, void> v3; Now the question is: does this correspond to the specialization you want? Not really, because in your specialization for enum: std::is_enum<T>::value = t...
71,271,968
71,272,000
Pointers, ampersands and pointers again?
I just cannot get my head around pointers - when and how exactly I am supposed to use pointers. No matter how many videos and literature I read on it, I just do not understand when and how I am supposed to use it. I am that dense apparently... Let us look at this example here: int main() { int* ptr = new int(10); ...
If we "draw" the first example it will be something like this: +------+ +-----+ +--------------+ | &ptr | --> | ptr | --> | *ptr int(10) | +------+ +-----+ +--------------+ So ptr is pointing to an int value (initialized 10 10). And &ptr is pointing to the variable ptr. In the second example the vari...
71,271,970
71,295,670
Is there a way to align objects in C# same way as in C++ to avoid false sharing?
I am a C++ habitat working on a C# project. I have encountered the following situation. I have class MyClass and want to avoid any 2 objects of type MyClass ever to share a cache line even if I have an array or any sequential collection of type MyClass. In C++ we can declare class alignas(hardware_destructive_interfere...
No, you can't control the alignment or memory location of classes (reference types). You can't even get the size of a class instance in memory. It is possible to control the size and alignment of structs (and of the fields within them). Structs are value types and work pretty much the same as in C++. If you create an a...
71,272,137
71,272,357
Can we update some object without stopping the program?
There is a program written in C++ and running in linux box. It has a configuration file given to it at starting point. I came to know that it can sometime support updating the configuration file without the need to stop the program. As the configuration update means eventually updating some of the objects(member variab...
Scope the configuration so that it is reread when necessary. Here's a very simple example void do_work() { Configuration config(path_to_config_file); while (not_changed(path_to_config_file)) { // do one unit of work } } int main() { while (true) { do_work(); } } Program sta...
71,272,307
71,275,334
Why is this allocating an unneeded temporary container
I am getting a warning against my foreach loop that I'm "allocating an unneeded temporary container" but I have no idea what that means. foreach(QString commandName, m_registeredResponseObjects.keys()) { delete m_registeredResponseObjects[commandName]; }; Does this means the key() method is called on each iteratio...
It means that you create a container with this statement: m_registeredResponseObjects.keys() for no good reason. This function iterates over your m_registeredResponseObjects, collects all keys and returns a container where you then iterator over just the get the values from m_registeredResponseObjects by key. This make...
71,272,341
71,272,387
C++ - Is it better to use references in for loops?
If I have something like this : vector<string> v{"lorem", "ipsum"}; Is it better to do my loop like this : for(string s : v){ ... } or like this : for(string &s : v){ ... } So my question is, does this type of loop duplicate the data (and so it's better to use a reference) or not ?
They are functionally very different Try this vector<string> v{ "lorem", "ipsum" }; for (string s : v) { s = "dd"; } cout << v[0]; for (string& s : v) { s = "yy"; } cout << v[0]; you will see that the first one gives you a copy of the element The second on a reference to the element in the vector. So which one to use ...
71,272,390
71,272,865
String offset in constructor (C++)
Anyone to give me some advice how to get this? Thank you for any advice. I am able to get this: l1 [start] l2 [start] l3 [start] l3 [end] l4 [start] l4 [end] l2 [end] l1 [end] But I need this: l1 [start] l2 [start] l3 [start] l3 [end] l4 [start] l4 [end] l2 [end] l1 [end] tasks.h #pragma once #includ...
class Logger { std::ostream& out; const std::string name; const std::string prefix; public: Logger(std::ostream& stream, std::string name); ~Logger(); Logger sublogger(std::string sub); private: Logger(std::ostream& stream, std::string name, std::string prefix); Logger(const Logger&) ...
71,272,401
71,272,545
How should I format the output?
For this code I need to be able to print the output but I am not sure how to complete this task. I can't change the main function at all and there is a certain output that I am looking for. The expected output should be formatted as the widget name, ID, then the address of the widget. I am thinking that I could use a s...
You could change getModelName to generate the output you need with the help of a std::ostringstream. Old implementation: string getModelName() const { return wModelName; }; New version: #include <sstream> // std::ostringstream string getModelName() const { std::ostringstream os; os << '\t' << wModelName << '\...
71,272,476
71,272,780
dangling reference in nested vector when parent container reallocates
thing contains 2 vectors, one of foo and one of bar. The bar instances contain references to the foos - the potentially dangling ones. The foo vector is filled precisely once, in things's constructor initializer list, and the bar vector is filled precisely once in things's constructor body. main() holds a std::vector<t...
What you are guaranteed is, upon moving a std::vector, no iterator, pointer or reference will be invalidated. This would apply to the vectors inside thing. See notes in https://en.cppreference.com/w/cpp/container/vector/vector When a std::vector grows, all iterators, pointers and references to it become invalid. So if ...
71,273,073
71,343,225
how to solve: error: global qualification of class name is invalid before '{' token
I'm trying to build https://android.googlesource.com/device/generic/vulkan-cereal but have run into an error that seems to only happen with GCC (v8.3 is what I have to work with). There are related questions, but I still don't understand what's going on well enough to fix the issue: Global qualification in base specif...
The global qualifier is the two colons at the front: struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> { ^^ But the answer was to remove all qualifiers: struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> { ^^^^^^^^^^^^^^^^^^^^^^^ So it becomes: #define REGISTER_VK_FN_INFO(coreName, allNames) ...
71,273,185
71,273,302
C++ Regex "Parenthesis is not closed." Error
In a game I'm making, I'm using a Regex expression to be able to parse in level data from a file. To test this, I'm trying to use the Regex expression (?<=(LEVEL_TYPE:\s))(\w+|[+-]*\d+) to try and get the level type data in the file which is formatted like LEVEL_TYPE: UNDERWATER This is my code: std::string RegexPat...
I can't see a reason for the lookbehind. Isn't this enough? std::string RegexPattern("(LEVEL_TYPE:\\s)(\\w+|[+-]*\\d+)");
71,273,433
71,273,677
Producing a library with a recent gcc and consuming it with an older gcc - Why are there issues despite the same C++ version?
Don't ask me why I am doing what I am doing... that would be a long story. For now, the purpose of this post is to learn and to understand why things don't work the way I expect. Possibly my expectations are wrong ? So initially I build my own SystemC 2.3.3 library from source using a recent compiler, say gcc 10.2.0. ...
Does it mean that in general, it is necessary but not sufficient for the producer and the consumer of a library to use the same C++ version (and the > same ABI) ? Correct. Backwards/forwards compatibility is not defined just by the C++ language version used when compiling source code. Backwards/forwards compatibility...
71,274,056
71,281,146
Buildroot cross-compiling - compile works but linking can't find various SDL functions
I have some code that I could cross-compile with an older toolchain that used uClibc, but the project is moving to musl libc, and I can't seem to get the code to compile with that toolchain. It always fails during the linking stage with a bunch of errors along these lines: /opt/miyoo/bin/../lib/gcc/arm-buildroot-linux-...
@user17732522 helped me work through a couple of issues: several flags were out of order: .o files should come before -l options -lfreetype must come after -lSDL_ttf) several flags were missing: -ljpeg -lpng -lz after -lSDL_image -lvorbisfile -lvorbis -logg after -lSDL_mixer -lbz2 -lmpg123 at the end This PR ha...
71,274,253
71,274,932
Could you please explain me the the working of following code?
// This is a function to check if the given array is sorted or not by recurssion #include<iostream> using namespace std; bool sorted(int arr[],int n) { if(n==1) { return true; } I am cofused here when n will reach 1 then it will return true to "restArray" after that if array is not sorted then...
As in every recursion there are two cases First the trivial case if (n == 1): An array of size 1 (ie only a single element) is always sorted. Thus it returns true and stops the recursion And if n is still greater than 1, you do the recursive call and check if the array without the first element is sorted (bool restArra...
71,274,470
71,275,001
"Guess the number" game with C++
I have an issue with a "Guess the number" game, as the title suggests. I need to write a program where the at the beginning of the execution, the program should ask the customer to enter a minimum and the maximum number and tries count (e.g the user will define with how many tries the number will be guessed by themselv...
Apart from correction in random number generation, I am only filling in the blank: /* generate secret number between "minNumber" and "maxNumber": */ randomlyGeneratedNumber = rand() % (maxNumber - minNumber + 1) + minNumber; int guessedNumber; do { std::cout << "Please, enter your guessed number: "; std::cin >> gu...
71,274,799
71,274,970
how to store 0 in MSB of int datatype in C++?
#include<iostream> using namespace std; int main() { int x = 0101; cout<<x; return 0; } The output I am getting is 101 but I want 0101 instead. what to do??
First of all, you should get 65 as 0101 is parsed as octal 101 (64+1). If you want to use binary literal, you can prepend 0b #include<iostream> using namespace std; int main(){ int x = 0b0101; cout<<x; return 0; } https://godbolt.org/z/5Pxqehz7P
71,275,447
71,275,521
std::valarray and type of iterators
Since C++11 std::valarray has iterators, provided through the std::begin() and std::end() interfaces. But what is the type of those iterators (so that I can declare them properly)? The following does not compile with a no template named 'iterator' in 'valarray<_Tp>' error: template <typename T> class A { private: std...
But what is the type of those iterators The type is unspecified. (so that I can declare them properly)? You can use decltype: using It = decltype(std::begin(ar)); It iter; Or, in cases where that's possible (not member variables), you should prefer type deduction: auto iter = std::begin(ar);
71,275,877
71,276,015
Problems while printing hollow square
I am trying to print a hollow square, I wrote the following code: #include <iostream> using namespace std; int main () { int heigth; cout << "Height: "; cin >> heigth; int width; cout << "Width: "; cin >> width; for (int i = 1; i <= heigth; i++) { for ( int j = 1; j <= width; j+...
Your code is perfectly fine and so is the value of j. The only problem is that you're printing " " while you should be printing " ". This is because " # " has 3 characters, so your space also should be 3 characters long. Final Code: #include <iostream> int main() { int heigth; std::cout << "Height: "; st...
71,275,887
71,275,912
What is the ^@ symbol at the end of my output txt file?
I wrote c++ code to read from a text file and then bash code to output it to another file (specifically './executable &> output.txt'). When I print it on the command line it looks fine, but when I check the output file, it has a '^@' symbol at the end of it.
You have a bug in your program, it's writing a nul character at the end of your file. Then whatever tool you use to check the output is using: caret notation for non-printable characters. ^@ is the notation for the nul character. We cannot tell more without seeing the code.
71,276,301
71,277,069
Drawing bezier curve using four segments
I am trying to draw a bezier curve which uses 4 control points to draw a curve. However when I run my program, after 4 clicks with mouse I only see one pixel being drawn, am I missing something in my code? How can I get this to work properly? void MyWindow::mousePressEvent(QMouseEvent *event) { if(event->button() ...
myv is local variable and you dont save its state to the new mousePressEvent Get some "debug" info and see what you receive in drawBezier function.
71,276,592
71,277,561
Is it possible to pass a reference to a consteval function and use it as additional return value?
Sometimes the result of a function can not be represented by a single return value. For example: A function that intersects two lines. One might want the function to return both the actual point of intersection as well as their relation to each other (that is parallel, identical, intersecting or skewed). Let us assume ...
You can return a std::pair<Point, Relationship>. Example: consteval std::pair<Point, Relationship> IntersectLines(const Line& l1, const Line& l2) { // replace with the real calc below, this is just for show: const Point pnt{l1.p1.x + l2.p1.x, l1.p1.y + l2.p1.y}; const Relationship rel = Relationship::paral...
71,276,707
71,276,828
How to use nested namespace to avoid ambiguity?
I have the following operators defined in the corresponding namespaces: namespace literals { constexpr ID operator"" _ID(const unsigned long long dyngateID) { // ... // return a constructed id } namespace multiplied { constexpr ID operator"" _ID(const unsigned long long dyngateID) { // ... // return ...
The name lookup rules for using namespace are such that the declarations introduced by it appear to be located in the inner-most namespace scope enclosing both the current namespace scope and the target namespace scope. Therefore it is no good to disambiguate based on the scoping of multiple reachable using namespace s...
71,277,205
71,277,963
How Does std::forward_list::sort Work in NlogN Time?
I can't imagine how to reorder a singly linked list with decent time complexity (The library says it takes "approximately" NlogN). Is there a name for the algorithm used that I could use to find educational material about it? I looked at the code in the standard library, but I couldn't figure much out other than a merg...
"Bottom up" variants of merge sort can sort a linked list in O(n log n) time and O(1) space. See the Wikipedia article. If O(1) space isn't a requirement then you can construct an array of pointers into the list, sort that using any O(n log n) sorting algorithm, and then rebuild the list from your sorted copy.
71,277,366
71,277,745
Cmake: how to delete old variables with a new build
I am trying to configure my app with cmake, which depends on cmake -DVERSION_TO_BUILD ../ In my CMakeList I wrote that checker if (NOT VERSION_TO_BUILD) message(FATAL_ERROR "Please, set VERSION_TO_BUILD") endif() In first configure all works normally, but in the next time when I try to reconfigre like cmake ../ ...
Passing a -D option during the configuration of your cmake project sets a cache variable. The cache is persisted for builds and future reconfiguration. Note that cmake does not treat cache variables that were persisted and cache variables that are passed via command line any different during reconfiguration of a projec...
71,278,317
71,278,532
What is the difference between CMAKE_CXX_FLAGS_RELEASE (cmake release flag) values?
I was working with CMake. I have seen many CMake files and found there is a different release flag value set. In one file I found: set(CMAKE_CXX_FLAGS_RELEASE "-O3") In another: set(CMAKE_CXX_FLAGS_RELEASE "-O2") and in other I found: set(CMAKE_CXX_FLAGS_RELEASE "-O1") Please let me know what is the exact difference be...
You can read about those flags here And shortly -O0, -O1, -O2, -O3 differ with the optimization level at the compile time. -O3 includes optimizations which are specified by -O2. And -O2 includes optimizations which are specified by -O1. In your projects you can use any of those. You can even use no one of those flags (...
71,278,366
71,280,081
Are all tasks that are created in worksharing loop constructs inside a parallel region sibling tasks in OpenMP?
I have this simple self-contained example of a very rudimentary stencil application to work with OpenMP tasks and the dependence clause. At 2 steps one location of an array is added 3 values from another array, one from the corresponding location and its left and right neighbours. To avoid data races I have set up dep...
In OpenMP specification you can find the corresponding definitions: sibling tasks - Tasks that are child tasks of the same task region. child task - A task is a child task of its generating task region. A child task region is not part of its generating task region. task region - A region consisting of all code e...
71,278,373
71,278,467
Confusion about [expr.static.cast]/13
I can't understand the quote (specifically, the bold part): A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A ...
does the address pointed by res (address of int) satisfy the alignment requirement of double? That would depend on the implementation. Most likely it doesn't. Typically the alignment requirement of int is smaller than that of double. For example on the x86-64 System V ABI used e.g. on Linux, int has alignment require...
71,278,421
71,280,517
What makes the calling convention different?
From my knowledge, the calling convention is depending on whether the platform is Windows or Linux. I wanna know, Compilers make the calling convention different. Platforms make the calling convention different. Which one is true? if only 2 is true, is the calling convention is defined by the platforms, and do the co...
Platforms generally define one or more "standard" calling conventions. Compilers need to follow those conventions if they want to interoperate with other tools or components on the platform using those conventions, but can use their own different calling conventions internally. The only real requirement is that any ca...
71,278,701
71,278,761
Prompt user to fill in a template?
I've never been able to find anything about this in any language, but what I want to do seems rather simple to me. I want to prompt the user for input, but have them fill in a sort of template. Let's use a simple DD-MM-YYYY date as an example. [█ - - ] █ is where the user writes. As they write, the [ and - stay wh...
Generally what you want is a text-based GUI library, such as ncurses. Doing console work is platform-specific, and every system has its own console API to do this. If you want to implement this yourself, you would have to examine what options does your target operating system give you in terms of console API, and build...
71,278,842
71,278,899
How can I find out which thread crashed inside my program?
Consider the following program: #include <atomic> #include <thread> #include <iostream> #include <string> #include <windows.h> std::atomic<int> crashId; void threadFunction(int id) { while (id != crashId) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } int* p = nullptr; *p = i...
On Windows, you can set a registry key associated with your program's name to generate a dump file when a crash happens Sample instructions here and here (I always recommend generating "full" crash dumps) With the crash dump in hand, you can load it into a tool such as Windbg or even Visual Studio to observe the call ...
71,279,031
71,302,589
Does range-v3's "sliding" view not work with lazy ranges?
I don't understand why the following code does not compile while the commented out version does work. #include <range/v3/all.hpp> #include <iostream> namespace rv = ranges::views; int main() { //std::vector<int> fives = {5,5,5,5,5,5,5,5,5,5}; //auto rng = fives | rv::sliding(2); auto lazy_fives = rv::ge...
As @康桓瑋 says in comments, the issue is that sliding_view requires a forward_range, but generate yields an input_range. A workaround is either to dump the generated range to a vector and create a sliding view of that, or I believe it is possible to use one's own generate written on top of iota like so #include <range/v3...
71,279,139
71,279,380
Do anonymous lambdas maintain their address across calls?
I have some code where I need to create unique-ids in some function to track some objects manipulated by that function. I thought about using the address of a callback which the function expects. The callbacks passed to the function are anonymous lambdas. I call this function in many different places and, in every plac...
That's by pure chance. The lambda object lives only until the end of the makeSignal call and after that the address which was occupied by the object can be reused. There is no guarantee on whether a new lambda object (or any other object) will have the same address or not. In particular that also means that after the c...
71,280,025
71,280,074
Two input types - Initializer list (C++)
I need the instance str is able to accept two diferent types. I have to use notation with {}. It should be std::initializer_list. const UTF8String str{ }; This works: class UTF8String { public: std::string inputString; }; int main() { const UTF8String str{ "hello" }; return 0; } This works: cl...
Not sure if the following meets yours needs, but it seems to work: #include <iostream> class UTF8String { public: std::string inputString; int inputInt; UTF8String(const char s[]) : inputString(s) {} UTF8String(int i) : inputInt(i) {} }; int main() { const UTF8String str1{ "hello" }; ...
71,280,161
71,287,951
Press a keyboard key by his char value C++
I would like to write a function that receives a char and presses it on the keyboard. void pressKey(const char key){ INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = //What to put here? (receives WORD of the hex val...
When simulating keyboard input for text, you should use the KEYEVENTF_UNICODE flag to send Unicode characters as-is, use virtual key codes only for non-textual keys. And you need to send 2 input events per character, one event to press the key down, and one event to release it. For example: void pressKey(const char key...
71,281,320
71,281,397
does std::map::end() return different results from different threads?
I've got this thread pool that holds a container of objects, and whenever it receives a new piece of data, it updates all the objects with the same new piece of data. The work is preallocated on the construction of the thread pool, and this work is stored in the following data member std::map<std::thread::id, std::vec...
I bet your problem is here for(unsigned i=0; i< m_num_threads; ++i) { m_threads.push_back( std::thread(&split_data_thread_pool::worker_thread, this)); most_recent_id = m_threads.back().get_id(); m_work_schedule.insert(std::pair<std::thread::id, std::vector<unsigned> >(most_re...
71,281,614
71,281,896
How do I get which() to work correctly in boost spirit x3 expectation_failure?
Calling which() in expectation_failure returns a strange std::string. How can I fix it? #include <boost/spirit/home/x3.hpp> #include <boost/spirit/home/x3/support/utility/error_reporting.hpp> #include <iostream> namespace x3 = boost::spirit::x3; struct my_error_handler { template <typename Iterator, typename Contex...
That string is the mangled type name of the parser. That's the default name if you don't supply one: std::cerr << boost::core::demangle(x.which().c_str()) << '\n'; Now it prints Live boost::spirit::x3::int_parser<int, 10u, 1u, -1> If you don't want the default, supply one. You can for rules, e.g. "test": Simplifi...
71,281,628
71,281,668
How is a read system call different from the istream::read function?
My Operating Systems professor was talking today about how a read system call is unbuffered while a istream::read function has a buffer. This left me a bit confused as you still make a buffer for the istream::read function when using it. The only thing I can think of is that there are more than one buffers in the istre...
The professor was talking about buffers internal to the istream rather than the buffer provided by the calling code where the data ends up after the read. As an example, say you are reading individual int objects out of an istream, the istream is likely to have an internal buffer where some number of bytes is stored an...
71,281,818
71,281,892
How is argv passed to the new process image with execvp()?
The man page does not seem to specify how this is done. I am confused particularly because of this line from here: The argv[] and envp[] arrays of pointers and the strings to which those arrays point shall not be modified by a call to one of the exec functions, except as a consequence of replacing the process image. Ar...
exec() functions can fail, and return an error indication. This occurs in the calling process, and the calling process continues to run. In this case, exec() simply fails, just like any other system call, like open() or read() can fail. It's just a failed system call. All that what you quoted means is that in this even...
71,281,986
71,282,054
Linked list search function not working properly
I am making a LinkedList class in C++ with its methods, like adding nodes, traversing, and searching. When implementing the search function, it seems not working properly because it does not find the value in linked list when in fact it is inside the linked list. The code is shown below. #include <iostream> class Node...
When I call the searchVal() function inside the main function it outputs value not found while value 4 is inside the linked list. What is wrong with my code? Just before you call searchVal(4) you call traverseLinkedList(), and traverseLinkedList() is implemented in such a way that when it returns, this->head will be ...
71,281,993
71,283,087
How to find the maximum difference of an array and print the numbers that gave the difference?
I've been trying to get into coding and need some help with my code. I figured out how to get the maximum difference, but I also want to print the numbers used to get that difference. For example, a-b=diff, I want to print a, b, and diff separately. My friend also challenged me to get the smaller value first, then get ...
I will address the algorithm part of this. The C++ part doesn't interest me; once you see the solution you'll know why. We must choose indices i and j such that i <= j and a[j] - a[i] is maximized. Your example sequence: a = [2, 3, 4, 15, 8, 1] Find the incremental maximum values starting from the right. (Most reade...
71,282,079
71,282,549
Why isn't break good enough?
C++ When I first ran this code with a different input value of 881, 643, 743, etc... which are all primes numbers, I got a result of "True" but when I input a higher number like 804047277, it came back as "True" when it should have been "False" #include <iostream> int main(){ int num; std::cin >> num; f...
I would correct your code like following (see description afterwards): Try it online! #include <iostream> int main() { int num = 0; std::cin >> num; for (int i = 2; i < num; ++i) if (num % i == 0) { std::cout << "True (Composite)" << std::endl; return 0; } ...
71,282,367
71,282,579
How to overload a template function where a parameter could be a vector of any kind
I have a class test which has a vector that contains a bunch of strings. I want to be able to either return the very first value in the vector as any type or an entire vector of any type. (So I could return the first value as an int or the entire data vector as a vector of ints) What I have right now does not work and ...
I found a solution from a related post which I could not find before... template <typename T> T get() { return get_helper((T*)0); } //return a single value template <typename T> T get_helper(T*) { return convert<T>(data[0]); } //return vector of values tem...
71,282,379
71,282,608
when writing a function in C/C++ that uses inline assembly (x86-64), is it safe to choose any GPRs (rax to r15) when want to?
I'm new to the concept of writing functions that contains inline assembly in C/C++ and I want to know if it's safe to use all of the available general purpose registers. (from rax to r15) In my knowledge, all of the variables/objects/data are actually stored in the main memory, and it is only loaded in the registers wh...
No, it is not correct that "data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it". Compilers work very hard to keep data in the registers and only spill to memory if required. You have to tell the compiler about all the registers you use in the in...
71,283,266
73,921,590
Auto-deduction of reference template argument from not-reference type in C++
In the following program there are struct A<int> template, and function template f<I> having const int& template argument, and A<I> function argument: template<int> struct A {}; template<const int & I> void f(A<I>) {} int main() { const static int a = 0; f<a>(A<a>{}); // ok in GCC and Clang f(A<a>{}); ...
I'm pretty sure Clang is right. According to [temp.deduct.call]/4 In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow a difference: [...] A is the transfo...
71,283,739
71,284,022
Bit fetching with type punning. Unexpected behaviour
Expected result The program simply prints anyNum in its binary representation. We accomplish this by "front popping" the first bit of value and sending it to standard output. After ≤32 iterations i (=anyNum) will finally fall down to zero. Loop ends. Problem The v1 version of this code produces the expected result (111...
unsigned b31: 1; is the least significant bit. Maybe not the last? The last. why Because the compiler chose to do so. The order is whatever compiler decides to. For example, on GCC the order of bits in bitfields is controlled with BITS_BIG_ENDIAN configuration options. x86 ABI specifies that bit-fields are alloca...
71,283,876
71,284,067
function return 2D vector gives Segmentation Fault
I'm trying to get some data and push them into a 2d vector (schedule) in getting_schedule function. In the function, when it reaches the return statement, raises segmentation fault. I tried resizing the vector but it didn't make a change. I'm aware that num_of_schedule should not be more than 479 and program raises the...
Following the recommendation of @WhozCraig And if you know the inner dimension is always 2, I'd use std::array for that. I made the following MCVE on coliru: #include <array> #include <iostream> #include <vector> int main() { std::vector<std::array<int, 2>> input; for (int value1, value2; std::cin >> value1 >> v...
71,284,058
71,284,975
Fallback for "std::ostream" and "<<" operator using SFINAE and templates in C++17
I'm using Catch2 with TEST_CASE blocks from within I sometimes declare local temporary struct for convenience. These struct sometimes needs to be displayed, and to do so Catch2 suggests to implement the << operator with std::ostream. Unfortunately, this becomes quite complicated to implement with local-only struct beca...
You can think of both methods as "operator<< on all types with some property". The first property is "has a toString()" method (and will work in C++11 even. This is still SFINAE, in this case the substitutions are in the return type). You can make it check that toString() returns a std::string with a different style of...
71,284,228
71,284,626
Writing contents of an STL Map to output stream using ostream_iterator
I have a map<string, int> object and I want to use ostream_iterator to write the contents of it to the screen or a file. I have overloaded output operator (operator<<) so that it can be used to write objects of type pair<const string, int> to an output stream, but when I try to compile the code I get the following erro...
std::ostream_iterator uses << internally. When it is instantiated for a type, << will find operator<< overloads only via argument-dependent lookup from the point of instantiation, not via normal unqualified name lookup. For type pair<const string, int> (the element type of map<string, int>) the namespace considered for...
71,284,270
71,285,042
Is there a way to access QMainWindowPrivate or QMainWindowLayout?
I'm using Qt5 and I am trying to do this: setCentralWidget(wid); ... setCentralWidget(nullptr); // i don't want it to do deleteLater() for my wid variable ... setCentralWidget(wid); The problem is that, when I call setCentralWidget(nullptr), it does deleteLater() for my wid variable. So, I found a way to use setCentra...
OP's issue is caused by using setCentralWidget(nullptr);. QMainWindow::setCentralWiget(): Sets the given widget to be the main window's central widget. Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time. (Emphasis mine.) Hence, for setCentralWidget(wid); ... setCentralWidge...
71,284,661
71,284,755
C++ Why wrong override method get called
I define 2 classes class BaseA { public: virtual void methodA() = 0; }; class BaseB { public: virtual void methodB(int val) = 0; }; Child inherits 2 Base Class class Child : public BaseA, public BaseB { public: void methodA() override { printf("Child A\n"); } void methodB(int val) override ...
You should just do this: void callBaseB(BaseB *p) {p->methodB(0);}. If you want to keep void *p as a parameter, you need to cast it to exactly Child * first. Either: BaseB *b = (Child *)p; b->methodB(0); Or: Child *b = (Child *)p; b->methodB(0); Alternatively, cast to BaseB * before converting to void *. Then castin...
71,284,775
71,284,912
SFINAE does not work in a non-type template class
I want to use SFINAE to select specific function to be compiled in a template class with non-type argument, here is how i do it: #include<iostream> #include<type_traits> template <bool T> struct is_right { template <class Q = std::bool_constant<T>> typename std::enable_if<std::is_same<Q, std::bool_constant<true...
The default template parameter for the second check function is wrong, it should be std::bool_constant<T> and not std::bool_constant<!T>. The call is_fs.check() has no matching function, because you're testing is_same<bool_constant<false>, bool_constant<true>> in the first overload and is_same<bool_constant<true>, bool...
71,285,018
71,285,146
Why is stod() shortening the number I am converting from string to double?
I am trying to convert a string to a double, however when i use stod() the double has lost some of it's decimal places. Here is the relevant code : cout << line3 << endl; float temp = stod(line3); cout << temp << endl; For example, when line3 is "4.225308642", temp outputs as 4.22531. What is causing the s...
There are two aspects to consider here. First, formating on a IOStream by default has a precision of 6 significant digits. That explains your result. You can increase the precision with the manipulator setprecision. Then, float by itself has a limited precision of about 6 decimal digits as well. Although you can displa...
71,285,200
71,285,218
Code not running from terminal in vs code
Image is showing that when i used terminal to run the code, it wont run. code is running perfectly in output section, opened vs code after a month and shows this type of output in terminal
You're just compiling the code, not running it. To run the code, type the following: ./exe_name.exe ..or in your case: ./tut4.exe ./tut5.exe If you're using a mac machine, just replace .exe with .out