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
72,457,380
72,457,456
stack overflow, when i using Detours to intercept CreateFileW
i want to intercept win32 api CreateFileW, but i meet an error "stack overflow". i don't know what happend, can someone help me? error: Exception thrown at 0x00007FFA76204170 (KernelBase.dll) in detoursExample.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000094A6A03FF0). Unhandled exception at 0...
In newCreateFile, you need to call oldCreateFile, not CreateFileW. The way you're doing it, your hook ends up calling into itself forever.
72,458,092
72,463,889
Can't figure out how to pass arguments to a bind function
After several tries of trying to pass arguments in a scroll event function, It's not working. I'm making a custom scroll panel and need the bind function to trigger when the user scrolls down, in order to do that I need to pass variables that are going to be used inside the panel. This wasn't an issue with the wxScroll...
Bind() does support passing pointers to arbitrary "user data", but this is not the best way to do it and is only supported for backwards compatibility and to ease migration of the very old code predating Bind(). Instead, consider making the data you need part of some object -- typically something deriving from a window...
72,458,457
72,458,743
This is a program to recursively calculate the reverse of a string but it's not printing anything
What I have done is created a global array to store the reversed string. #include <bits/stdc++.h> using namespace std; char arr[10]; int c = 1; string Reverser(string z) { arr[c] = z[(z.size() - c)]; c++; if (c == (z.size() + 1)) { return 0; } else { Reverser(z); } ...
You can use a std::stringstream and pass it by reference in your recursive function. Also, you can pass the string by reference. #include <iostream> #include <string> #include <sstream> void reverse(const std::string& a, std::stringstream& ss, unsigned int pos) { ss << a[pos]; if (pos == 0) return; re...
72,459,809
72,460,017
Is false sharing the case with heap memory?
As I know, false sharing occurs when several threads try to read small and adjacent pieces of data which are placed within the same cache line: #include <omp.h> #define NUM_THREADS 4 int main() { int arr[NUM_THREADS]; # pragma omp parallel num_threads(NUM_THREADS) { const int id = omp_get_thread_num...
Memory is memory. To the cpu an array on the stack is exactly the same as an array on the heap. So any false sharing problem remains the same.
72,460,511
72,499,230
Error while computing Surface Normal using Camera Intrinsic Matrix in OpenCV
I am trying to compute surface normals in OpenCV. Well, this should be quick and easy but I don't know why it is not working. Below is the code: > import cv2 > img_color = cv2.imread("color.png") > img_depth = cv2.imread("depth.png", cv2.CV_16UC1) # millimeters > img_color.shape, img_color.dtype ((720, 1280, 3), dtyp...
There is a function called depthTo3d in OpenCV to do convert depth image into 3D points. Please see the following code snippet: In [1]: import cv2 In [2]: cv2.rgbd.depthTo3d? Docstring: depthTo3d(depth, K[, points3d[, mask]]) -> points3d . Converts a depth image to an organized set of 3d points. . * The coordin...
72,460,975
72,461,759
Assembly 32bits sum of elements of two vectors
I have a problem with sum of elements of two vectors type double which are the same size. Code always returns 0. #include <iostream> using namespace std; int main() { int n = 5; double* tab = new double[n]; double* tab3 = new double[n]; for (size_t i = 0; i < n; i++) { tab[i] = 1; ta...
Sadly i am not on windows, so i had to modify the code to use g++ instead of msvc, but i used intel syntax assembly too. During debugging it turned out that fadd instructions had no effect. I fixed it by adding qword ptr before the [edi + 8 * eax - 8] and [esi + 8 * eax - 8] to tell assembler to use pointers to an 8 by...
72,462,450
72,462,472
Return lambda with capture from a function in c++11
The standard 5.1.2 6 says that there is a conversion function from a lambda expression without capture to the corresponding function pointer type. What about lambdas with capture? The following code compiles without warnings. Does this lead to undefined behavior? std::function<void()> makeFucntion(int& parameter) { ...
std::function<void()> is not a function pointer. std::function<void()> can store more than just function pointers. If you'd try to return a function pointer void(*)() then the code would fail to compile, because lambdas with capture do not have a conversion to function pointer. As parameter is passed and capture by ref...
72,462,468
72,462,509
Does placement-new into the same type still require to manually call the destructor?
Context I'm trying to get a grasp on the placement-new mechanism since I never have had to use it. I'm trying to understand how to properly use it out of pure curiosity. For the question, we will consider the following code base for illustration purposes: struct Pack { int a, b, c, d; Pack() = default; Pack...
Yes, you must call the destructor. It's irrelevant whether the old object is of same type or not. Only thing that matters is whether the type of the old object is trivially destructible. If it is, then there is no need to call the destructor. If it isn't, then you must call the destructor before reusing the memory. Exa...
72,462,807
72,463,536
If arr[3] is an array and ptr is a pointer, then why do arr and &arr give same result but ptr and &ptr don't
I am a beginner to data structures and algorithms, started studying the pointers now and before asking the question here I read this recommended post but I couldn't understand it so I am asking the query here. I have been told by a friend that array's name is a pointer to the first value in the array, as arr returns th...
Arrays are not pointers! Arrays do decay to a pointer to their first element in all sorts of circumstances. For example std::cout << arr; actually prints the memory address of the first element of the array. std::cout << &arr; prints the memory address of the array. As the address of the first element is the same as th...
72,462,904
72,463,449
boost: parse json file and get a child
I am trying to pars a JSON file with the following function: std::string getFieldFromJson_data(std::string json, std::string field) { std::stringstream jsonEncoded(json); // string to stream convertion boost::property_tree::ptree root; boost::property_tree::read_json(jsonEncoded, root); if (root.empty(...
Use a JSON library. Property Tree is not a JSON library. Using Boost JSON and JSON Pointer: Live On Coliru #include <boost/json.hpp> #include <boost/json/src.hpp> // for header-only #include <iostream> #include <string_view> auto getField(std::string_view json, std::string_view field) { return boost::json::parse(jso...
72,463,355
72,463,629
What exactly is std::function<void(int)> doing in this code?
I've recently come across some code for the inorder traversal of a binary search tree which is as follows: void binary_search_tree::inorder_traversal(bst_node *node, std::function<void(int)> callback) { if (node == nullptr) { return; } inorder_traversal(node->left, callback); callback(node->va...
https://en.cppreference.com/w/cpp/utility/functional/function has a pretty good description: Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions, lambda expressions, bind expressions, o...
72,463,360
72,463,589
std::strcpy and std::strcat with a std::string argument
This is from C++ Primer 5th edition. What do they mean by "the size of largeStr". largeStr is an instance of std::string so they have dynamic sizes? Also I don't think the code compiles: #include <string> #include <cstring> int main() { std::string s("test"); const char ca1[] = "apple"; std::strcpy(s, ca1...
strcpy and strcat only operate on C strings. The passage is confusing because it describes but does not explicitly show a manually-sized C string. In order for the second snippet to compile, largeStr must be a different variable from the one in the first snippet: char largeStr[100]; // disastrous if we miscalculated t...
72,463,846
72,486,802
Argument of type "float" is incompatible with parameter of type "const void *"
I am trying to design a basic matrix class having data allocated in device. I am having some problems when inserting an element into the matrix given its row and col. This is my actual code: template <typename CellType_> class CUDAMatrix { public: using CellType = CellType_; CUDAMatrix(size_t rows_, size_t cols_) ...
cudaMemcpy requires pointer as src and dst, _data[index] does not return a pointer. The right way should be: cudaMemcpy(&_data[row * _cols + col], &val, sizeof(CellType), cudaMemcpyHostToDevice)
72,464,347
72,464,544
Can you use a constructor as a UnaryOperator?
If I have a class with a unary constructor, can I somehow use that constructor as a UnaryOperator in an algorithm? i.e.: #include <algorithm> #include <vector> class Thing { public: Thing(int i) : m_i(i) {} int i() { return m_i; }; private: int m_i; }; int main() { st...
For the first code sample just use a lambda: std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), [](int i){ return Thing(i);}); And this is the best way for what your code does. Everybody will understand it. Constructor can't be used as an UnaryOperator, because it does not return a value.
72,464,511
72,466,730
can anyone help me in this time exceeds error
** Consider the following sequence: 7,77,777, 7777,... Let T be the smallest element in this sequence that is divisible by 2003. How many digits does T have?** enter code here #include <iostream> #include <stdio.h> using namespace std; int main() { int a=0; int count =0; for(int i=1;;i++); { a=...
Everything in this problem is known at compile time. So lets let the compiler solve this: #include <stdio.h> #include <cstddef> consteval std::size_t solve() { int a=0; std::size_t count = 0; do { a = (a*10 +7) % 2003; ++count; } while (a != 0); return count; } int main() { pri...
72,464,565
72,534,332
Directx 9 Rotate Textured Vertex
I used vertexes to draw textures and did not have a problem but now i am trying to rotate some textures and getting black screen. This is my initial code to draw texture with vertex. struct CUSTOM_VERTEX { FLOAT X, Y, Z, RHW, U, V; }; #define CUSTOM_FVF (D3DFVF_XYZRHW | D3DFVF_TEX1 ) CUSTOM_VERTEX vertices[4] = { /...
My problem was using the same points for both pre-transformed (RHW) and non pre-transformed vertices. Solved problem like below. struct CUSTOM_VERTEX { FLOAT X, Y, Z, U, V; }; #define CUSTOM_FVF (D3DFVF_XYZ | D3DFVF_TEX1 ) float halfBackBufferWidth = backBufferWidth / 2.0f; float halfBackBufferHeight = backBufferHeigh...
72,464,693
72,464,722
How to disable mutex if called within another function locking same mutex
I've got a resource class being guarded by a std::mutex, where any methods accessing it must be locked and only executed by a single thread. This works fine if individual methods are called separately, but now I've got a requirement for batching those methods together. In this case, the mutex needs to be locked only on...
This is exactly what std::recursive_mutex is for, it can be locked multiple times from the same thread. It will only fully unlock when the number of unlock calls matches the number of lock calls.
72,464,958
72,465,902
How to set a conditional breakpoint for C++ strings in VS2019?
I'm trying to set a conditional breakpoint for my debug but VS keeps returning me this error: How can it be so if the operator != is defined for strings? The variable error is std::string
There are many workarounds you can do, for example a much better way of writing your condition is this: !errors.empty() You also have size() that you can compare against 0, c_str() that returns a C string which you can test the first element against \0, etc etc. As to the reason why your line doesn't work is that most...
72,465,396
72,465,465
std::vector<std::vector<float>> in header file throws error LNK1120
I want to include my own header file but vector< vector < float > > throws an error matrix.cpp #include <vector> class Matrix { public: std::vector<std::vector<float>> data; Matrix(std::vector<std::vector<float>> d_data = { {} }) { data = d_data; } }; matrix.h #ifndef MATRIX_H #define MATRI...
The problem is that you've more or less copy pasted the class definition to the source file matrix.cpp. That is, you have defined the class Matrix twice. Once in the header and second time in the source file. To solve this just provide the implementation for the constructor Matrix::Matrix(std::vector<std::vector<float>...
72,465,968
72,466,036
How to sort an vector based on any column value by passing the column index as input?
I have already tried the below code but i want to use this same function for sorting based on different columns. This given code is sorting based on first column only. bool sortcol( const vector <int> v1, const vector <int> v2) { return v1[0]<v2[0]; } sort(ArrOfTimings.begin(), ArrOfTimings.end(), sortcol); Is there ...
You cannot pass additional info to a free function used for comparison for std::sort by means other than global data. You can create a struct with a member variable storing the column to compare in addition to providing a call operator for comparing the values though. I'd prefer a lambda, since it results in shorter co...
72,466,034
72,466,102
to find number to be prime in c++ I'm getting numbers like 9 and 15 also prime . pls find the error in the code
I'm getting numbers like 9 and 15 also prime by using this code . pls find the error in the code and if possible Pls edit my code to find the error Here is the code-- `#include<iostream> using namespace std; int main() { int n; cout<<"Enter the number : "; cin>>n; int flag=0;...
Your check logic is flawed as you are checking against %2, you should check against %i. I've also added a little optimization as you only need to check up until n/2. To check if a number is prime: #include<iostream> using namespace std; int main() { int n; cout<<"Enter the number : "; ...
72,466,463
72,467,761
Is alias construction of shared_ptr from void safe?
This is an entirely hypothetical question about shared_ptr aliasing constructor and UB. Lets imagine a situation where we store std::shared_ptr<void> in some database. Lets also imagine that we can safely cast a void * pointing to an instance of a parent type A to a pointer of a child type B (ex. via a compile-time gen...
From https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr: ... such as in the typical use cases where ptr is a member of the object managed by r or is an alias (e.g., downcast) of r.get() ... So this is exactly the envisioned use case.
72,467,023
72,467,374
Program slower with multi-threads
I started learning programming with multi-threads and i have program. My program is slower with multi-threads: multi-threads: ~ 8.5 sec without multi-threads: ~ 4.96 Someone can explain me what is wrong with my code? #include <iostream> #include <thread> #include <ctime> using namespace std; long long even_sum = 0; lon...
At minimum, you have a false sharing problem. even_count and odd_count are almost certainly on the same cache line, which means when you want to touch one variable you're actually forcing the other thread to have its cacheline invalidated. There's more to false sharing than this, but for a quick overview there's a gr...
72,467,305
72,467,376
Array printing out -858993460
I've been trying to work out why my array is printing out -858993460 with the following code int myInt = 0; int myArray[10]; // I know this is undefined, but the same results occur if I put {} to initialize it while(myInt <= 10) { myArray[myInt] = myInt; myInt++; std::cout << "Test " << myArray[myInt] << s...
Arrays in C (and by extension C++) are zero based, so an array of ten elements is indexed 0 through 9. But your loop is trying to access elements 0 through 10. myArray[10] is actually the eleventh element of the array, which doesn't actually exist. Trying to change it is undefined behavior. Your original code was act...
72,467,333
72,467,811
C++17: Deducing function noexcept specifier as non-type parameter
I've noticed that MSVC sometimes fails to deduce non-type parameters that other compilers accept, and recently came upon a simple example involving the function noexcept specifier (which is part of the function's signature since C++17): template <typename T> struct is_nocv_method : public std::false_type { }; template...
A non-type template parameter cannot be deduced from a noexcept-specifier. [temp.deduct.type]/8 gives the list of contexts from which template parameters can be deduced. Essentially, it can be read as a list of ways to "unwrap" the argument type, and a list of positions in the unwrapped type from which template argumen...
72,467,734
72,468,069
regex with string_view returns garbage
Matching a regex on a std::string_view works fine. But when I return matched substrings, they die for some reason. std::string_view argument is being destroyed upon the end of the function's scope, but the memory it points to is valid. I expected std::match_results to point to the initial array and not to make any copi...
For example, let's look at the following line: std::string_view config = matchResults[1].str(); Here, matchResults is of type std::match_results, and [1] is its std::match_results::operator[], which returns an std::sub_match. But then, .str() is its std::sub_match::str(), which returns an std::basic_string. This retur...
72,467,966
72,478,370
How can I split a raw buffer of uint8 I420 video data into YUV pointers?
I have a raw uint8 pointer to a buffer containing I420 formatted video data, and a buffer size. I also know the frame width / height. I want to feed the data into a library which can create video frames via this function signature: Copy(int width, int height, const uint8_t* data_y, int stride_y, const ...
The best site I know for describing the various YUV and RGB video formats is FOURCC - the YUV descriptions are here. The I420 format you refer to is described here. That means that your raw data will be organised like this: Y plane, of H x W bytes, with a line stride of W bytes U plane, of H/2 x W/2 bytes, with a line...
72,467,979
72,468,016
Where does C++20 prohibit sizeof...T (without parentheses)
Both g++ and clang++ reject the use of sizeof... when the argument is not parenthesized. For example, the following code is rejected: template<typename... T> auto packsize = sizeof...T; $ g++ -std=c++20 -ggdb -O -Wall -Werror -c -o z.o z.cc z.cc:1:50: error: 'sizeof...' argument must be surrounded by parentheses [...
It's required by the grammar: [expr.unary.general]/1 unary-expression:       ...       sizeof ... ( identifier )       ...
72,468,086
72,468,414
While Loop vs Do While Loop
I am working on a program in C++ for my class to prepend, append, insert, display items of a circular-list. I came across while loop functioning differently then a do-while loop for what to my mind would potentially output the same items. I am looking for an explanation to why the output is different with the code bloc...
A while loop evaluates its condition before entering the body. So, a while loop may run 0 iterations. A do..while loop evaluates its condition after leaving the body. So, a do..while loop will always run at least 1 iteration. Using a while loop will not work in this situation, since the condition (temp != head) will a...
72,469,399
72,469,475
Directly creating an object in a function call
Suppose a function Foo() takes an object of type Bar. Instead of Bar bar(parameters); Foo(bar); You can do Foo(Bar(parameters); Why isn't the second case allowed when Foo is defined to take a reference i.e returntype Foo(Bar &bar);
An lvalue reference (the kind you're referring to, written as T&) refers to an lvalue. Now the exact details of what that means are kind of complicated in modern C++, but the basic idea is that an lvalue is a thing that you can assign to. The name originally comes from the fact that an lvalue (where "l" is short for "l...
72,469,687
72,469,739
Why does this bad universal initializer syntax compile and result in unpredictable behavior?
I have a bunch of code for working with hardware (FPGA) registers, which is roughly of the form: struct SomeRegFields { unsigned int lower : 16; unsigned int upper : 16; }; union SomeReg { uint32_t wholeReg; SomeRegFields fields; }; (Most of these register types are more complex. This is illustrative....
reg1.wholeReg = card->readReg(REG2_ADDRESS) This is simply treated as an expression. You are assigning the return value of card->readReg(REG2_ADDRESS) to reg1.wholeReg and then you use the result of this expression (a lvalue referring to reg1.wholeReg) to aggregate-initialize the first member of reg2 (i.e. reg2.whole...
72,471,087
72,471,223
Is std::exchange specialized for atomics?
std::exchange(x,y) assigns x the value y and returns the old value of x. Is this function specialized for atomic values, i.e. will it use std::atomic_exchange? I am thinking the answer is no, in that case why not? Was it ever considered? Seems like a good idea to me. I am using this for resetting a simple counter and w...
How can I write generic function where it will use atomic exchange for atomic types and ordinary exchange for ordinary types? You can detect whether obj.exchange(x) is a valid expression (which works for std::atomic) to determine whether to use member function exchange or free function std::exchange. #include <utilit...
72,471,250
72,486,722
SFML 3.0 'intersects' function
I downloaded the latest SFML 3.0 source code from github and compiled it using MinGW GCC 11.2 on Windows 10. I'm try to compile example programs from SFML Essentials book. The code below causes compilation error: if(playerRect.getGlobalBounds().intersects(targetRect.getGlobalBounds())) window.close(); error: 'usin...
There are API changes in SFML 3.0 which are not compatible with SFML 2.5. For example VideoMode constructor is defined as follows: // SFML 2.5 VideoMode(unsigned int modeWidth, unsigned int modeHeight, unsigned int modeBitsPerPixel = 32); // SFML 3.0 explicit VideoMode(const Vector2u& modeSize, unsigned int modeBitsPe...
72,471,395
72,477,911
Array Circular left shift
I am trying to implement AES with an array of boolean values. I am stuck on the ShiftRows() function that left shifts a 4*4 matrix a specified amount. For example, some random input would create a 128bit array as such: Enter a message: random bits more! Before: 01110010 01100001 01101110 01100100 0...
You are swapping numbers instead of shifting. This works for shifting by 1 since the first value ripples along getting swapped over and over. And for 2 since numbers just swap places. But shifting by 3 you only swap the first and second number and nothing else. for (int j = 0; j < 4 - i; j++) { with i = 3 that only pr...
72,471,441
72,471,599
C++ Vectors: Error in push_back member function call
I am trying to create the transpose of a matrix - by traversing into 2-D vectors and assigning the values of indices accordingly. [[2, 4, 6], [6, 8, 9]] --> [[2,6], [4, 8], [6, 9]] // transpose matrix representation Here's my code vector<vector<int>> transpose(vector<vector<int>>& matrix) { vector<vector<int>...
result[j][i] is not a vector, it's an int. Also, you have to at least resize the vector to the number of rows in the transposed matrix (equal to number of columns in the input matrix). #include <iostream> #include <vector> std::vector<std::vector<int>> transpose(std::vector<std::vector<int>>& matrix) { std::vector...
72,471,900
72,479,469
Why isn’t my code with C++20 likely/unlikely attributes faster?
Code ran on Visual Studio 2019 Version 16.11.8 with /O2 Optimization and Intel CPU. I am trying to find the root cause for this counter-intuitive result I get that without attributes is statistically faster than with attributes via t-test. I am not sure what is the root cause for this. Could it be some sort of cache? O...
Per godbolt, the two functions generates identical assembly under msvc movsd xmm1, QWORD PTR __real@4000000000000000 comisd xmm0, xmm1 jbe SHORT $LN2@calc xorps xmm1, xmm1 ucomisd xmm1, xmm0 ja SHORT $LN7@calc sqrtsd xmm0, xmm0 ret 0 $LN...
72,472,069
72,523,139
Wrap cstdio print function with C++ variadic template
I'm writing a lightweight parsing library for embedded systems and try to avoid iostream. What I want to do is write variables to a buffer like vsnprintf() but I don't want to specify the format string, much rather the format string should be infered from the arguments passed to my variadic template wrapper. Here's an ...
I figured it out with some inspiration from this thread #include <cstdio> template<class T> struct format; template<class T> struct format<T*> { static constexpr char const * spec = "%p"; }; template<> struct format<int> { static constexpr char const * spec = "%d"; }; template<> struct format<doubl...
72,472,200
72,472,422
C++ type for functor structs
I am trying to have a single variable with some type that can be assigned to some of the C++ standard functors (eg: std::plus, std::multiplies, etc...) Here is the definition for std::plus (from this link): template <class T> struct plus : binary_function <T,T,T> { T operator() (const T& x, const T& y) const {return ...
A single variable to hold all kinds of callables with same signature is std::function<int(int,int)>. Though the functors need to either have the template argument specified or deducde them from arguments: std::function<int(int,int)> func2 = [](int a,int b){ return std::plus{}(a,b);}; or std::function<int(int,int)> fun...
72,472,209
72,472,366
how to convert depth map to 3D points for cv::rgbd::RgbdNormals
I am trying to compute surface normal using OpenCV. Below is the code snippet: // load 16bit uchar depth image (values are in millimeters) cv::Mat img = cv::imread("depth.png", CV_16UC1); // define our camera matrix cv::Mat k = (cv::Mat1d(3, 3) << 900, 0, 640, 0, 900, 360, 0, 0, 1); // compute surface normals cv::Mat...
It turned out that there is a function called depthTo3d in OpenCV to do this conversion. Please see following code snippet: cv::Mat points3d; cv::rgbd::depthTo3d(img, k, points3d); After conversion, these points should be given as input as shown below: normal_computer(points3d, normals);
72,472,234
72,472,410
C++ Header & Source Files - What To Include And In Which Order
I just started learning C++ and have trouble understanding the concept of header and source files, specifically which ones I'm supposed to include where. Suppose I have the classes A and B, each of whose contents are seperated into a header file and a source file, and I have a file in which I want to use those classes....
Which file do I need to include where #include directive in fact is very simple preprocessor directive, which just adds content of the specified file into the target file. Conventionally you keep declaration of functions in a header file and definition of the said functions in the corresponding cpp file, and thus you...
72,472,550
72,472,621
long long int ans = a*b VS long long int ans = (long long int) a*b
I've written a code: int a = 1000000000, b = 1000000000; long long int ans = a * b; cout << ans << '\n'; this code is causing overflow. I understand that a * b is causing the problem but I have taken long long int variable to keep a*b. But look at the following code: int a = 1000000000, b = 1000000000; long long int a...
This makes two temporary variables, (long long int)a and (long long int)b. The second conversion is implicit. Actual compilers might not bother, if the hardware has a 32*32->64 multiply, but officially the conversions have to occur. On 64 bits hardware, it's essentially free when you load an int in a 64 bit register.
72,472,629
72,473,408
Iterator over map with uncopyable types
I am trying to implement my own map type and I want an iterator for this map. My understanding is that the value_type of this iterator should be pair<const K, V> (see https://en.cppreference.com/w/cpp/container/map). Now, the iterator's operator* is supposed to return a reference to such a pair. I think this means that...
You should not create a copy. The iterator should provide some means to modify the element in the container, not a copy of that element. As you are bound to storing the data as K* and V* you cannot simply return a reference to a std::pair<const K,V> because there is no such element to begin with. You can take a look at...
72,472,943
72,473,133
Is integer overflow that evil?
Consider the following code #include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; vector<int> a(n); int sum = 0; for (auto &it : a) { cin >> it; sum += it; } cout << sum << "\n"; for (int i = 0; i...
There is actually no integer overflow in your code. Well in a wider sense it there is, but in a more narrow sense integer overflow would happen for example with: int k = 1234567891564; What actually happens is that in this line cin >> n >> k; operator>> tries to read a int but fails. 1234567891564 is never actually ...
72,473,132
72,478,402
Creating a constexpr array from non-constexpr argument
I learnt from here that args is not a constant expression. Now my question is: What should I modify in the given program so that I will be able to have an static_assert in the first variant without getting a compile time error. In the following code: #include <array> template<typename... Args> auto constexpr CreateArr...
You have to put the arguments into template parameters. Unfortunately it then can't deduce the type of the arguments anymore: #include <array> template<typename T, T... args> auto constexpr CreateArrConst() { constexpr std::array arr { args... }; static_assert(arr.back() == 4); return arr; } // cleane...
72,473,815
72,475,646
Why is heterogenous std::*map lookup opt-in in C++?
To support heterogeneous key lookup for a std::map one has to be a bit more verbose that in the olden days: (taken from the question on how to do it) int main() { { puts("The C++11 way makes a copy..."); std::map<std_string, int> m; auto it = m.find("Olaf"); } { puts("The C++...
If std::map would simple support this silently, that is if std::map<KeyT, ValT> would support find(LookupT) for "any compatible" type then: The abseil page on the matter cites an implicit comparison between double and intthat would be trouble: implicitly supporting heterogeneous lookup can be dangerous, as the relat...
72,474,030
72,474,240
C++ class declaration after using it
I want to create method with an argument which links to Enemy which is declared later. Here is my code: #include <iostream> #include <vector> using namespace std; class Weapon{ public: int atk_points; string name; string description; void Attack(Entity target){ }...
The problem is that the compiler doesn't know what Entity is at the point where you have used as a parameter type. So you need to tell the compiler that Entity is a class type. There are 2 ways to solve this both of which are given below: Method 1 To solve this you need to do 2 things given below: Provide a forward de...
72,474,389
72,474,509
Adding an explicit constructor makes a construction fail
I would like to understand how the compiler is selecting constructor in the following situation class Y { public: Y(int) {} }; class X { public: X(int, int, Y) { cout << "Y\n"; } //explicit X(int, int, int) { cout << "3 ints\n"; } }; int main() { X x({ 1, 2, 3 }); // Y } so that if we uncomment the...
X x({ 1, 2, 3 }); is direct initialization. The behavior of your program can be explained using copy initialization's documentation notes which states: In addition, the implicit conversion in copy-initialization must produce T directly from the initializer, while, e.g. direct-initialization expects an implicit conver...
72,474,878
72,475,063
Is any precision difference between (float + int) and (float + (float)int) in C++?
For example, If I have int A = 106 and float B = 10.345f, which operation has better precision, A + B or (float)A + B? Or do they actually have the same precision?
No there is no difference. When adding two arithmetic types, there is a set of implicit conversions that are applied by the compiler. You can find a list of these rules for example on cppreference. In your case rule number 3) applies: Otherwise, if one operand is float, float complex, or float imaginary, the other op...
72,474,896
72,474,928
Is directly putting in binary possible C++
Is putting in binary as a value possible? I want something like char test = 00101011 and it will become 43. I know this is possible by making a function that converts binary to decimal (which can be inputted) but thats not direct and Im pretty sure it takes time.
You need to put the prefix 0b. #include <iostream> int main() { char c = 0b00101011; std::cout << static_cast<int>(c) << std::endl; }
72,475,728
72,476,036
variadic template deduction with two template argument fails
When I have the class: template <std::same_as<char> ... Indices> struct MIndices { std::tuple<Indices...> indices; MIndices() = delete; constexpr explicit MIndices(Indices... args) : indices(args...) { } }; The following call works: MIndices myI('i', 'j', 'l', 'z'); But changing t...
If Dims should equal the number of parameters passed, you should use the sizeof... operator instead of letting the caller specify the size. CTAD (class template argument deduction) only works when all template arguments of the class are deduced. The workaround is to let all arguments be deduced. You can wrap the class...
72,475,983
72,478,795
opengl glut rotation keyboard directions
i wanna make a small app that allow me to move the triangle to top/bottm left/right. and when i press w -> rotate above and move above , s => rotate bottom and move bottom ,, d -> rotate right and moves right , a -> rotate left and move left .. here is my code : #include <GL/glut.h> // (or others, depending on the syst...
glRotated rotates around (0, 0). Actually rotate the triangle out of sight. You have to rotate the triangle first and then move it to its place in the world. Do not change the vertex coordinates but add a translation matrix with glTranslate: double tx = 0.0, ty = 0.0; double direction = 0.0; void Keys(unsigned char ke...
72,476,043
72,544,326
Should std::string specialize std::less with support for heterogeneous lookup?
Being able to look up a char* in a container with find without needing to create a temporary string object is a Good Thing. See: Avoiding key construction for std::map::find() and https://www.cppstories.com/2021/heterogeneous-access-cpp20/ and ... There are reasons why C++ could not enable this for any type T used as a...
I think the primary reason is that nobody proposed it. Nothing happens by magic, it has to be proposed by somebody and then reviewed and approved. If the proposal step doesn't happen, nothing will change. However, it should be noted that making std::less<std::string> transparent would be a breaking change for types lik...
72,476,055
72,476,108
Overloading operator+ to add 2 class objects. "C++ expression must be an unscoped integer or enum type" error
I have a Student class which has dynamic int array marks and int variable marksCount. I am trying to overload operator+ to sum 2 Student* objects. It is supposed only to sum their marks. For example, when adding 2 students (Student* objects) with marks { 2, 3, 4 } + { 1, 5, 2 }, I must have an output of Student* with m...
You don't need to use new or pointers here Student* s1 = new Student(marks1, SIZE); Student* s2 = new Student(marks2, SIZE); Student* s = s1 + s2; so instead Student s1{marks1, SIZE}; Student s2{marks2, SIZE}; Student s = s1 + s2; Similarly I would change all your int* to std::vector<int> and basically remove all o...
72,476,311
72,476,357
the value is different inside and outside the for-loop C++
I am a beginner in C++, and I want to write a program that replaces the max value with the min value in an array and vice versa. #include<iostream> using namespace std; int main(){ int num, arr[200],max,min,max_pos,min_pos; cout <<"enter array size: "; cin >> num; for (int i=0; i<num; i++...
Here for (int i=1, max=arr[0], min=arr[0] ;... You declare 3 variables, they are called i,max and min. max and min shadow the variables of same name declared outside of the loop. Do not declare the variables of same name, but use the ones you already declared: int max = arr[0]; int min = arr[0]; for(int i=1; i<num; i+...
72,476,814
72,476,983
Error in vector of struct with implemented Functions
I get the Erro: "no instance of constructor "std::vector<_Ty, _Alloc>::vector [with _Ty=FunctionToUpdate, _Alloc=std::allocator<FunctionToUpdate>]" matches the argument list" No matter how I change it, it persists, as long I keep it as a class. If I keep it all in just a simple .cpp without class and header, it all...
Your code has a few issues First, the correct initialization of static member Error::table would be as follows: const std::vector<FunctionToUpdate> Error::table { { 100, &Error::testFunctionA, { { {177} }, { {"string"} } }}, { 1948, &Error::testFunctionB, { { {...
72,477,155
72,477,933
Is the move or the copy constructor used when passing a list into a direct initialization?
Given the following toy code: class P // with compiler-generated copy constructor and move constructor { public: P(int x, int y) { } }; int main() { P p({x,y}); } In my current understanding, the {x,y} in P p({x,y}); is converted into an object of type P by implicitly calling the constructor P::P(int x, int ...
Usually there is optimization so that this P object is directly constructed as p. Nevertheless, may I ask if this implicit call of P::P(int x, int y) is invoked by the move constructor or the copy constructor Let's see what happens here with and without optimizations in C++17 and prior to C++17. Prior C++17 Prior to ...
72,477,749
72,477,931
How to write a lambda function that can only take in int or float pointers?
I need to create a lambda function that can take in either a int * or a float *, e.g., something like auto func = [](void* ptr) { // do some assignments with the pointer } Currently, I am using the void * approach, but I'm wondering what are some other approaches to accomplish what I want? I don't have access to C++...
C++14 has generic lambdas, meaning you can use SFINAE on them, e.g. in their trailing return types: #include <type_traits> template <typename T> struct valid_ptr_type : std::false_type {}; template <> struct valid_ptr_type<int *> : std::true_type {}; template <> struct valid_ptr_type<float *> : std::true_type {}; ...
72,477,834
72,478,168
Calculate an answer from a string equation in c++
I would like to convert a string equation such as 10+20 or even use of numerous operators such as 10+20*5 into an answer such as 110 from a string equation. I have currently tried looping through each char of the equation string and sorted the numbers and operators, however, I'm not able to get any further than this. H...
there is several sub problem in what you want to achieve pseudo code: for char in equation; if char == number do stuff else if char == operation do stuff the number in the equation, will they only be integer ? that's a single problem its self. lets assume its only integer... To test if char is a n...
72,477,867
72,479,296
Why does C or C++ “-0” not produce a floating-point −0?
I am trying to collect some edge cases for floating-point arithmetic. The thing is, my attempt with printf is not showing me what I want: #include <cmath> #include <stdio.h> #include <complex> int main() { double x = -0; auto y = sqrt(x); printf("x %f y %f \n", x, y); return 1; } Per IEEE, squareRoo...
0 is an integer constant, so -0 is also an integer which is still 0. To get a negative zero, using a floating point constant. double x = -0.0;
72,478,077
72,478,414
How to handle optional class members that are classes
Specifically my problem is that I've created a Texture class (writing OpenGL code). The Texture class handles loading a file into memory, etc. and the constructor takes a filename as its parameter. Here's a snippet of some of the relevant code for that class. class Texture { public: unsigned char* image; int wi...
Pointers can help you with that. They can either reference a Texture or nothing (via nullptr). class Pyramid : public Shape { Texture* m_Texture; Pyramid(Texture *tex = nullptr) m_Texture(tex) {}; }; Notes : Pyramid may or may not be responsible for creating the texture depending on your need (meaning that t...
72,478,243
72,479,906
Calling C++ function which accepts and returns std::string from Python
I'm trying to call C++ function using ctypes. The function declaration looks like std::string some_function( const std::string &param ) As Python can not interact with C++ directly, I have created a C-wrapper for this function as follows const char *my_function( const char *param ) { std::string result = some_functi...
Since your data contains embedded nulls, c_char_p won't work as it assumes the returned char* is null-terminated and converts the data up to the first null found to a bytes object. std::string as used also makes that assumption when pass a char* only, so it needs the data length as well. To manage a data buffer with n...
72,478,246
72,478,611
Eigen, How to handle element-wise division by zero
How to handle an element-wise division in Eigen if some divider could be 0 ? I would like the result to be 0. #include <iostream> #include <Eigen/Dense> using namespace Eigen; int main() { ArrayXd a(3), b(3), c; a << 1, 2, 0; b << 1.2, 3.4, 5.6; c = b / a; }
You can handle division by zero by using a binaryExpr: ArrayXd a(3), b(3); a << 1, 2, 0; b << 1.2, 3.4, 5.6; Eigen::ArrayXd c = a.binaryExpr(b, [](auto x, auto y) { return y==0 ? 0 : x/y; });
72,478,338
72,478,448
GoogleMock - Returning a value based on mocked function variables
I'm trying to mock a function that accepts a struct and returns another one. Something like struct InParams { int important_value; int other_value; } struct OutParams { int same_important_value; int idk_something; } virtual OutParams MyClass::TransformParams(const InParams& params){ ... } When making a mock...
When you use Return it takes the object of returned type as argument, by copy. If you want to be more generic, and alter your return value with respect to some logic, use a gmock action. E.g. Invoke will be fine here: EXPECT_CALL(*fake_wrapper, TransformParams(_)) .WillRepeatedly(Invoke([](const InParams& params)...
72,478,576
72,478,781
Using CMake with CPP and ASM on Windows template doesn't work
https://github.com/Ybalrid/cmake-cpp-nasm this project doesn't compile with errors: [build] cpp.obj : error LNK2019: unresolved external symbol _asm_foo referenced in function _main [C:\Users\[username]\Downloads\cmake-cpp-nasm-master\build\cmake-cpp-nasm.vcxproj] [build] Hint on symbols that are defined and could ...
Ok, I managed to fix this by adding a space: Old: if(WIN32) string(APPEND CMAKE_ASM_NASM_FLAGS "-dWIN32=1") endif(WIN32) New: if(WIN32) string(APPEND CMAKE_ASM_NASM_FLAGS " -dWIN32=1") endif(WIN32)
72,479,043
72,484,675
fail to wcout wchar[] which from GetWindowText();
while(TRUE){ HWND window = GetForegroundWindow(); WCHAR str[300] ; ZeroMemory(str, sizeof(str)); GetWindowTextW(window,str,299); wcout<<L"11"<<endl; wcout<<str; wcout<<L"22"<<endl; Sleep(1000); } this code will output "11",and then stuck. When I try to use char , cout and GetWindowTextA...
OK ! Just need to set locale that I forget. wcout.imbue(locale("your locale"));
72,479,081
72,480,260
Static assert that method cannot be called from constructor or destructor
Suppose I have the following classes: template <typename SELF> class Base { protected: template <int X> void foo(); }; class Child : public Base<Child> { public: Child() { //I want this to throw a static assertion failure foo<10>(); } ~Child() { //Should also static assert h...
While the OP has acknowledged in the comments that the whole endeavour is probably misguided in their case, the question remains an interesting puzzle. Performing such a check at runtime is feasible, but it needs to involve code that runs after Child during construction, and code that runs before Child during destructi...
72,479,322
72,479,487
How to use x64 assembly with C++ on windows?
cpp.cpp: #include <iostream> extern "C" int returnnum(); int main() { std::cout << returnnum() << "\n"; } asm.asm: segment .text global _returnnum _returnnum: mov rax, 420 ret First, I compile the assembly file with nasm -f win64 asm.asm. Then, I compile the C++ file with g++ cpp.cpp asm.obj. But this gives...
Based on your information from the comments and your g++ --version output, it looks like you installed plain MinGW (which is purely 32 bit, and works just fine if you only need to build 32 bit executables since Windows supports running 32 bit executables on a 64 bit OS) rather than MinGW-W64, the fork with native suppo...
72,479,545
72,479,667
Convert between vector::operator[] and vector::at in C++
vector::at are quite helpful for boundary checking, but will lead to low speed. So I am wondering whether there is a way to quickly convert code between vector::operator[] and vector::at, so that one for release and one for debug. Like If (DEBUG) { // Do with .at } else { // Do with [] } However, using code like that...
Like If (DEBUG) { // Do with .at } else { // Do with [] } You get something like this by using operator[] and by enabling bounds checking debug mode of the standard library implementation that you use. How to do that, and whether that option exists depends on what implementation you use. Note that typically the enti...
72,479,696
72,479,828
Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
I'm getting a runtime error for the below code while solving the Pascal's triangle question on Leetcode: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior I did come up with other code that works, but I'd like to know why I'm g...
You construct vector v with numRows number of elements. And then you iterate from 0 to numRows - 1 and in each iteration, you add a new vector to the and of vector v, so you end up with a vector holding 2 * numRows number of elements instead of numRows number of elements. Instead of vector<vector<int>> v(numRows); you ...
72,480,093
72,480,446
Convert array of bits to an array of bytes
I want to convert an array of bits (bool* bitArray) where the values are 1s and 0s into an array of bytes (unsigned char* byteArray) where the values at each index would be one byte. For ex, index 0~7 in bitArray would go into byteArray[1]. How would I go about doing this? Assuming that I already have an array of bits ...
Just just use bit shifts or a lookup array and and combine numbers with 1 bit set each with bitwise or for 8 bits at a time: int main() { bool input[] = { false, false, false, true, true, true, false, false, false, false, false, false, true, true, true, false, false, false, false, false, fal...
72,480,360
72,481,352
Problems discovering glibc version in C++
My application is distributed with two binaries. One which is linked to an old glibc (for example, 2.17) and another binary that targets a newer glibc (for example, 2.34). I also distribute a launcher binary (linked against glibc 2.17) which interrogates the user's libc version and then runs the correct binary. My code...
The fundamental problem is that the glibc version is a string and not a decimal number. So for a "proper" solution you need to parse it manually and implement your own logic to decide which version is bigger or smaller. However, as a quick and dirty hack, try inserting the line setlocale(LC_NUMERIC, "C"); before the s...
72,480,374
72,480,698
C4389 signed/unsigned mismatch only for x86 compilation c++
I am seeing a C4389: "'==': signed/unsigned mismatch" compiler warning when I execute the following code in Visual Studio using the x86 compiler using a warning level of 4. #include <algorithm> #include <vector> void functionA() { std::vector<int> x(10); for(size_t i = 0; i < x.size(); i++) { if (...
You have declared x as a vector of int – but the value you are looking for in the call to std::find (the i variable) is a size_t. That is an unsigned type, hence the warning. One way to fix this is to cast i to an int in the call: if (std::find(x.begin(), x.end(), static_cast<int>(i)) != x.end()) Another option (depen...
72,480,377
72,492,287
Replacing define statement with actual code
I know that #define is not really good to use, I am not sure if that's a duplicate but I couldn't find what's the best way is to do this: I have a program that uses a definition like: #define True GetObject(true) I need to replace the define statement with actual code but I can't think of a way to make it so the follo...
The following is probably similar in principle to your code. It is solved with #define and sets a serialno to each Object and prints something out to the console: #define True GetObject(true) #define False GetObject(false) #include <iostream> using namespace std; class Object { public: Object(bool b, int serial) ...
72,480,399
72,484,629
Does compiler need to care about other threads during optimizations?
This is a spin-off from a discussion about C# thread safety guarantees. I had the following presupposition: in absence of thread-aware primitives (mutexes, std::atomic* etc., let's exclude volatile as well for simplicity) a valid C++ compiler may do any kinds of transformations, including introducing reads from the me...
Yes, C++ defines data race UB as potentially-concurrent access to non-atomic objects when not all the accesses are reads. Another recent Q&A quotes the standard, including. [intro.races]/2 - Two expression evaluations conflict if one of them modifies a memory location ... and the other one reads or modifies the same ...
72,480,439
72,480,620
What components of a machine affect the machine code produced given a C++ file input?
I wrote this question What affects generated machine code at each step of the compilation process? and realized that is was much too broad. So I will try to ask each component of it in a different question. The first question I will ask is, given an arbitrary C++ file what affects the resulting executable binary file i...
The main one I think you're missing is the Application Binary Interface.  Part of the ABI is the calling convention, which determines certain properties of register usage and parameter passing, so these directly affect the generated machine code. The kernel has a loader, and that loader works with file formats, like EL...
72,480,933
72,495,767
CRTP and Incomplete Types
I'd like a short clarification on how complete types relate to CRTP. I thought this question was somewhat related. However, my question here question pertains to CRTP where a derived class member function explicitly calls the base class member function, which in turn calls a derived function. This appears different fro...
Using B<D> as base class for D requires B<D> to be a complete class. Hence it will cause implicit instantiation of B<D>. The point of instantiation of the class specialization is immediately before the namespace scope declaration requiring it, meaning before the definition of D. (by [temp.point]/4) The implicit instant...
72,481,316
72,481,630
Shortest distance around a circular axis; using degrees
Premise A simple SDL program of an entity (single dot/pixel) that rotates around (in a circle), then moves in that direction. Problem I'm unable to properly calculate the shortest distance from one degree to another; especially when those degrees cross the bounds of the 360/0 mark. Goal Calculate whether the shortest ...
If it wasn't for the 0/360 cross, it would just be a matter of getting the difference between the two angles, the sign of that difference would tell you if it's clockwise or not. On, top of that, if you get the difference between two angles for which the shortest path DOES cross the boundary, you'd end up with a differ...
72,481,395
72,481,419
C++ access object behind iterator in loop
I have created a list of objects of a class. The class has an overloaded ostream << operator to output customer data in a structured way. What I am trying to do is loop over the list of objects and call cout on the object in the iteration. Code for the loop is as follows: for (list<Kunde>::iterator it = this->kun_list....
Use a const reference loop over the container: for (const auto & kunde : kun_list) { cout << kunde << endl; } Obviously you also have to fix <<: friend ostream& operator<< (ostream& os, const Kunde& kd) {...}
72,481,445
72,481,446
COUT gives strange number for simple C++ code
I am trying to add a ASCII asterisk (*) frame around the hello world in a very simple C++ code. It works but gives this strange number before the frame. Here is my sample code. #include <iostream> #include <string> using namespace std; int main() { cout << "Please enter your name" << endl; string name; cin >> n...
Try double quote, so it looks like this: cout << "**" << stars <<"**" << endl; :-)
72,481,511
72,481,605
Return type of decltype()
In the below code, why decltype(++c) returns int& instead of int whereas decltype(a++) return int. #include <iostream> #include <typeinfo> int main() { int32_t a {}; decltype(a++) b; // OK int32_t c{}; decltype(++c) d; // error: 'd' declared as reference but not initialized std::cout << "typeid(b...
The result of the built-in pre-increment operator is an lvalue referring to the operand (which then holds the value after the increment). This means that, for example, ++a = 1; is valid. The result of ++a refers to the variable a, which can be assigned a value 1. The result of the built-in post-increment operator is a ...
72,482,493
72,483,088
removing x from a string using pass by pointer with recursion
I wrote this code to remove all occurrences of x from the string using recursion #include <bits/stdc++.h> using namespace std; void removex(string str) { if (str.length()==0) { return; } if (str[0] != 'x') { removex(str.substr(1,str.length())); } int i = 1; for (; str[i]...
Doing this with std::string and recursion is a formidable template for insanity. The erase/remove idiom exists for just this purpose, functions iteratively, and is highly efficient. Best of all, it already exists; all you have to do is set up the calls. That said, if you're bent on doing this recursively (and inefficie...
72,482,660
72,482,749
I'm getting an out of range error on my Leetcode program
So, I'm working on a relatively simple program on leetcode (https://leetcode.com/problems/plus-one/). I'll copy the description below: You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least signifi...
If all elements are 9, all elements will be removed by this part: if(digits.at(i) == 9) { digits.pop_back(); zeroCount++; } Therefore, the condition digits.at(index) < 9 becomes invalid after this operation. This condition should b...
72,482,793
72,485,835
No matching member function to call for 'push_back' error
While implementing LRU cache got this error. Earlier I was implementing it via maps it works then but somehow even when doing it as vector it does not work. #include <list> class LRUCache { list<pair<int,int>> lru; int cap; vector<list<pair<int, int>>::iterator> hash; public: LRUCache(int capacity) { ca...
Create an iterator variable, instead of nullptr value, as bellow: list<pair<int, int>>::iterator emptyIt; // this iterator object refer to nothing // Using `emptyIt` to initialize the hash LRUCache(int capacity) { cap = capacity; for(int i=0;i<=3000;i++) hash.push_back(emptyIt); } // Using emptyIt in...
72,482,815
72,623,461
Deleting all rvalue function overloads of a class
Say I have a class object that must be captured by the caller when returning this class's object from a function call. // no_can_rvalue *must* be captured [[nodiscard]] no_can_rvalue a_func(); I can enforce this by deleting all rvalue function overloads, thus making it impossible to use the class functionality unless ...
No, it is not possible to do so.
72,483,524
72,483,851
C++ Error: Continue option is not working and is looping the program instead
Note: I am a beginner in C++, so please bear with me if there are any serious programming errors that can be fixed easily. Edit: Options 3 and 4 work perfectly fine without any errors. However, Option 2 has a serious looping problem where 'Error! Number should be in range of (1 to 100)' and 'Enter the number again:' lo...
Your code is fine but you just have some typos in these lines. cout << "\nDo you want to continue? "; cin >> n; /*Here => */ if (n== 'Y', "Yes") fix it to if(n == 'Y'), also you have unintentionally used n instead of the char d that you have defined to use as a check. So your code should be cout << "\nDo you want to c...
72,483,808
72,484,701
Default random engine as class member, even if passed by reference does not update external engine
I know that I have to pass the random engine by reference in order for it to update out of a function. However, if I pass it by reference in a class construction, it looks like the seed is not changing outside of the class. Minimum working example: #include<iostream> #include<random> class rv{ public: ...
Like someone else already suggested; use an initializer list, that way you can have a reference variable as a member: class rv { public: std::default_random_engine& eng_ref; rv(std::default_random_engine& eng) : eng_ref{ eng } {}; double nd() { std::normal_distribution<double> ndist {0.0, 1.0}; ...
72,484,378
72,484,435
Function call cannot be matched to a candidate template definition (of a function to receive 2D array by reference) in C++
Novice here trying a different method to pass array-by-reference in C++. For C++, geeksforgeeks (under title Template Approach (Reference to Array)) shows a way to pass array by reference in C++ by creating a template. I am trying it because it seems a way to not use pointers and still pass arrays of different sizes on...
The problem is that float r[2][nums.size()]; is not standard C++ as the size of an array must be a compile time constant. But as nums.size() is not a constant expression so it cannot be used to specify the size of an array and moreover it cannot be used as a template nontype argument as a template nontype argument must...
72,484,487
72,484,599
C++ Library management system
I'm doing a library management system using arrays as database, when I enter a value in bookName, and after a loop and enter a value again, when I print all values in bookName[], it only prints the last value I entered. Please help me!! Heres my code: #include<iostream> using namespace std; int main(){ char yesNo;...
The for loop in your code initializes the variable i to zero, everytime you want to add a new book. Inside the for loop there is a break that exits the for loop after entering the string describing the book name. When the user selects option 4, the variable i will always be zero. Therefore, you will only print the info...
72,484,813
72,506,552
Declare a class and member variables using macros in C++
I would like to use preprocessor macros to declare many classes like the following: class ClassA : public ClassBase { public: int a; float b; char c; std::vector<void *> fun() { /* Code that uses all member variables */ std::vector<void *> v{&a, &b, &c}; ret...
#define NEW_CLASS(name_, seq_) \ class name_ : public ClassBase \ { \ public: \ IMPL_NEW_CLASS_end(IMPL_NEW_CLASS_decl_loop_a seq_)\ \ std::vector<void *> fun() \ { \ return { IMPL_NEW_CLASS_end(IMPL_NEW_CLASS_list_loop_a seq_) }; \ } \ }; #define I...
72,485,369
72,485,543
Calling constructor with string argument passing char * report error
template<typename T> class SharedValue { public: SharedValue(const T& t): valuePtr(new T(t)) {} const SharedValue& operator = (const T &t) { *valuePtr = t; return *this; } protected: dd_shared_ptr<T> valuePtr; }; typedef SharedValue<std::string> SharedString; int main(int argc...
Why str succeeded whereas str2 failed, is there any difference? Yes, there is difference between the two. In particular, in str we have have direct initialization while in str2 we have copy initialization. The behavior of your program can be understood from copy initialization documentation which states: In addition...
72,486,352
72,534,617
Implicit object parameter C++
In this link : Implicit object parameter In this quote : If any candidate function is a member function (static or non-static) that does not have an explicit object parameter (since C++23), but not a constructor, it is treated as if it has an extra parameter (implicit object parameter) which represents the object fo...
It's useful to consider examples. When you have: struct C { void f(int); void f(int) const; }; C c; c.f(42); How does overload resolution pick? You effectively have a choice of: // implicit object | regular // parameter | parameter void f(C&, int ); void f(C const&, ...
72,486,990
72,488,664
Why thread_local in different compiler or different platform has the different outcome?
#include <iostream> #include <unordered_map> #include <vector> #include <thread> using namespace std; // not POD struct A { std::unordered_map<int, int> m_test; }; struct B{ thread_local static A a; }; thread_local A B::a = A(); B b; void func(){ b.a.m_test[0]++; } int main() { vector<thread> T...
Based on testing on compiler explorer, this seems to be a GCC bug fixed in 2019 for versions 9+, 8.4+ and 7.5+. The code should work fine as posted. There is nothing wrong with it. Probably it is this bug. I recommend you install and use a more up-to-date version of GCC.
72,487,498
72,499,990
How Rvalue references bind to a temporary value (rvalue) behind the hood
I am interested in how the following code: int&& c = 2; c++; std::cout << c; //3 keeps the variable 'c' in memory? How the compiler implements the reference at the machine level? Does it set aside any memory for it? If so, where? Or it keeps it in CPU register?
Whether or not a reference is bound to a lifetime-extended temporary is a property that is determined at compile-time for the specific reference. For example in { int x = 2; int&& c = std::move(x); c++; std::cout << c; //3 } the value category of std::move(x) is xvalue and therefore it doesn't result i...
72,487,682
72,487,986
Why getting reference binding to null-pointer error?
I am solving the following Leetcode problem: https://leetcode.com/problems/find-if-path-exists-in-graph/ I am getting the following error: Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-beh...
The outer vector of adj should be resized, before adding elements to the inner vector. bool validPath(int n, vector<vector<int>>& edges, int source, int destination) { vector<vector<int>>adj; for(auto& it:edges) { if (adj.size() < (it[0] + 1)) { adj.resize(it[0] + 1); ...
72,488,154
72,503,232
MacOS C++ SFML Failed to add a new character to the font: the maximum texture size has been reached
I'm trying to write "hello world" to an SFML window... i know If I paste SFML font/text tutorial code in GSpace class, I get the error: "Failed to add a new character to the font: the maximum texture size has been reached" If I comment all of that out, and copy/paste to Simpulator class it works. If I undo everything, ...
I edited the make file from: Simpulator.o: Source/Simpulator.cpp Header/Simpulator.h $(CXX) $(CXXFLAGS) -c $< to: Simpulator.o: Source/Simpulator.cpp Header/Simpulator.h Header/GSpace.h $(CXX) $(CXXFLAGS) -c $<
72,488,691
72,488,807
Resolve enum class variable name to string
Consider, I have got the following enum class: enum class TestEnum { None = 0, Foo, Bar }; I'd like to specify ostream operator ( << ) for this enum class, so I could write: std::cout << "This is " << TestEnum::Foo; and get following output This is Foo. My question is: Is there any place where enum "name spe...
Is there any place where enum "name specifiers" are stored? No, but one option is to use std::map<TestEnum, std::string> as shown below: enum class TestEnum { None = 0, Foo, Bar }; const std::map<TestEnum,std::string> myMap{{TestEnum::None, "None"}, {TestEnum::Foo, "Foo"...
72,488,935
74,487,496
Conditional inheritance based on derived type
I have a set of graph classes that can be composed to create directed graphs for different purposes. For instance, it can be a plain directed graph, or functionality for traversal or nested graphs can be added. TraversableGraph and TraversableNode should inherit a StatusTrait. However, if the TraversableGraph is also a...
I've finally found the solution! As pointed out by @Jarod42, checking whether the derived class is a NestedGraph is not possible, since the derived class is incomplete when checking. Instead we can check whether the derived node is a NestedNode! We just need to pass the derived node as a template parameter to Traversab...
72,489,726
72,490,130
Switch Case with While Loop in C++ Menu
I've been building a menu driven console in C++, and I'm currently using switch-case as my options, but now I'm stuck in switch case. Here's the scenario: SCENARIO Explanation: After inputting invalid option in the main menu, it gives an error which prompts the user to re-input their desired option, now my problem is w...
It's a good idea to avoid repeating code. Here, you have a default case that is essentially an input loop, whereas you could have done that input loop at the start. So the way you wrote it, you still need a loop around the whole thing, plus more logic which makes the code harder to read and more bug-prone. Why not simp...
72,490,604
72,513,816
pointer already defined in file
I have this piece of code that works as expected when all of it is in a single file The problem is i need the platform to have a static pointer to the engine and vice versa #include <iostream> #pragma region include/iplatform.h namespace engine { class IEngine; } namespace platform { class IPlatform { pub...
The solution as @wohlstad commented was moving the line engine::IEngine* platform::IPlatform::ptrEngine = nullptr; to one of the source files
72,490,616
72,500,328
Processing flutter images with C++ openCV
I am working on a project, where I want to process my images using C++ OpenCV. For simplicity's sake, I just want to convert Uint8List to cv::Mat and back. Following this tutorial, I managed to make a pipeline that doesn't crash the app. Specifically: I created a function in a .cpp that takes the pointer to my Uint8Li...
Thanks to Richard Heap's guidance in the comments, I managed to fix the pipeline by changing my matrix definition from cv::Mat img = cv::Mat(h, w, CV_8UC3, rawBytes); to vector<uint8_t> buffer(rawBytes, rawBytes + inBytesCount); Mat img = imdecode(buffer, IMREAD_COLOR); where inBytesCount is the length of imgBytes.