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
66,103,132
66,103,238
error: cannot convert 'int* (*)[10]' to 'const int* (*)[10]'
I am having a problem passing a non const 2D array of pointers as const argument for a function. But I am getting an error. I don't understand why. // Online C++ compiler to run C++ program online #include <iostream> void test(const int *arrayPtr[][10]){} //void test(int * const arrayPtr[][10]){//Works DO NOT USE //...
There are two errors in your code. Your passing in a int* array[][], not a const int* array[][]. So change the function parameter to int* array[][10]. You are subjected to array decay. To resolve this, you should pass in the array by reference. To this your function parameter should be like this: int* (&arrayPtr)[][10...
66,103,202
66,139,231
How to downsample a point cloud while maintaining its order? (PCL C++)
I want to downsample incoming pointclouds by using the passthrough filter provided by the pcl library and also maintain the order of the given clouds. My current solution is as follows: using point_type_colored = pcl::PointXYZRGB; using point_cloud_colored = pcl::PointCloud<point_type_colored>; point_cloud_colored::Pt...
You are looking for the function setKeepOrganized. Providing true will set each filtered point to NaN instead of removing the point. You can also change the value to set it to with setUserFilterValue, but keeping it NaN has the benefit that other PCL algorithms won't consider these points for their algorithm.
66,103,694
66,103,743
|= (or_eq) order of evaluation in C++
I was trying to find the answer to the following question, but was unsuccessful. I have the expression involving bit AND and bit OR (everything unsigned long): A |= B & C What is the order of evaluation in C++? Is it A = A | (B & C) or A = (A | B) & C? Or it depends on the compiler version? Thanks.
With the compound assignment operators (op=), the expression E1 op= E2 becomes E1 = E1 op E21. That means for your code that E1 is A and E2 is B & C so the result would be A = A | (B & C)
66,103,890
66,104,065
fstream not reading character by character but whole numbers
void Map::LoadMap(std::string path, int sizeX, int sizeY) { char c; std::fstream mapFile; mapFile.open(path); int srcX, srcY; for(int y = 0; y < sizeY; y++) { for(int x = 0; x < sizeX; x++) { mapFile.get(c); srcY = atoi(&c) * 32; map...
Your code invokes Undefined Behaviour as atoi expects a null-terminated string, which &c is clearly not, it's a pointer to a single character. Why do you need atoi in the first place? It's a function from C for converting strings like atoi("532532"). If you want to convert a single char to int you can just do it like t...
66,104,113
66,104,447
Reference becomes dangling in expression template
I wrote an expression template code, but I had an error. And the following is just a minimal reproducible example. #include <iostream> template<typename Derived> class VecExp { public: double operator[](int i) const {return static_cast<Derived const&>(*this)[i];} }; template<int n> class Vector : public VecExp<Vec...
v + v is an expression of type VectorSum<Vector<16>, Vector<16>>. v + v + v is an expression of type VectorSum<VectorSum<Vector<16>, Vector<16>>, Vector<16>>, where the type for the first template parameter is significant: VectorSum<VectorSum<Vector<16>, Vector<16>>, Vector<16>> // ^^^^^^^^^^^^^^^^^^^^^^^^...
66,104,772
66,104,882
Will the thread die after his caller will finish the job?
One of my class functions running in infinity loop and accepting clients with the function Server::accept(). So my question is: will userThread die after accept() will finish his job, or it will run forever because of the infinity loop in second function that calls accept() forever? void Server::accept() { // notic...
userThread has been detached so the system thread will run until clientHandler() finishes or throws. Server::accept() will return immediately.
66,105,099
66,122,294
How to link an external library in Qt Creator when LIBS += -L"..." doesn't seem to work?
I've been trying to use the Intel Open Image Denoise library in my code but still have no luck as of now. Apparently it seems that I am not linking the library properly. Here's what I've done so far: after compiling OIDN I moved the oidn directory to the directory where my path tracer code is and did the following in m...
All the previous answers/comments were correct. The weird thing about my case was the symlinks of the libraries in the build directory were not valid and were not pointing to the right files. The output of ls -lh /home/Warrior/Desktop/pathtracer/oidn/build was as follow: total 160K drwxrwxr-x 4 amir amir 4.0K Feb 4 00...
66,105,153
66,520,979
Non blocking pseudo terminal, recovery after POLLHUP
I create a new pseudo-terminal by opening /dev/ptmx with open() function and O_RDWR | O_NOCTTY | O_NONBLOCK flags. Then I use poll() function to wait for incoming data from the remote end: struct pollfd pollFileDescriptors[numberOfTerminals]; for (unsigned terminalIndex = 0; terminalIndex < numberOfTerminals; terminalI...
The issue can be easily solved by reopening the pseudo-terminal right after it is created. The POLLHUP won't appear as long as at least one writer exists so we can do this by ourselves with open() and ptsname(): // Create a new pseudo terminal int fileDescriptor = open("/dev/ptmx", O_RDWR | O_NOCTTY | O_NONBLOCK); gran...
66,105,279
66,105,491
Error when casting derived class to protected base interface in std::make_shared
I have this code: #include <memory> class SomeInterface { public: virtual void VirtualMethod() {} virtual void PureVirtualMethod() = 0; }; class SomeInterfaceDependent { public: explicit SomeInterfaceDependent(SomeInterface* a) : a_(a) {} private: SomeInterface* const a_; }; class Implementation : ...
Is it the std::make_shared bug? No. Why? std::make_shared is not a friend of Implementation, and therefore it doesn't have access to its non-public bases, and therefore it cannot implicitly convert the pointer.
66,105,635
66,105,951
How to extern declare an extern "C" variable
I wants to export a global variable from dll I define the global variable like below. Assume this variable is defined in A.cpp extern "C" __declspec(dllexport) int A; Meanwhile, within the dll, another source file B.cpp wants to use and modify this value. I am wonderring how to declare the variable within B.cpp before...
Per [basic.def]/2.2, a declaration of an object at namespace scope is a definition unless: it contains the extern specifier (9.2.1) or a linkage-specification19 (9.11) and neither an initializer nor a function-body, ... 19 Appearing inside the brace-enclosed declaration-seq in a linkage-specification does not affect w...
66,106,098
66,106,405
Is it proper to use qualified lookup with no namespace on the left of the scoping operator (::name) in general code?
This sample code from cppreference.com: #include <iostream> int main() { struct std{}; std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct ::std::cout << "ok\n"; // OK: ::std finds the namespace std } shows how ::name (no namespace on the left side of the scoping operator) refers to a ...
Argument-dependent lookup only works for unqualified function calls, which excludes using the nested-name-specifier ​:: if wanting to leverage ADL; [basic.lookup.argdep]/1 When the postfix-expression in a function call is an unqualified-id, Using qualified names with a leading :: also forces developers to include pos...
66,106,178
66,152,275
How to implement Priority Preemptive Scheduling (similar to interrupts) with threads in C++
I want to write a C++ program on Windows (but preferably to support cross-platform) in which I have two threads that are scheduled based on Priority Preemptive Scheduling - which is like an interrupt behavior (when the interrupt occurs, the main thread pauses wherever it is and only when the interrupt thread goes back ...
I found several solutions for this issue and I thought I'd share them here for everybody else. Throughout stackoverflow I found others who asked similar questions to this one and there are several possible solutions. Possible Solutions to Implement interrupt behavior with threads: Force a context switch on your thread...
66,106,213
66,106,301
Ambiguity when using << >> operators
The << and >> operators have two meanings in C++, bit-shifting and stream operations. How does the compiler resolve this ambiguity when the meaning isn't obvious from context? Take this line for example: std::cout << 1 << 2 << std::endl; Would the output be 12, as if the second << were treated as a stream insertion, ...
operator >> and operator << have left to right associativity. That means that with the addition of some parentheses, the actual expression is ((std::cout << 1) << 2) << std::endl; and here you can see that with each call, the stream object, or the return of the stream expression, is used as the left hand side of each...
66,106,518
66,106,647
Can coroutine return std::future? (unable to find the promise type for this coroutine)
I have tried to compile coroutine example from the CppCon presentation https://youtu.be/ZTqHjjm86Bw?t=560 Unfortunately compilation fails: $ g++-10 -pedantic -Wall -std=c++20 -fcoroutines main.cpp main.cpp: In function ‘std::future<int> compute_value()’: main.cpp:7:16: error: unable to find the promise type for this ...
There are (basically1) no standard library types in C++20 that implement the necessary coroutine machinery to make coroutines work. This includes std::promise<T>/future<T>. You could write wrappers for them that implement the coroutine machinery though. 1: There are support types like std::suspend_always/never which ha...
66,106,750
66,107,203
What is struct Cleaner <T*> mean?
What is struct Cleaner <T*> mean? Is it specific the second Cleaner can only accept the type of pointer? what is the terminology of this usage in C++? template <typename T> struct Cleaner { static void clean ( T x ) { } }; template <typename T> struct Cleaner<T*> { static void clean ( T* x ) { if ( x ...
The idea is to provide two behaviours for the function release() depending on the type of its argument (pointer or not). We could also have written two overloads template <typename T> void release2(T) { } template <typename T> void release2(T *x) { delete x; } In your example, the distinction is done on two versions o...
66,106,819
66,106,898
How to declare a multidimensional array member in a C++ class or struct?
I have created a data structure that contains a multidimensional array member. The dimensions of this array are ultimately supplied by user input and are known at the construction of the struct, but not before. I have provided a minimal working example that hopefully demonstrates the problem: struct MyStruct{ int r...
How to declare a multidimensional array member in a C++ class or struct? Like this: struct MyStruct{ float data[42][123]; }; The dimensions of this array are ultimately supplied by user input This is not possible if the array is a member variable. The size of an array variable must be a compile time constant i...
66,107,226
66,107,282
Why `std::unordered_map::erase(key_type const&)` return number of removed elements?
Recently I went to use std::unordered_map::erase, and see the function has some overloads: Link to cppreferences iterator erase( const_iterator pos ); (1) (since C++11) iterator erase( iterator pos ); (1) (since C++17) iterator erase( const_iterator first, const...
Because there is also unordered_multimap where several elements can have the same key. Returning the number of erased elements makes perfect sense for multimap, multiset, unordered_multimap and unordered_multiset. The returning of the number of elements rather than just bool for the non-multi containers is a way to mak...
66,107,281
66,109,399
How to map different C++ classes to enum class values
I produce messages and each is receive by one object, chosen by an enum class member: enum class ReceiverID { R1, R2, MAX_NUM_RECEIVERS }; struct Msg { ReceiverID _receiverID; Data _data; }; The receiving classes are stored in an array. The enum member indexes the array to access the receiving obj...
For on-the-fly creation of objects we could go for some kind of a factory method, e.g.: //In the Base class: static Base* createReceiver(ReceiverID recvID) //static member function { switch (recvID) { case ReceiverID::R1: return new R1Receiver(); case ReceiverID::R2: return new R2Receiver(); ...
66,107,436
66,107,680
How to delete a specific line/string from a text file (fstream/c++)
This function is meant to remove a specific line from a database text file. void removeEntry() { fstream outputFile("outputFileName", std::fstream::in | std::fstream::out | std::fstream::app); fstream database("database", std::fstream::in | std::fstream::out | std::fstream::app); string line; string fin...
Let's think about the structure of your program: while(getline(database, line)){ if(line.find(find) != string::npos) { var = line; cout << line << endl; string choice{}; cout << "Is this the line you want to delete[y/n]: "; cin >> choice; if (choice =="y") ...
66,107,524
66,108,208
What are the units of QPdfDocument::pageSize?
QPdfDocument (5.15.2), in the QtPDF module (part of QtWebEngine), seems to not be fully documented yet (presumably because it's fairly new, first appearing in 5.14). What are the units of the size returned by QPdfDocument::pageSize() (don't bother checking those docs, it's not there)? It appears to be some reasonable (...
Looks like the implementation is done with PDFium. Qt calls FPDF_GetPageSizeByIndex and the docs state the height/width is in points: // Function: FPDF_GetPageSizeByIndex // Get the size of the page at the given index. // Parameters: // document - Handle to document. Returned by FPDF_LoadDocument...
66,107,834
66,108,256
Using boost::chrono::system_clock to get time causes linker error
I have program which is linking to system,chrono and thread in boost. But simply adding auto now = boost::chrono::system_clock::now() gives me a linker error. Following is my main.cpp #include <iostream> #include <boost/chrono.hpp> #include <boost/circular_buffer.hpp> int main(int argc, char* argv[]) { boost::circu...
After add_executable, add target_link_libraries: add_executable(TestProgram TestProgram.cpp) target_link_libraries(TestProgram ${Boost_LIBRARIES})
66,108,656
66,122,285
How to draw Qt widgets in a QTabWidget in non-selected tabs?
My QTabWidget has 2 tabs on launch. Tab 1 is the one that's opened upon launch. Tab 2 contains some widgets of which I take the QSize to later draw similar elements in newly opened tabs. The problem is that currently the size of the elements is 640x480 (apparently the default value), if tab 2 was not shown yet. Once ...
For performance reasons, a QWidget's size() method is not guaranteed to return its expected value until after the QWidget has actually been laid out and shown. If you need to know in advance what a QWidget's size would be, you can call its sizeHint() method instead, and that will force the calculation to be performed r...
66,108,967
66,135,133
OpenGL flickering issue in rendering
I have an OpenGL rendering issue and I think that is due to a problem with the Z-Buffer. I have a code to render a set of points where their size depends on the distance from the camera. Thus bigger points means that are closer to the camera. Moreover in the following snapshots the color reflect the z-buffer of the fra...
As already updated the issue is called Z-fighting when choosing the wrong near and far panes in the projection matrix. If they are to far away from your objects, there is only a very discrete number of values for z left. Then the drawing is detemined by the call order and processing order in the shaders, since there is...
66,109,234
66,109,744
(Ray tracing) Trouble converting to screen coordinates, objects being stretched
I followed along with Ray Tracing in One Weekend and managed to get the final output but I wanted to understand more about creating a camera and "painting" the screen since he didn't go over it much. When I tried using a different way of creating a camera by spheres actually get elongated, making them look like more li...
You shall define const float img_ratio = (float)img_width/img_height; Which, for a 640x480 image, would be 1.333 rather than 2 as in your code. Also in screenCords you subtract 1.0f from x but not from y. It creates a tilt-shift effect.
66,109,275
66,111,482
Using Boost Python, I can wrap C++ overloaded operators "+=", "-=", "*=", but not "/="?
Boost Python has a pretty straightforward method of wrapping overloaded operators. The tutorial for exposing C++ classes, methods, etc. at boost.org (https://www.boost.org/doc/libs/1_66_0/libs/python/doc/html/tutorial/tutorial/exposing.html) gives this example: The overloaded C++ operators for an example class, FilePos...
Python 3 changed the way the division operator is defined, and Boost.Python's auto-generated version uses the old Python 2 style for in-place division, which no longer works. This seems to be an oversight, since the non-in-place version has been updated to Python 3's __truediv__ magic method. There is an open GitHub ...
66,109,866
66,609,767
How to recursively print the contents of a vector in C++
I want to have a function that takes in a template for a std::vector and prints whatever is in the vector provided it is a datatype allowed in std::cout. I believe this needs to be recursive since what about a vector of vector of a vector.... For example, given a 1d vector, template< typename T> void PrintVector(T vec)...
First let's clarify some things: std::vector is a template, but std::vector<T> is a class (generated from the template, but that is irrelevant). Also the T in the std::vector<T> is a type not a template. I also want it to take in a reference to the vector within the template It doesn't work like that. You simply make...
66,109,949
66,110,880
How to avoid ambiguity within symbol table lookups?
I have a rather rudimentary symbol table to map a identifier to a symbol, storing VariableSymbols, MethodSymbols, BuiltInTypeSymbols etc. This has worked fine for my simple interpreter. However now I want to implement more advanced symbol types such as tuples (say - TupleSymbol) which stores an array of BuiltInTypes. I...
If you allow duplicate symbol names for different types, as most languages allow, for example the same name for a variable and a function you need to go with different maps for each type. Also you probably need to iterate over some symbol type, for example built-in symbols - it's a good idea to create a map for them as...
66,110,056
66,198,990
How to read input from a C++ file with K lines of input and N elements on each line from stdin
I am just learning C++ and I want to read input from the file "gymnastics.in" with K lines of input, and N integers on each line, N is the same for all the integers. The input would look something like this: 3 4 4 1 2 3 4 1 3 2 4 2 1 3 The first line containing K, and N respectively. And then three lines after that wi...
You're almost there. All you have to do in your inner for loop is extract your number from the stream and add it to your temp vector. Then you can add the temp_vector to nums. Since you know it's always an integer, you could declare say an int temp_val variable and read all n numbers on a line one at a time. Then use v...
66,110,152
66,170,716
Passing overloaded function and args to template function
I'd like to send the two overloaded fun()s to one template that handles them plus their arguments. This is my attempt so far: #include <vector> #include <iostream> using namespace std; class Demo {}; template<typename Function, typename... Args> void call(Function func(Args...), Args &&...args) { func(forward<Ar...
The reason for compilation error is that the compiler does not know which fun overload you are actually going to use. To resolve this error, you just need to cast your function parameter to the right overload like: int main() { call( static_cast< void(*)(int, int, int) >( fun ), 1, 2, 3 ); call( static_cast<...
66,110,709
66,395,045
How to create a portable executable with allegro 4.4.2
So I am creating a C++ program using the allegro version 4.4.2 library and I need to be able to produce an executable package which I can submit to a course instructor and have run on his computer without issues. I am developing the program using DevC++. If I am understanding this correctly so far, I need to link to a ...
So I just ended up using a dynamically linked version of my program and including the appropriate .dll files which turned out to be a lot less work than I thought it would be. Basically I just had to ensure the allegro-4.4.2-md.dll from the bin folder was included in the folder with the executable. I then sent off the ...
66,110,899
66,111,202
If a floating-point number is representable in my machine, will its inverse be representable in my machine?
Given some initialized object x of type double that stores a positive value, I want to find the smallest double v such as 0 <= v < 1/x. It seems fairly obvious that I could write double v = DBL_EPSILON;, but, if x is big enough, could it happen that v end up being bigger than the real value 1/x because it's so small th...
I will assume double is IEEE 754 binary64. If a floating-point number is representable in my machine, will its inverse be representable in my machine? Not necessarily, for two reasons: The inverse might not be a floating-point number. For example, although 3 is a floating-point number, 1/3 is not. The inverse might...
66,111,254
66,111,323
Pass C++20 Templated Lambda to Function Then Call it
I'm trying to pass a templated lambda to a function and then call it with a template parameter, to enable specialization of that function for custom types. But when I try to call the lambda I get this error: error: invalid operands to binary expression Here's a godbolt link for anyone who wants to play around with this...
The issue is that lambdas are not class templates, they're just regular classes where the member call operator, i.e. operator() is templated. When the template parameters are deduced for a generic lambda, this distinction is not noticeable (which is a very good thing). So in your example, lambda is not a class template...
66,111,441
66,111,682
Can compiler combine multiple malloc calls into one?
Let's say we have the following two pieces of code: int *a = (int *)malloc(sizeof(*a)); int *b = (int *)malloc(sizeof(*b)); And int *a = (int *)malloc(2 * sizeof(*a)); int *b = a + 1; Both of them allocate two integers on the heap and (assuming the normal usage) they should be equivalent. The first se...
In reality, no, the compiler will never combine the 2 malloc() calls into a single malloc() call automatically. Each call to malloc() returns the address of a new memory block, there is no guarantee that the allocated blocks will be located anywhere close to each other, and each allocated block must be free()'d indivi...
66,111,709
66,160,072
Bazel linker not finding function defines
I've been able to make a fair amount of progress in trying to add Bazel build files to enable the building of the gennorm2 tool in ICU. Here is my work-in-progress PR using the Bazel target //icu4c/source/tools/gennorm2. I'm currently getting stuck when running bazelisk build //icu4c/source/tools/gennorm2 --verbose_fai...
A teammate was able to take a look and help me reason through the errors and ultimately fix them. The first thing is to acknowledge that it is indeed a linker error, which can see by noticing the error message references the linker program ld. This is important because we previously spent time in the wrong place by deb...
66,111,896
66,112,170
The program always displays 0 matches even if some numbers match
The program should have an array of five integers named lottery and should generate a random number in the range of 0 through 9 for each element in the array. The user should enter five digits which should be stored in an integer array named user. The program is to compare the corresponding elements in the two arrays ...
Your program always display 0 digit match because matchCounter function works wrong. you can write like this. int matchCounter(int lotto[], int input[], int match) { for (int i = 0; i < SIZE; ++i) { if (lotto[i] == input[i]) ++match; } return match; } You can also pass match by ref...
66,111,930
66,112,124
How can I get a const value for the size of a string in C++?
I need to be able to use ImGui textboxes, however they don't take const char* or std::string so I need to convert a string to a char array. The problem with this is, however, that I need my char array to be the same size as the string (+1). I get an error saying it needs to be constant value in declaration but I need t...
Use a local char buffer to accomplish what you want. There's no OS call to allocate memory, and you should have an idea of what you want your maximum allowable input to be. This function doesn't really do anything. After you get the input, you'll need to copy the data into a std::string or something else to do stuff wi...
66,112,095
66,112,417
How to handle key_down and key_up of char in WndProc?
I'm trying to handle key up and key down messages for arrow keys and A, W, S, D characters. I can handle arrow keys' up and down behavior using WM_KEYUPand WM_KEYDOWN. But when I try to handle above characters' up and down behavior, it doesn't work properly. I tried WM_KEYUPand WM_KEYDOWN to handle chracters. But after...
According to WM_DEADCHAR: WM_DEADCHAR specifies a character code generated by a dead key. A dead key is a key that generates a character, such as the umlaut (double-dot), that is combined with another character to form a composite character. So the WM_DEADCHAR message is not what you think corresponds to the WM_CHAR ...
66,112,482
66,113,162
In Visual Studio, what's the common structure for 3rd party files outside of c++ project director such as glad.h and glfw3.lib?
I was following the tutorial of learning OpenGL here, and got "glad/glad.h no such file or directory" error. My structure of 3rd party files: C:\Deleveper\Libs (directory) --glfw3.lib --glad (directory) ----glad.h --KHR (directory) ----khrplatform.h In the project property setting, I have added "C:\Deleveper\Libs" int...
The common structure of libraries has three important folders: include, lib, and bin. Include will have the headers, lib will contain the library files you link to your program at compile time, and bin contains the dll file that go in the same directory as your exe. Moving your dll file to the right directory can be do...
66,112,596
66,112,936
When is std::codecvt<char, char, std::mbstate_t>::always_noconv() required to return true?
Does the standard (C++17) mandate that std::codecvt<char, char, std::mbstate_t>::always_noconv() returns true for all locales, or for locales provided by the implementation, or only for the C locale, or something else? The C++ standard does have something to say about it. From section 25.4.1.4 of C++17: codecvt<char...
Ok, as was pointed out by cpplearner, the standard (C++17) also has the following text in the requirements for do_always_noconv() in section 25.4.1.4.2: codecvt<char,char, mbstate_t> returns true. If the text had instead been: The specialization codecvt<char,char, mbstate_t> returns true. I would no longer have any...
66,112,748
66,112,856
Why do we get sizeof( &arr ) and sizeof( arr ) / sizeof( int ) different?
using namespace std; int main( ) { int arr[ 5 ] = { 1 , 2 , 3 , 4 , 5 } ; cout << sizeof( arr ) << endl ; cout << sizeof( &arr ) << endl ; return 0 ; } why do we get answer 4 for sizeof( &arr) ,if &arr is a pointer to array why are we getting size 4 when size is 5
Difference is that arr is an array, while &arr is a pointer to the array. Compare to: #include <iostream> using namespace std; int main( ) { int arr[5] = { 1, 2, 3, 4, 5 } ; // array of 5 integers int (&ref_arr)[5] = arr; // reference to array of 5 integers int (*ptr_arr)[5] = &arr; // po...
66,112,914
66,112,956
Doesn't output text from function to console?
Why doesn't my GetMeshLocation() function output a nested function to it Print() with the text Object location is (23x, 61y, 80z)? The compiler passes successfully. #include <iostream> class Mesh { public: void GetMeshLocation() { Print("Object location is (23x, 61y, 80z)."); return; } ...
You're using a variable that is initialized after its usage, till that it's empty. Thus, you need to put this syntax: _print = print; Before using the cout statement in the method The method should look like this: const void Print(const std::string print) { _print = print; std::cout << _print << std::endl; ...
66,113,223
66,113,458
Even and Odd vector position
So I am trying to change my int vec1 that is populated with all zeroes. What I am doing for every even number I would make it to a 10 and for every odd would be an 11. But I am unsure how to do that and unsure how to print it out. What I thought was to use the % when finding out indices like vec1[0], vec1[2], and so fo...
You can achieve this like this: First you have to loop over the v, to check if we are on even index or odd index, we simply take mod with 2 of i. If it is zero then it pushes 10, if not then 11. And in the second loop it simply print the array. #include <iostream> #include <vector> using namespace std; int main() { ...
66,114,111
66,114,138
C++ assignment precedence
To make things more meaningful, basically for the below two cases. I somehow imagined them to be similar, right hand side first. But "=" just passes value through "==" returns the result of the comparison "true" and then converts to 1. So they are actually NOT similar? int hehe = haha = 3; int hehe = haha == 3; //---...
But why the result of (haha = 3) is not 1 indicating something like the operation is successful? Because that is not how the C++ language specification says things works. Instead, the result of an assignment is the value that was assigned. In this case haha = 3 evaluates to 3. In C++, we never have "this operation wa...
66,114,232
66,114,278
How to decay rvalues reference type whilst preserving lvalue references in C++14?
I have the following C++14 lambda https://godbolt.org/z/aexxTY #include <boost/optional.hpp> int main(){ auto foo = [](auto && t) { using T = decltype(t); return boost::optional<T>(std::forward<T>(t)); }; // This is fine because i is lvalue auto i = 10; foo(i); // This f...
You could use std::is_rvalue_reference together with std::conditional, both from the <type_traits> header. auto foo = [](auto && t) { using Orig = decltype(t); using T = std::conditional_t<std::is_rvalue_reference<Orig>::value, std::decay_t<Orig>, Orig>; return boost::optional<T>(std::forward<T...
66,114,655
66,114,815
Difference between std::lock_guard and #pragma omp critical
Let's consider some code to safely increment a variable in a for loop with multiple threads. To achieve this you have to use some kind of lock mechanism when incrementing the variable. When I was searching for a solution I came up with the following to solutions. My questions are: Are they equally good or does one of ...
The critical section serves the same purpose as acquiring a lock (and will probably use a lock internally). std::mutex is standard C++ feature whereas #pragma omp critical is an OpenMP extension and not defined by the standard. The critical section names are global to the entire program (regardless of module boundari...
66,114,660
66,202,984
How to write an outlook add-in using unmanaged code (C++/Delphi)?
I developed an Outlook Add-in using C#. I want do completely avoid being punished for slowing down Outlook startup. Therefore I would like to create a "Loader"-Add-in. It's written in C++/Delphi and does nothing but enabling the C#-Add-in after itself has beeing loaded. There are a lot of hints on stackoverflow, etc. b...
Of course - just implement a creatable COM object that (besides IUnknown) also exposes _IDTExtensibility2 interface - see https://learn.microsoft.com/en-us/dotnet/api/extensibility.idtextensibility2?view=visualstudiosdk-2019. You will also need to add its class name to HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\Outloo...
66,115,189
66,115,275
Mysterious error in this C++ pointer program in visual studio
I have a written code for finding missing elements below. #include <iostream> int main() { int arr[7] = { 1,3,5,7,9,11,13 }; int max{ arr[0] }, min{ arr[0] }; for (int i = 0; i < 7; i++) { if (max < arr[i]) max = arr[i]; if (min > arr[i]) min = arr[i]; } int*...
max is 13. So ptr's length is also 13. int* ptr = new int[max]; for (int j = 0; j < 7; j++) ptr[arr[j]] = 1; this is accessing ptr[13], which is out of bounds.
66,115,771
66,115,969
Whats the meaning of gcc/g++ error 'implicitly-declared' constructor is 'deprecated'?
I am trying to chase down errors coming out of upgrading my build system OS and gcc version with it to 9. I can demonstrate it with the following code. class Cl { private: float f; public: constexpr float GetF() const { return f; } Cl& operator=(const Cl& other) { ...
You are using a copy-constructor for lcl(cl) although you didn't define one but you defined a user-defined assignment operator. You can fix it by adding a user-defined constructor: class Cl { private: float f; public: constexpr float GetF() const { return f; } constexpr C...
66,115,837
66,115,955
Why does shrink_to_fit (if the request is fulfilled) cause reallocation?
Given a container v with v.size() == 3 and v.capacity() == 5, my understanding is that a call to v.shrink_to_fit() can be fulfilled and, if it is, it causes v.capacity() to become 3. However, this comes at the cost of a reallocation. Why? Isn't it possible to free the unused memory without reallocating a chunk of memor...
The container does not allocate/deallocate the memory on itself, but it is it's allocator who does it. For the (vector's) allocator to be able to deallocate the memory, it needs to be provided the exact the same pointer as the pointer to the memory it has allocated for the vector's data. At this is the begin of the vec...
66,115,927
66,116,548
How to get Windows-1252 character values in c++?
I have a weird input file with all kinds of control characters like nulls. I want to remove all control characters from this Windows-1252 encoded text file, but if you do this: std::string test="tést"; for (int i=0;i<test.length();i++) { if (test[i]<32) test[i]=32; // change all control characters into spaces } I...
32 is a signed integer, comparing the char with the signed integer is performed by the compiler as signed: E9 (-23)<32 which return true. Using an unsigned literal of 32, that is 32umakes the comparison to be performed on unsigned values: E9 (233) < 32 which return false. Replace : if (test[i]<32) test[i]=32; By: if (...
66,116,533
66,118,009
Linkingoption for mariadb connector c
Sooo, I am writing a C++ application to receive Data from a Socket and save it into a MariaDB database. I included the MariaDB connector c library from the libmariadb3 package and it worked without a problem. When compiling the program I had to add the linking option -l mysqlclient. Compile command would be: g++ main.c...
There is no workaround, you need to link with the libraries you want to use. In CMake, target_link_libraries simplifies this and adds the needed include paths and libs when compiling/linking.
66,116,827
66,117,038
C Dynamic linking and security of signed tokens
I have a question regarding the security and integrity of my application when it comes to dynamic linking. I'd like to ship an application to my client together with libcrypto.so that does some signature verification of some JWT tokens. Now ideally I'd like my client not to "hack" my security (I don't want to allow him...
As a software developer, you rely on the security of the computer and operating system on which the software will run. If the user with admin right want to hack your software, you mostly can't do anything about it. Just think that it's not only about replacing the dynamic library, but he (the user) could even modify th...
66,117,214
66,136,708
How to use the WinRM C++ API in a simple example
why is my code failing to run a simple executable using WinRM's C++ API? //main.cpp int main() { ShellClient *shellClient = new ShellClient(); //Set up the shell client here and connect to the localhost. //This seems to be working fine because I'm handling every //possible error code, and none of t...
I wasn't aware of this so can't comment on whether it's common knowledge but Microsoft have a nifty error lookup tool where you can enter an error code (after converting it from a normal number to hexadecimal) and it tells you what it means. In this case, 2150859250 (803381F2 in hex) corresponds to: ERROR_WINRS_IDLET...
66,117,725
66,118,331
Cross-platform issues or what is the alternative to QtConcurrent :: run?
I need to run the function asynchronously in a separate thread, I used QtConcurrent :: run everything was fine when I tested windows, but as soon as I ran the same code on linux, it started to work synchronously. Using qt4.8 and c++98 :c Testable code: void myRunFunction(QString name) { for(int i = 0; i <= 1000; i+...
Based on the comments it appears that the number of threads in the global QThreadPool instance may be limited, by default, to a single thread due to constraints imposed on the VM. To counter that you can simply set the thread count explicitly using... QThreadPool::globalInstance()->setMaxThreadCount(4);
66,118,163
66,118,319
How to delete all implicit (default) methods of class in C++?
C++ compiler in certain conditions for class adds implicit default constructor, copy constructor, destructor, conversion operators, assignment operators, etc. And other implicit methods. How do I disable/delete all possible implicit methods in shortest way possible? I don't want my class to be un-copyable, I want just ...
You may go for a mixin approach. Define the cumbersome class once class DeleteAllSpecialMemebers { private: DeleteAllSpecialMemebers() = delete; DeleteAllSpecialMemebers(DeleteAllSpecialMemebers const &) = delete; DeleteAllSpecialMemebers & operator = (DeleteAllSpecialMemebers const &) = delete; DeleteA...
66,118,429
66,118,551
problem during typecasting during function calling
In the program i am converting the character datatype into integer but it is displaying the ASCII code of the character, why? what should i do to print 4 as output? void fun(int x) { cout<<x; } int main() { char ch='4'; fun((int)ch); return 0; } I have tried changing the parameter from 'int x' to 'char x' and then t...
Casting a char to int will do what it should, cast the stored value into an integer. When you say char ch='4';, the variable holds the ASCII value of '4', it does not store the integer value 4. So casting it will not give you the integer value 4. To get the integer value of ch (get 4 from '4'), we can subtract the inte...
66,118,580
66,194,929
clang-format: Use custom style if file doesn't exist
I want to format code using a custom style if .clang-format doesn't exist. Is there any way to do so? I used --fallback-style but it fails. clang-format -i --style=file --fallback-style="{BasedOnStyle: google, IndentWidth: 4, ColumnLimit: 100}" a.cpp It raises an error: Invalid fallback style "{BasedOnStyle: google, I...
I doubt there is a command line option to use another style if .clang_format file doesn't exist. The option -fallback-style does work only with predefined styles, which are llvm, chromium, mozilla, google, webkit, gnu, microsoft. Also there is none to skip formatiing. You can use -fallback-style=google for example. How...
66,118,799
66,254,115
What's the age before __STDCPP_DEFAULT_NEW_ALIGNMENT__ appears
Taking Windows as example that __STDCPP_DEFAULT_NEW_ALIGNMENT__ is 16. When I override new operator, compiler calls non-alignment version new. This indicates that compiler assumes new operator should allocate memory align to 16. (Please correct me if I already wrong). However __STDCPP_DEFAULT_NEW_ALIGNMENT__ appears si...
The fundamental alignment is represented by alignof(std::max_align_t). It means that any supported alignment is less than this value. std::max_align_t was introduced by C++11. It means that any type of alignment requirement can be met as long as alignof(std::max_align_t) is followed. The introduction of __STDCPP_DEFAUL...
66,119,532
66,119,950
Can I ask the compiler to forbid defining a generic version of a member function of a templated class?
Suppose I have an interface I, and a templated class C which implements the interface: class I { public: virtual int foo() = 0; }; template<typename T> class C : public I { public: int foo() override; }; I want there to be only two instantiations of C, with types T1 and T2. I want to specialize foo() for each of ...
You should add the generic definition yourself: template<typename T> int C<T>::foo() { static_assert(!std::is_same_v<T,T>, "Missing specialization of C<T>::foo()!"); return 0; } Since the condition for the static_assert is always false, everyone trying to use C with a not yet specialized type will get the static asser...
66,120,117
66,120,276
why it only "see's" the first row?
So I have been trying to make a simple program to count how many "au" there is in a text. Ran into a problem when everything seems working, except that it stops counting after the first row. Here's the program: #include <iostream> #include <fstream> using namespace std; int au (); int main(){ cout << au() <<endl; ...
The simple answer is that you read 2 chars at time (the 2 in.get() ) so basically are reading the file this way: given abcaud in the file, you read ab ca ud edit for clarification: the problem is that while reading the file, you read 2 chars, check if they matched an then read the next ones. This way you read chars at ...
66,120,432
66,130,468
How to include an open source library into C++ project?
I am trying to use an open-source library into my project, specifically this one here. I have followed the installation guidelines and installed it globally with sudo cmake --build "build" --config Release --target install And I could see that the library is installed in /usr/local/lib, now back to my own C++ code, wh...
Thanks for the many helps, I have finally figured it out. Go to build settings in Xcode and add both header and library search path And then go to linking, add linkers, for my case it looks like this
66,120,740
66,144,507
Why do we need the highlighted sentence below in [dcl.init]/(6.2)?
[dcl.init]/(6.2) If T is a (possibly cv-qualified) non-union class type, its padding bits are initialized to zero bits and each non-static data member, each non-virtual base class subobject, and, if the object is not a base class subobject, each virtual base class subobject is zero-initialized; AFAICT, the sentence a...
The writing of a technical specification is a bit like programming. [dcl.init]/6 can therefore be thought of as a kind of function: the function which performs zero-initialization on an object. This function gets called when a complete object is zero-initialized. Here's some pseudo-code for the general structure of [dc...
66,121,444
66,122,211
using QT Process or threads to run functions?
I wanted to run few functions using different threads or QProcess or something which is more effective and also provide good performance. I am trying to build one gui for calibrator and as soon as I press calibrate button it needs to calibrate. For calibrating, I have some function to do that. However it takes some tim...
A QProcess is meant to run an external process (an executable if it may be clearer). This is not what you need in my humble opinion. What you may need is to use QThread to run your function of Calibration. As you have already looked at the documentation, let us provide you some examples of how to execute functions usin...
66,121,565
66,121,634
Generate random long long C++
int generator I currently generate deterministic pseudo-random ints using this code: #include <chrono> #include <ctime> #include <random> #include <stdint.h> const uint32_t CurrentTime = static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count())...
the documentation says that the template parameter can be long long long long Min = 3; long long Max = 6; std::uniform_int_distribution<long long> Distribution(Min, Max-1); long long Result = Distribution(Mersenne);
66,122,085
66,122,358
How to remove all instances of a duplicate from a vector<int>
I've been trying to solve an "easy" leetcode question for two hours now where I need to remove every instance of an int that appears more than once then add the non dupes together. I've tried about 10 different ways and I can only get it to go down to one copy of each int. Here is the nicest solution I've written, but ...
NlogN complexity, you avoid needing to pre-sort: Godbolt #include <set> #include <vector> int main() { std::vector<int> nums = {1,2,2,3,5}; std::multiset<int> m (nums.begin(), nums.end()); std::size_t sum = 0; for (const auto& elem : m) { sum += m.count(elem) == 1 ? elem : 0; } } Upda...
66,122,109
66,126,629
How to check if any key is pressed in pixel game engine
I know that a specific key, for example a can be checked as if (GetKey(olc::A).bPressed){ //do stuff } but how can I check if any key is pressed. Example if (any key is pressed){ //if i pressed a, it should output a. std::cout << the key which was pressed was a; } ...
Turns out there is no way provided by the engine to do this, but there is a work-around provided to me by some awesome people. Its to set the make you own key char map and store them in a vector with appropriate values. Then iterate through that vector to see if any of those keys are pressed. struct KeyCharMap { o...
66,122,174
66,122,688
How to skip names in File?
I am writing a code to read a text file from my computer and I need to successfully skip names that are italian. The text file follows the pattern of composer name, then opera name, then language. This is my code so far: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstrea...
If the language is not "Italian", the next thing in the loop you expect to read a composer, but instead in that place is opera. After that you expect to read a language but there is a composer. It gets worse if is not "Italian" again: while (getline(fileIn, composer)) { getline (fileIn, language); if (language...
66,122,225
66,122,367
How to have c++ 20 on windows?
I am working on windows 10 and currently have gcc8 installed on my system but the thing is #include <execution> cannot work with this version of gcc. So, I want to have gcc 9, but I have downloaded mingw 8 (the newest version) which probably have the latest gcc. But this version of mingw does not have an installer. I c...
you can use msvc which supports c++20 features https://en.cppreference.com/w/cpp/compiler_support#C.2B.2B20_library_features
66,122,268
66,122,599
C++. Assignment operator of a pointer array in class
My task is to create the class stack using a pointer array. However, when I assign a variable of type stack to itself, the elements of the stack (or array) become garbage. So here's the code (fields are array, stack_size and stack_capacity): stack& operator= (const stack& old) { if (stack_size != old.stack_size) {/...
Since *this and old are the same object, this->array is the same as old.array. This means that you're copying the uninitialized data in array = new int[stack_capacity]; into itself. The traditional and quick fix is to check for self-assignment first, if (this == &old) return *this; A more modern solution is the "...
66,122,332
66,134,346
Matrix multiplication in c++ in Android Studio
I'm trying to do matrix multiplication in Android Studio and want to use c++ for the speed benefit. I found the library xtensor and think that it will be useful but I cant get working. I tried putting the header files into the cpp folder but then they dont have access to the base library dependencies and I've been rese...
How can I install the xtensor library in android studio or is there some other way? I wanted to avoid using for loops for the calculation but if there's no other possibility I guess I have to.. xtensor project is based on cmake which is supported by AndroidStudio(gradle) so you can easily use it for NDK build. It tak...
66,122,433
66,123,038
glDrawElementsInstanced getting only one vertex position and texture coordinate
I am trying to use instanced rendering to render a simple mesh (a textured quad made of 2 triangles) multiple times in a single draw call. When rendering, I don't see my instanced meshes, and when analyzing a frame with renderdoc, all vertices positions are set to the position of the first vertex of the mesh, same for ...
You have misunderstood what glVertexAttribDivisor does. glVertexAttribDivisor is used for instance attributes. Instance attributes are attributes that change for instances, not the vertices of an instance. The vertex coordinate, color and texture coordinate are not instance attributes, but vertex attributes. Hence you ...
66,122,767
66,124,073
Largest Rectangle in Histogram using stack
Hey friends i am solving this problem but i got an runtime error and not able to figure out that why i am getting this error for the input [0,0] my code gives right answer if the input is not [0,0] in 0ms response time.. This question is related to the stack data structure. Here is a screenshot and the link of the ques...
As if every element in vector h is the same, your code will crack. In your first 2 for loop has 3 if statements, when it runs into the second element in vector h, if h[0] = h[1] then all 3 if statements will not be satisfied, so left and right vector will only have 1 element, in the last for loop you run through all el...
66,122,935
66,125,289
C++ - I want to combine data from pointer of vectors of strings into a static vector of strings in the following format
My vector of strings with dynamic size based of what user wants std::vector<std::string>* allTags = new std::vector<std::string>[tvSize]; Filling the allTags variable for (unsigned int i = 0; i < tvSize; i++) allTags[i] = ParseData(vals[i]); Now suppose that size of allTags pointer is 3 and following are the valu...
You want something like this: vector<string> function(int lvl) { if (lvl == tvSize) return vector<string>(0); vector<string> r; // some compilers will complain because of () vector<string> v = funtion(lvl + 1); for(int i = 0; i < allTags[lvl].size(); i++) { if (v.size() != 0) ...
66,123,242
66,134,515
How to convert QList to QSet in Qt 6
I am porting my application to Qt 6 and as I am reading documentation I see that classes are cleaned up a lot, QList and QVector are unified, QStringList is now alias to QList<QString> and so on. But now this gave me one problem. In my code (which is Qt 5) I am converting QStringList to QSet to eliminate duplicates fro...
I must admit that I'm still on Qt5. However, QList and QSet remind me strong to std::list and std::set. For the latter, there was already another (and more flexible) way to achieve such things: using construction with iterators. A short check in the Qt6 doc. convinced me, this should work in the Qt classes as well: QSe...
66,124,020
66,124,248
atomic operations and visibility in C++
Consider the below code: static std::atomic<int> x; // Thread 1 x.store(7, std::memory_order_relaxed); // Thread 2 x.load(std::memory_order_relaxed); Further assume that Thread 2 executed the load a few cycles after Thread 1 executed the store. Is it guaranteed that Thread 2 would read the value 7 on all hardware pl...
Yes, it will be visible. It has become somewhat a common question regarding relaxed memory orders and what they do in contrast to stronger memory orders. A memory order stronger then memory order relaxed does the following two things: synchronizes non atomic data prevent reordering of instructions in the same thread ...
66,124,021
66,124,275
Sum of last N nodes of a linked list
The problem given is that we have to find the sum of the last n nodes of a linked list. Example if the list is this:- 1->2->3->4->5->6->7 and n is 3 then answer should be 18 (from 5 + 6 + 7). Here is my solution -> Node*temp = head ; int sum = 0;int cnt = 1; if(n<=0){ return 0 ; } while(cnt!=n) { tem...
There is some issues with your code, namely 1) In the first while(cnt!=n) you are not considering the case when temp is null, which leads to problems when you do: temp = temp->next Moreover, you want to sum the last 'n' elements but you are actually trying to sum the elements after the first 'n' elements. This proble...
66,124,034
66,124,083
Why is this C++ working? (declaration/definition of variables)
Why can I declare and define 3 variables inside the for-loop [for (auto vall: k0L){...}], at each iteration of the for-loop? The compiler doesn't complain when I do g++ code.cpp. I know a variable can be declared only once. I know I cannot write int a = 5; int a = 6; inside the main() scope. However, this is what I am ...
Because that’s how scopes in C++ work: the scope of these variables is the body of the for loop. In other words: they are created inside each loop iteration and live until the end of that same iteration. It’s entirely equivalent to how you can declare local variables inside a function even if you call a function multip...
66,124,794
66,125,733
Is Clang or GCC correct in rejecting/accepting this CTAD code?
Clang and GCC disagree on accepting this code. What is the standard required behavior? #include <utility> #include <iostream> #include <vector> int main() { std::vector pairs = {std::pair{1,11},{2,22}, {3,33}}; for (const auto& p: pairs) { std::cout << p.second << std::endl; } } Note: I know this ...
The process of CTAD is largely defined by [over.match.class.deduct]. Broadly speaking, the overload set is all of the accessible constructors of the type, plus any deduction guides. And the overload set is resolved per this rule: Initialization and overload resolution are performed as described in [dcl.init] and [over...
66,124,936
66,125,145
MSVC's standard library does not define spaceship operator for std::string, std::shared_ptr, and so?
I'm trying to make my program multi-platform, originally written for Linux. MSVC (I'm using 19.28) is told to have spaceship operator support from version 19.20 (https://en.cppreference.com/w/cpp/compiler_support/20), but it seems like it does not define this operator for std::string, or std::shared_ptr (probably for m...
MSVC supports the operator<=>, but that doesn't mean they've implemented for all libraries. From your link to cppreference, under the C++20 library features section, it actually shows that MSVC does not have P1614R2 (Adding <=> to the standard library) It has partial support for P0768R1 (Library support for operator<=>...
66,125,296
66,125,413
C++: Unhandled exception: std::out_of_range at memory location
Currently learning C++ building a little program that takes in movie names, stores them in a vector and then outputs it based on user input. The problem is I made a function for displaying the movies list. Now every time I run that function I get this error: Unhandled exception at 0x769DA842 in ConsoleApplication2.exe:...
In the for loop, the condition movieList.size() > 1 is always true (if you have more than one movie in the list), so you are incrementing i beyond the size of the list, accessing to memory out of the range of the vector. This example should work, since the variable i is only used in the body of the loop till it reach m...
66,126,210
66,126,792
Combining predicates in a functional way and allowing short-circuiting to work
Foreword I asked a similar question: say I have a predicate auto p1 = [](int x){ return x > 2; } and a predicate auto p2 = [](int x){ return x < 6; }, how do I combine p1 and p2 to obtain p1and2 such that p1and2(x) == p1(x) && p2(x)? The answer was use boost::hana::demux (refer to the linked question for details). The ...
I've just realized that an ad-hoc lambda to do what I described is actually very terse: #include <assert.h> #include <optional> constexpr auto all = [](auto const& ... predicates){ return [&predicates...](auto const& x){ return (predicates(x) && ...); }; }; constexpr auto has_value = [](std::optional<...
66,126,750
66,127,106
Trim both path and extension from __FILE__ compile-time
---- Question ---- I'm attempting to convert the file name "/path/to/Module.cpp" into a const char* holding the value "Module" compile-time. This helps me print ergonomic logging in a microcontroller. I use GCC 8.3. There are lots of fine examples on how to strip only the path component, e.g. an adaptation of this answ...
The following "works", but it's not perfectly clean. Cleaning it up is left as an exercise. Anyway, it may show you how to do it: #include <cstdio> constexpr unsigned long filename_we_size(const char *path) { // I know - some C pointer stuff. I don't know which C++ functions are // constexpr which are not, an...
66,126,777
66,127,302
Pause threads from a different thread, and then wait until all are paused
I want to pause a number of worker thread from a creator thread. This can be done with a conditional variable, as seen in this code. #include <iostream> #include <vector> #include <thread> #include <condition_variable> #include <atomic> #define NR_ITERATIONS 3 #define NR_THREADS 5 class c_threads { private: bool ...
There might be a better way, but I think you're going to have to do something a little more complicated, like create a gatekeeper object. Worker threads generally work like this: while(iShouldKeepRunning()) { ... lock the mutex ... look for something to do ... if nothing to do, then wait on the condition } ...
66,126,802
66,127,488
Is there a way to use STL iterators as arguments without a template?
I have a class A that implements a function foo which takes as arguments two iterators (from any stl container). For what I've seen, the common approach is to use a template, as shown here: class A{ public: template <typename It> void foo(const It& begin, const It& end){ // do stuff ...
You can use a specific iterator type, such as std::vector<int>::iterator. Note that this may be different to std::vector<int>::const_iterator, std::deque<int>::iterator and std::vector<unsigned>::iterator, so you can end up with a multitude of overloads. You can also use a type-erasing iterator, such as the iterators f...
66,126,893
66,126,991
CRTP and downcasting
Following up a similar question in previous post about downcasting and type safety , I wonder if the following example creates undefined behavior. An instance of Base class has been created. No dynamic binding take place. However, in the Base::interface function the instance of the Base class is casted to an instance...
There is no Derived that this new Derived * could point to, so it is definitely not safe: the cast itself has undefined behaviour, as described in [expr.static.cast]§11 (emphasis mine): A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a...
66,127,016
66,127,272
How do I initialize an element of an array of superclasses with an instance of a subclass in C++?
Say I have Animal animals[100]; And now, at run-time, I want to initialize one of these to be a new instance of Cat, a subclass of Animal. How do I do this? I thought maybe I could do animals[0] = Cat("Fluffy") but this doesn't seem to work. My understanding of how a constructor works in C++ is that space for the obj...
This is wrong because animals[0] = Cat("Fluffy") calls Animal::operator=(const Animal&), which forgets about all the Cat-specific parts of the object. Poor Fluffy has been sliced Generally if you want a heterogeneous array, you would need to store an array of pointers to the base class, or preferably a smart pointer, ...
66,127,093
66,127,583
Short circuiting in fold expressions
This is a self triggered question based on a self-answer I gave here. This seems a pretty convincing explanation of why short-circuiting of logical operators is available in fold expressions, and of the fact that wrapping a fold expression in a function with a variadic argument seems to be non short-circuting (in fact,...
... && ps(x) with four predicates a, b, c, d expands to ( ( a(x) && b(x) ) && c(x) ) && d(x) which leads to this order of evaluation: a b c d ps(x) && ... expands to a(x) && ( b(x) && ( c(x) && d(x) ) ) which leads to the same order of evaluation: a b c d This does not change anything about short-circuiting; as soon ...
66,127,149
66,127,286
std::chrono::duration passed as a method parameter
I have this method: string tpToString(const system_clock::time_point &tp) { string formatStr { "%Y-%m-%d %H:%M:%S" }; return date::format(formatStr, date::floor<microseconds>(tp) ); } This method produces a string such as: 2021-02-09 20:53:10.123456 That's great. It uses Howard Hinnant's date library. I just ...
If you make tpToString a template you can allow the caller to choose the accuracy at compile time. template <typename FloorType = microseconds> string tpToString(const system_clock::time_point& tp) { string formatStr{ "%Y-%m-%d %H:%M:%S" }; return date::format(formatStr, date::floor<FloorType>(tp)); } int main...
66,127,320
66,127,395
Pointer Constructor in C++
I'm asked to write a SmartPointer class. One of the constructors takes a pointer variable, and I assume that I should simply copy the pointer to the relevant variable. But when I try, I get a segmentation error. Here is the content of the header file and my implementation of Pointer Constructor. class ReferenceCount { ...
You appear to be writing something similar to shared_ptr<T>. For a shared_ptr-like smart pointer, each smart pointer has both a pointer-to-object and a pointer-to-control-block. When you are constructed with a pointer-to-object, you are responsible to create the control block. In your case, your control block name is R...
66,127,392
66,127,554
Output the repetitive ASCII diamonds
My desired output looks about like this: ** ** ** ** ** **** **** **** **** **** ****** ****** ****** ****** ****** ******** ******** ******** ******** ******** ********** ********** ********** ********** ********** ********** ***...
I would redesign your app so you have a function that prints one line of the diamond: So the initial program looks like this: void printDiamondLine(int line) { // You write this part } int main() { for(int loop = 0; loop < sizeOfDiamong; ++loop) { printDiamondLine(loop); std::cout << "\...
66,127,641
66,128,465
shorthand std::array literal parameter
I've been trying to write some shorter code that still uses std::array but I'm not sure how to get the deduction to work in my favor. Is there a way to write this that is equally as short(readable) as the vector version? #include <array> #include <iostream> #include <vector> template <std::size_t SIZE> void afunc(cons...
std::array and std::vector have the same size() and operator[] members, so you could roll your 2 functions into 1 function: template <typename Container> void func(const Container &c) { for(int i = 0; i < 10; ++i) { std::cout << c[rand() % c.size()]; } } std::array<std::string_view, 2> a{"1","2"}; ...
66,128,119
66,128,147
Accessor function for std::mutex
There are two classes. Class A has a private member std::mutex m_. Class B has an instance of class A as its member. The goal is to let class B to be able to use m_ (which is in class A). I tried adding an accessor method in class A as below, but it gives error no matching function for call to 'std::unique_lock<std::mu...
Is above error because std::mutex is non-copyable? That is correct. A std::mutex cannot be copied or moved. What is the suggested way to expose the std::mutex in this case? In this case, you can just return by reference like std::mutex& getMutex() { return m_; } and use it like std::unique_lock<std::mutex> lo...
66,128,167
66,128,252
return value from possible type in std::variant through std::visit
I am trying to wrap my head around std::variant and std::visit and I am trying to come up with a method to specify a couple of types that I would like my variable to hold (which would go into my std::variant) and then retrieve stored data through a std::visit. Consider the following example: #include <iostream> #includ...
The error messages suck, but the issue here is that all of the alternatives of the variant must have the same return type in the visitor. Your AllTypesOperatorOverload does not obey this rule, returning a double and an int, which are not the same type. The newest versions of libstdc++ or any version of libc++ produce m...
66,128,585
66,128,777
How to pass template function to POSIX threading (pthread)
I am in trouble with the usage of a template function with POSIX threading. As a programming language, I am using C++98, and as a threading infrastructure, I am using POSIX threading (<pthread.h>). My environment does not support the standard threading (<thread>) Normally, we can pass parameters to pthreads as below: #...
Since you are not calling hello() directly, the compiler can't deduce the template parameter for you, so you have to specify the template parameter explicitly. You also need to change hello() to match the signature that pthread_create() is expecting (like your non-template example does), unless you type-cast the functi...
66,128,626
66,130,471
Does the bitwise OR operator do anything special to a 2's complement byte?
So I need to dig a bit into number representation for sensor readout over I2C -- and for the readout of an I2C accelerometer there is one step I just cannot wrap my head around (bold part): In order to read them all, we start with the first register, and the using the requestionFrom() function we ask to read the 6 reg...
Bitwise OR just means outputting the inclusive OR of each bit of the inputs. It has nothing to do with 2's complement So if we have two bytes X and Y with bit patterns abcdefgh and ABCDEFGH respectively, the result of X | Y << 8 is like this Y 00000000ABCDEFGH Y << 8 ABCDEFGH00000000 X 00...
66,128,719
66,128,825
C++: How to create a member 2D-array of size determined at runtime
I've tried to declare an empty pointer to a pointer, assign to it pointer to allocated during construction memory and iterate over it doing the assignment again, but I'm missing something. Also I wonder if it's possible to do this with the std::array. Attaching the code: // Cell.h class Cell { char contents; b...
Also I'm curious if it's possible to do this with the std::array You can not, the size of an std::array is specified as a template parameter and your array is dynamically sized. Rather than dealing with raw pointers, you should look at std::vector for dynamically sized arrays: std::vector<std::vector<Cell>> cells{nco...
66,128,828
66,142,660
Problem with using header of <execution> in c++
I have gcc 10.2.0 on windows 10. so, is implemented in this latest version of gcc. The problem is when I copy the example code from the following link :https://docs.w3cub.com/cpp/algorithm/reduce, it says: std::execution has not been declared. Any idea? #include <iostream> #include <chrono> #include <vector> #include ...
Many compilers default to older C++ modes for backwards compatability. Enable C++17 in the settings to use newer features.
66,128,948
66,129,078
Correctly passing an object to pthread_create() using void*
I've been following the instructions on creating POSIX threads, and closely following their example Pthread Creation and Termination. According to their example, they pass a long integer value to pthread_create(), which results in a call similar to this one: pthread_create(&thread, NULL, do_something, (long*)testVal); ...
void* do_something(void* range) { (Range)range.print(); ... ...but am confronted with a bunch of type errors. This is because your Range class isn't convertible from a pointer to void. Question How do I pass the Range object to pthread_create()? By using indirection. pthread_create accepts pointer to an object...
66,129,925
66,130,842
Is there something like std::remove() which does not preserve the order of retained elements of a vector?
In C++14, I have a std::vector of values for which I want to remove all elements that match a given value and I do not care about preserving the order of the elements after doing the remove. The specification for std::remove provides that the relative order of the elements that remain is preserved. Is there a built-in...
Is there a built-in algorithm to do something like a std::remove but that does not preserve the order? I wish to do this since it is less work to just swap elements from the end of the vector into locations to be removed std::partition() is an algorithm that will do what you are asking for. Instead of the value to re...
66,130,242
66,130,519
Is there a way to print a string-type variable in C++ via the ncurses library?
I have been constantly trying to print out a string type variable via ncurses' functions since "cout" is not working by the time I am typing in the "initscr()" command. I have created an array of string variables and I am trying to print each and every single one of the strings out on a window. The result I am getting ...
The menuShow uses the same type formatters as printf(). So "%s" is expecting a C-String (or char*). You are proividing a std::string which is not the same. int menuShow(string *choices, int opt, WINDOW *menu) ... STUFF mvwprintw(menu, i + 1, 1, "%s", choices[i]); ^^^^^^^^^...