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
63,308,619
63,308,692
c++ applying templated function to each element of a tuple
template<typename T> void print(T& t) { std::cout << t << std::endl; } template<typename ... Args> class Container { public: Container(Args&& ... args) : values_(std::forward<Args>(args)...) {} template<int INDEX> typename std::tuple_element<INDEX, std::tuple<Args...> >::type& get() ...
You need to unpack the tuple into apply like this: void display() { std::apply([](auto ...ts) { (..., print(ts)); },values_); } Here's a demo. Note that this solution uses a fold-expression to make the syntax easier.
63,308,679
63,308,919
Debug errors from my triplet sum from an array code from C++
I was tring a codingninjas problem, while executing got only 1 test case satisfied, please help. Given a random integer array and a number x. Find and print the triplets of elements in the array which sum to x. While printing a triplet, print the smallest element first. That is, if a valid triplet is (6, 5, 10) print "...
What would happen if there the triplet consists of 2 equal numbers on the i-th and j-th position, and arr[k] > arr[i]? For example (1, 1, 2) with the required sum 4? The expression arr[i]<arr[j] && arr[i]<arr[k] is false. The same is true for arr[j]<arr[i] && arr[j]<arr[k]. So you fall into the else branch (arr[k]<arr[...
63,308,758
63,309,161
Evaluation of variable
What does evaluation of variable mean? int main(){ int variable; variable; } What does "variable" do? Why evaluation of "variable" should produce its own value?
To "evaluate an expression" means to compute its result and execute its side effects. Expression variable has no side effects. (Unlike something like x = 1 or printf("abc")). It's result has type int (determining the type is not a part of the evaluation, because it never requires runtime computations), and the result h...
63,308,929
63,309,729
C++ keyboard even with SendInput - creating an autologin
as said in title I am creating an app to auto login, with account and password it grabs from a filestream. I have a function, DirectInput which takes a 'char' as parameter, and sends it as input from keyboard.The problem is I can not cast the parameter as int i, because it is not surrounded by ''. How would I be able t...
For upper-case: void DirectInput(char _key) { HKL kbl = GetKeyboardLayout(0); INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.time = 0; ip.ki.dwFlags = KEYEVENTF_UNICODE; if ((int)mK < 65 && (int)mK>90) //for lowercase { ip.ki.wScan = 0; ip.ki.wVk = VkKeyScanEx(mK, kbl); } ...
63,309,104
63,309,892
stack pop() causes "reference binding to misaligned address" error
I'm trying to code a solution for this leetcode problem https://leetcode.com/problems/maximum-frequency-stack/ class FreqStack { public: map<int, int>mp; map<int, stack<int>, greater<int>>st; FreqStack() { } void push(int x) { mp[x]++; st[mp[x]].push(x); ...
It is not the reference as in the above answer - you need the reference to actually make changes to st. If you dont declare v as a reference, you end up making changes only locally to v, and not to st. using the example from leetcode, after all the pushes, st[3] should have a stack containing [5]. In the first pop, tha...
63,309,242
63,309,416
a write function throwing the exception of read access violation in visual studio c++
I tried writing to a file and I am unable to write to it due to "Access violation reading location 0x0000000F" I am able to isolate the problem here is the sample code: void test_1() { std::fstream fio{ "xyz.dat",std::ios::in | std::ios::out | std::ios::binary | std::ios::app }; if (!fio) { std::cerr <<...
( char* )(s_test.length()) is treating the length of the string as though it's a pointer and passing address 15 into write. Since there is no valid character at address 15, this triggers Undefined Behaviour, and the behaviour in this case is the program crashes. This is always a problem when forced to use such a wide c...
63,309,530
63,309,732
Initializing array with results of variadic class template type's member function?
Say I have a template type ... template<typename ...Ts> struct SomeStruct { std::tuple<Ts...> some_tuple; } ... where I'm sure any type expanded from Ts all share a base class, and thus some member function that returns some type R. How could I go about collecting the results of calling that member function ...
Given that all Ts... element are supporting a foo() method, returning a R value, I suppose you can use std::apply(), if you can use C++17 std::apply([](auto ... vals) { return std::array<R, sizeof...(vals)>{ vals.foo()... }; }, some_tuple); or maybe simply std::apply([](auto ... vals) ...
63,310,209
63,310,266
Understanding Preprocessor Directives in C++ as a beginner
I recently began learning C++. As a programmer coming from Python, I've noticed some general similarities when it comes to how certain things in C++ do the same thing over in Python. One question I had is understanding Preprocessor directives. I/O Stream seems to be a common one to use in beginner programs. Is #inclu...
C++ did not have modules until the latest standard (C++20). #include is not the same as import in the languages that support modules. Instead, it is a source code - level inclusion of a "header" file. Usually, the headers only contain declarations but not definitions of what you are "importing". The definitions are con...
63,310,210
63,310,310
How to run CMake with predetermined settings?
In Visual Studio, a project using CMake will have a CMakeSettings.json file that specifies the command line parameters to be used. In IDEs other than Visual Studio, how do I control which parameters CMake is run with? Assuming CMake is run from the project root, I want CMake initialization to be run like this: cmake -B...
In IDEs other than Visual Studio, how do I control which parameters CMake is run with? Depends on what IDE you are using. There is no standard way. Typically, there is a settings form. A good solution is to document the command line commands that should be used. And ideally, those commands should be as conventional a...
63,310,390
63,310,982
C++ Find file name before file extension
I am new to C++ and learning curve has taught me a lot already, but now I really need to find a way to this quickly, and neatly. I tried many ways, but can't figure it out (or it works; but partially). size_t found = strFullPathName.find(".file001"); if (found != string::npos) { //Find us the filename, and return ...
To extract just the file name, simply rfind() or find_last_of() the last '/' and/or '\' char in the string, depending on platform, and then substr() everything after it. Then, to remove the extension, you can rfind() the last '.' char in the extracted file name, and then substr() everything before it. size_t found = st...
63,310,955
63,311,317
all possible combinations to divide pack of candies
I have problem to solve and I'm stuck, I don't know how to start. Suppose I have R childrens and S candies. I want to divide candies between childrens. Each child can get 0, 1, 2, 3 or 4 candies. How to find all the possibilities of such a division? #include <iostream> using namespace std; void solve(int r, int s) { ...
Just store counts and save variants at the last recursion level vector<int> counts; vector<vector<int>> sol; void solve(int r, int s) { if (s == 0) { sol.push_back(counts); return; } if (r == 0) { return; } for (int j = 0; j <= 4 && j <= s; ++j) { count...
63,311,040
63,311,237
segmentation fault while freeing pointer
class matrix { public: int nrow; int ncol; double **m; matrix(int r, int c) { nrow = r; ncol = c; m = (double**)malloc(nrow*sizeof(double*)); for(int i=0; i<nrow; i++) m[i] = (double*)malloc(ncol*sizeof(double)); for(int i=0; i<nrow; i++) fo...
int x = 0, y = 0; for(int i=0; i<nrow; i++) { if(i == r) continue; for(int j=0; j<ncol; j++) { if(j == c) continue; ans.m[x][y] = m[i][j]; y++; } x++; } The logic for incrementing y is broken here. Perform a simple mental exper...
63,311,069
63,311,594
Match an expression but don't match lines that start with a #
I am us Qt. I have a text string that I specifically look for a function call xyz.set_name(), I want to capture the last occurrence of this call but negate it if the line that contains it starts with a #. So far I got the regex to match the function call but I don't know how to negate the # matched lines and I don't kn...
If you merely want to match the last line that matches the pattern ^[a-z]+\.set_name\(\) you can use the regular expression. (?smi)^[a-z]+\.set_name\(\)(?!.*^[a-z]+\.set_name\(\)) For simplicity I've used the character class [a-z]. That can be changed to suit requirements. In the question it is [().\w\d], which can b...
63,311,501
63,311,588
Asterisk in C++ console lists all files in folder, why?
So I wanted to create a simple console calculator that'd take arguments via the int main(int argc, char ** argv) function. It works for regular examples, but trying multiplication with '*' started giving me way too many arguments listed in argv[], so I tinkered around and figured out it was listing all the files in the...
This has likely nothing to do with C++ and everything to do with your shell. Bash and other sh-like shells allow you to use "glob" patterns to name multiple files easily. This allows you to, for example, easily move all .png files in a directory to another directory with a command like mv *.png some-other-dir. The sh...
63,311,528
63,311,805
algorithm graph fiber network skeleton
I have a exercise to do fiber network skeleton. Each node is represented by IP address. On input I get commands to build network (B) and then commands to check (T) if there is connection between one node and another. B 100.100.100.1 100.100.100.2 B 100.100.100.1 100.100.100.3 B 100.100.100.10 100.100.100.11 T 100.100....
If links are bi-directional and there is no limitation on distance you could try using https://en.wikipedia.org/wiki/Disjoint-set_data_structure (a.k.a. Union-Find). When you see a link, merge the sets owning the two ends of the link. To test for connectivity, see if the two ends have been merged into the same set.
63,311,984
63,312,017
Get a non-const iterator from a const string parameter
I am reading strings with the following syntax: string example {"firstList:[element1:value1,element2:value2];secondList:[elementA:valueA,elementB:valueB]"}; Since a real list can have hundreds of elements, and I need only read operations (checking if value1 == "something" or if elementA exists), I implemented a std::s...
const std::string::iterator means "iterator for a string, through which the string can be changed; the iterator can't be pointed anywhere else." std::string::const_iterator means "iterator for a string, through which the string cannot be changed; the iterator can be pointed somewhere else." It looks like you are confus...
63,312,262
63,315,371
Store dynamic amounts of data in a class C++
I have a class that stores data and within the class I have an array called 'position' that stores strings of 2 characters. Unfortunately, the amount of 2 character strings it should hold will vary: class shipStatus { public: char* name; int x{}; char position[x][2]; // does not work void setInf...
Since this is C++, you should use the C++ facilities that are available to you. In your case, it would be std::string, std::vector, and std::array. Below is an example using basically what your original shipStatus structure consisted of, and changing it to using the above mentioned constructs: #include <string> #inclu...
63,312,319
63,318,108
How to send variable to widget from c++?
From code I want to assecc widget and and send string variable to it. But with my code I see only default value for it. Whet I set value in widget without code - it works. Call method from another class: UChangeDialogBottomText* changeDialogBottomText = CreateWidget<UChangeDialogBottomText>( GetWorld()->GetFirstP...
The Event Construct pin the in the blueprint is only called once when the widget is created, not every time a variable changes. Therefore, if you want the UpdateDialogBotton method to change the text of the widget, then you have to call the SetText method in there. However, you will also need a reference to the text bl...
63,312,625
63,312,651
Why am I getting a crash after calling my constructor? I'm trying to push back a shared_ptr to a vector
I'm quite new to programming (currently learning C++). I'm trying to learn how to use smart pointers. I'm trying to do a challenge from a tutorial in which the goal is to fill in data points to a unique_ptr of a vector that contains shared_ptrs that points to a data point. When I run it, it shows 0 errors and 0 warning...
In the function make, return std::unique_ptr<std::vector<std::shared_ptr<Test>>>(); just returns an empty std::unique_ptr which owns nothing. Dereference and usage on it like *vec_ptr leads to undefined behavior. You could return std::unique_ptr<std::vector<std::shared_ptr<Test>>>(new std::vector<std::shared_ptr<Test>>...
63,312,756
63,312,838
error: too few arguments to function 'float getTotalAmount'
Here is the problem i Designed a program to collect blood from users after collecting the data i give them the output. one of the output is retrieved from outside function which is getTotalAmount but i am getting error: too few arguments to function 'float getTotalAmount'. code attached below : class BloodDonator{ priv...
You may have to change the following segments of your code: // it's ok cout<<"name :"<<p1.n()<<endl; // removed space between "p1." and "getBloodType()" cout<<"blood type :"<<p1.getBloodType()<<endl; // it's ok cout<<"Blood Amount :"<<p1.getAmount()<<endl; // passed pointer to p1, cause getTotalAmoun...
63,312,894
63,316,195
Pragma omp parallel for inside inner loop is not correctly ignored in nested loop
I'm trying to implement the following codes to see how OpenMP threads are managed over the nested loop where each inner/outer loops are separately implemented in a function and its caller. Each loop is implemented with the statement #pragma omp parallel for and I'm assuming the pragma for the inner loop is ignored. To ...
I'm not sure I understand what is that you expected, but the result you get is perfectly expected. By default, OpenMP nested parallelism is disabled, meaning that any nested parallel region will create as many teams of 1 thread as there are of threads from the outer level encountering them. In your case, you outermost ...
63,312,955
63,316,963
Query regarding pointer member variable
I am learning c++ from 'Teach yourself c++ in 21 days' by Liberty and Jones. Compiler I am using is gcc 6.3.0. I am on pointer topic. First I am writing one code similar to the one book gives which works fine. Here it is: #include <iostream> using namespace std; class Cat { public: Cat(); int Getage() {return...
In this function: void Setage(int age) { *itsage=age; } you are dereferencing itsage, but it's not pointing to valid memory. This invokes undefined behavior. You need to do: void Setage(int age) { itsage = new int; *itsage=age; } For the second question, the correct syntax to access a member variable of pointer ...
63,313,052
63,313,265
How to implement 'reverse application function' in C++?
I am writing the C++ part of my project which has OCaml as the main language. I much more experienced with OCaml then C++. I use name binding (in OCaml, variable in C++) when this name is a conceptual point of the logic (to highlight it) or when this name is expected as an argument by more than one function (Possibly, ...
C++ doesn't let you define new infix operators, so you will have to use identifiers. Let's assume you are happy to have | rap > (spaces optional) instead of |>. struct rap_t { template <typename F> struct wrapper_t { F f; }; template <typename F> friend wrapper_t<F> operator>(rap_t, F&& f) { return { s...
63,313,096
63,313,188
Simple C++ interface to concepts example
I have an interface as follows: struct TestInterface { void on_read(unsigned len, const char* buf); }; My attempt at expressing this as a concept is as follows: template<class T> concept TestConcept = requires(T a) { { a.on_read(unsigned, const char*) } -> void; }; However, this does not compile. What is the...
Two problems: you have to use the objects not the types in the parameter list of the method to check you have to check the type with SFINAE expression because the return type itself did not result in failure if it is different to the expected one. struct TestInterface { void on_read(unsigned len, const char* buf)...
63,313,201
63,316,131
Find minimum number of digits required to make a given number
We have to find the minimum number of digits required to make a given number, for example: 14 => 95 (9 + 5 = 14) is two digits which is the minimum to form 14. int moves(int n) { int m = 0; // Minimum count while (n-9 >= 0) { // To place maximum number of 9's n -= 9; m++; } ...
Your code starts by looking at how many times 9 fits into that number. This can be done way more easily: int m = n/9; This suffices since we do an integer division, in which the remainder is thrown away. Note that if n would be float or another floating type, this would not work. The question left is if it is divisibl...
63,313,324
63,313,347
c++ destructor seg fault when using linked list
I currently have a seg fault when coding with c++, the Valgrind and gdb has told me that my destructor is having some problem //implementing constructor and destructor list::list(){ node * head = NULL; } list::~list(){ if(head != NULL){ delete head;} } //some code in a function that deal with l...
Almost certainly this list::list(){ node * head = NULL; } should be this list::list() { head = NULL; } In your code you've declared a variable called head in your constructor, that's a different variable from the head in your list class. So the head variable in the list class is uninitialised and that explain...
63,313,334
63,313,490
Decrypting text using c++
I want to decrypt a text using this code. But I can't seem to make it work. Can somebody help me? My editor keep saying that line 29 will never be executed, and does using return 1; correct? #include <iostream> using namespace std; int main() { int i, x; char str[100]; cout << "Please enter a string:\t";...
Your posted code has formatting issues as well as typos. The main problem that I inferred from the description that you'd written is return 1 in middle of the code. I think you should avoid that. Instead put a break statement. Also add default case label before the line where you are printing Invalid Input. This code m...
63,313,357
63,313,410
FastLED library not working when iterating through the LEDS backwards
Im having issues where my code running up the w2812b strip is working fine but when I run down the strip I get an error. This is the error /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c:1443 (xQueueGenericReceive)- assert failed! abort() was called at PC 0x4008...
for(int i = NUM_LEDS; i > 1; i--) You need to start from NUM_LEDS - 1 and go to zero: for(int i = NUM_LEDS - 1; i >= 0; i--) Because NUM_LEDS itself is out of range.
63,313,727
63,313,862
Difference between malloc and std::allocator<T>::allocate
I know both functions accepts size_t number. For malloc that number is raw bytes and for the allocate it is rahter n*sizeof(T) of that type. So does allocate call internally malloc? Also, from cpp reference about allocate: Allocates n * sizeof(T) bytes of uninitialized storage by calling ::operator new(std::size_t) I...
Your quote of std::allocator<T>::allocate: Allocates n * sizeof(T) bytes of uninitialized storage by calling ::operator new(std::size_t) or ::operator new(std::size_t, std::align_val_t) Does not refer to the new expression that creates and initializes objects. But to the operator new which is called by the c++ runtim...
63,314,158
63,314,363
Need some clarification on a c++ project on phone book using BST
I was supposed to make a project on a phonebook using BST in c++. I tried creating the insert function in the phonebook. I am not too confident in my code, can someone look into it an tell me if it is good enough. Like I think I have got the basic right in my code, I just want to make sure that I got it right. #includ...
Your phone book will have people's names and phone numbers right ? To start, create a Person class that will have a name field and a number field. Then you can use your BST to insert Person objects, comparing the Person objects by the name field. In a phonebook, we use search operation most frequently. Hence it is sugg...
63,314,477
63,316,256
tic tac toe better way of finding the matched symbol and the winner?
I'm a beginner in coding and this is the most complex code that I have created I'ts a simple tic tac toe game and I'm asking if there's a better way of finding the matched X and O string getWinner(string _gameBoard[ROW][COL]) // get the winner { for (int i = 0; i < ROW; i++) { if (_gameBoa...
First of all, you better hold your gameBoard as 2D array of char, because string is heavy and unnecessary. Next, as I suggested in the comment, you can split all the logic into separate functions like that. Don't be afraid that they return strange std::pair<bool, char> it's just a way of returning two values from a sin...
63,314,700
63,314,786
how to corectly make template function with iterators and user classes
I'm learning c++ and decided do something with templets and iterators. But when I started trying using my code with my classes it stopt working because I can't use with my classes something like ::iterator what i used in my template function. #include <vector> template <class Iterator> struct Page { std::vector<It...
My_struct <typename C::iterator> is the error source, since Page has no iterator member (Page::iterator does not exist). Also, this auto begin() const { return *data.begin(); } auto end() const { return *data.end(); } will cause a segmentation fault since there is no elements in the vector, therefore you should not be...
63,314,714
63,400,439
How does thrust determine arguments to pass to functor
My questions are: 1: How does Thrust determine what arguments to send to a functor and in which order to send them? Is it in the order of the input iterator data? I have not found any information on this. I have seen examples of e.g. thrust transform usage with zip/tuple iterators, which then has two data types, for in...
How does Thrust determine what arguments to send to a functor and in which order to send them? Is it in the order of the input iterator data? I have not found any information on this There isn't any information on it because the order of operations in parallel algorithms in thrust is undefined. Is there a max number...
63,314,788
63,314,836
why compiling below testcase without -DPASS is not sfinae friendly
$cat test.cc #include <type_traits> struct foo{ }; template<typename F,typename A> struct other { template<typename f, typename a, #ifndef PASS typename = decltype(std::declval<F>()(std::declval<A>()))> #else typename = decltype(std::declval<f...
Because SFINAE, related to class methods, works over template parameters of the methods itself, not over methods of the containing class. You can go around this limitation "transforming" a class parameter in a method parameter with the following trick template <typename T> struct foo { template <typename U = T,...
63,314,915
63,315,630
More efficient way for reading CAN data in while loop
I have 3 devices which send 8 bytes of data over CAN interface. To read the buffer from CAN I am using a while loop which looks something like this: void CanServer::ReadFromCAN() { data_from_buffer_.clear(); can_frame frame; read_can_port_ = read(soc_, &frame, sizeof(struct can_frame)); if (read_ca...
It turns out that poll is what you need. Here is my example. First, create a pollfd structure from <poll.h> header in Linux. I have decided to create a class member but you can create however you like: pollfd poll_; poll_.fd = soc_; poll_.events = POLLIN; poll_.revents = 0; Here, soc_ is a socket and POLLIN mea...
63,314,985
63,315,022
how to delete a dynamically allocated 2d array?
#include<iostream> using namespace std; int main(){ int **arr; arr=new int*[3]; arr[0]=new int [4]; arr[1]=new int [4]; arr[2]=new int [5]; arr[2][0]=20; cout << arr[2][0] << endl; delete []arr; cout << arr[2][0]; } I used a double pointer to create a 2d array in heap.The output before and after "delete []arr...
You are deleting array of pointers, not the actual 1D arrays. //Free sub-array's first for(int i = 0; i < 3; ++i) { delete[] arr[i]; } //Free the array of pointers delete[] arr;
63,315,540
63,342,661
C++ Matrix Multiply Slower OpenACC
When I enable OpenACC during compilation using GCC, is there a reason why my code is slower? I'm currently using GCC 6.3.0, on Windows 10. I'm really unsure why this is happening. This is the command I'm compiling with: g++ -fopenacc -o a Example.cpp And here is my C++ code: #include <stdlib.h> #include <cassert> #incl...
Not sure GNU 6.3 supported OpenACC, at least not well, nor do I know if it was supported on Windows. I'm using GNU 10.2 on Linux, where OpenACC support is much better. However, GNU still doesn't handle the "kernels" directive well so I'd suggest using parallel instead. Also, you're missing a data region so you'd get ...
63,316,242
63,316,255
Apply std::conj in template function if template argument is complex
TL;DR Let's say I have a function with a template argument T that takes a std::vector<T>& as input (see below), I want to conjugate this vector, if T is a complex type. How can I do that ? What I have tried Following https://stackoverflow.com/a/30737105/5913047, I know I can check if a type is complex with template<cla...
You are using an if statement. This requires the code in the if branch to be compilable, even if you don't need it to be executed. In c++17, to conditionally compile a piece of code, you can use if constexpr like this: if constexpr (is_complex<T>()) { //^^^^^^^^^ std::transform(MyVector.begin(), MyVector.end(),...
63,316,901
63,320,285
Is there a Python API function to get value by its name in C++?
I want to do something like this: Py_Initialize(); PyRun_SimpleString("d = 0.97"); float a = ? // how to get value of d by its name? Py_Finalize(); Is there a simple way to do this?
As said tdelaney, "d ends up in the __main__ module". So the best solution I find is Py_Initialize(); PyRun_SimpleString("d = 0.97"); PyObject *mainModule = PyImport_AddModule("__main__"); PyObject *var = PyObject_GetAttrString(mainModule, "d"); float a = PyFloat_AsDouble(var); Py_Finalize(); Not as simple as I expect...
63,317,148
63,317,216
How to print linked list using c++ recursion in object oriented form (OOP)
i m just creating my on stack using linked list,but when i print elements using recursion it exit with random code in geany. #include <iostream> using namespace std; class Node { public: int data; Node* next; }; class Stack { public: Node* Top; void stack() { Top = NULL; } vo...
You are not initializing Top in your code, so the first time you read from it, you are invoking undefined behavior (UB). The result of a program with UB could be anything, including freezing for some time, or exiting with an error code. This function: void stack() { Top = NULL; } looks suspiciously lik...
63,317,229
63,317,319
C++ memory model char vs word, concurrency? From Stroustrup book
Stroustrup gives the following example in C++ 4th Ed Page 1193. My question is with a concurrent program using two thread, one for f() and the other for g() and Stroustrup's statement that: if a linker allocated c and b in the same word in memory and (like most modern hardware)", what happens to variables c and b? It...
The point Stroustrup is making is that the C++ implementation is required to do whatever is necessary on the particular hardware to make things work as the memory model requires. What that may be dependent on the particulars of the hardware. A particular cache architecture might allow two values within the same "word" ...
63,317,762
63,317,905
Passing a 2D array to a function / constructor
Can't convert float[3][3] to float ** I am writing a Program deal with Matrices as a practice for learning But I am getting an error and am unable to assign float matrix[3][3] to float** I know that a 2D array is a Pointer of pointer, so a float ** My aim for this project is to write a Simple Matrix class to create mat...
2D arrays are stored contigously, so you should probably do something like this example: #include <iostream> template<size_t N1, size_t N2> void output(const float (&elements)[N1][N2]) { for (size_t i = 0; i < N1; i++) { for (size_t j = 0; j < N2; j++) std::cout << elements[i][j] << ' '; ...
63,317,840
63,317,878
Always getting interesting Segmentation Fault with g++
I am working on simple linked list project, everything works fine except List class destructor. I am trying to delete every Node that list has but g++ throws Segmentation Fault everytime(even for empty destructor). Can someone help me, what is wrong with my code? Thanks!. My List header; struct Node{ double data; ...
You invoked undefined behavior by using values of the member variables head and currNode without initialization. Initialize them like this: List::List(){ head = nullptr; // add this currNode = nullptr; // add this std::cout<<"Constructed Linked List"; } Or like this: List::List() : head(nullptr), currNode(...
63,317,859
63,317,952
Does C++ compiler treat all postfix operator overloading as same (postfix version of - and --)?
#include <cstdio> #include <iostream> using namespace std; class Int32 { int num; public: Int32(int num = 0) : num(num) {} ~Int32() {} int value() { return num; } Int32 & operator - (int x) { cout << "Postfix of -" << endl; return *this; } Int32 & operator -- (int x) { cout << "Postfix of --" <...
What is wrong with x- ? Nothing wrong with it; This by language design. You will see the same error with 1 - ; meaning, the operator - expect an argument to work with like you did it in the next line x.operator-(0);
63,317,993
63,320,670
Minimize Number- c++
how can I Print the maximum possible number of operations that can be performed? The operation is as follows: if all numbers are even then divide each of them by 2 otherwise, you can not perform any more operations. First line contains a number N (1 ≤ N ≤ 200) number of elements. Second line contains N numbers (1  ≤  A...
You are taking 'x' with n and m, but it has to be at end. Also just use an 'index' variable to keep track of where to insert in your array. And then use the same 'index' while finding the 'x'. #include <iostream> using namespace std; int main() { int a[100000],n,m,x; cin>>n>>m; bool flag=0; int index ...
63,318,473
63,318,876
What does the linker actually do when linking a pointer variable to an array in C++?
I have searched a lot for the extern-array-pointer problem but still feeling confused. In the following code: // example 1 //1.cpp int a[]={1,2,3}; //the array a //main.cpp extern int*a; //the pointer a In main.cpp, when I use printf to print a, it gives me 1 which is the first four bytes of the array a defined in...
The C/C++ part can be dealt with immediately: with many implementations, C doesn’t mangle any symbols, since they’re all supposed to be unique, and lacking overloading for variables C++ doesn’t mangle them either. (Variable templates are mangled, as are static data members.) This isn’t a requirement of the language: ...
63,318,904
63,319,337
Can someone explain this C++ code to me which is part of LinkedList program?
I know this question won't be specific but I can't figure out what this code is doing: I have a constructor for a class: ListNode(const T & data) : data(data), next(nullptr) {} that initializes next as a nullptr. Then I have this code: template <typename T> const T & List<T>::operator[](unsigned index) { ListNode *th...
Is this trying to define [] as an operator that will return the 'data' at the given 'index'? Yes. Basically it means you can do this: List<int> l; //suppose it has values int x = l[3]; //access the third element. And what is thru = thru->next; trying to accomplish? It is trying to find the index position provided ...
63,318,984
63,319,192
match a short string within a long string in c++
I tried to write a class called Mystring which basically does everything std::string class can do. Right now I'm trying to write a MyString::rfind function which will match a short string with the long string(just like the rfind function for string class). However, when I run the code nothing gets printed out in the co...
Your problem is here in the rfind() function: for (size_t i = a; i >= 0; --i) { The minimum value size_t can reach is 0. If you decrement it when it is 0, you wrap around to the largest value again. On my 64 bit system that value is 18446744073709551615. As you can see this value is greater than 0 so the loop never fi...
63,319,001
63,319,967
Using the enum from class template's scope without specyfing template parameters
Having such a code: template<size_t lines, size_t line_size> class Lcd { public: enum class Interface : uint8_t { _8_BIT = 0x30, _4_BIT = 0x20, }; Lcd(Interface interface); // some other stuff } int main() { Lcd<4, 20> lcd(Lcd<4, 20>::Interface::_4_BIT); } Could I change the code so tha...
Could I change the code so that it would be possible to call the Interface enum without using the <4, 20> specifier as the enum is universal? No, it is not possible. As @super already mentioned in the comments, in order to access something inside the template class, you need to specify the template parameters. The be...
63,319,341
63,319,463
Vectors and Functions exercise
I have a question regarding this program. I am a beginner when it comes to programming and c++, and I'm trying to figure out two things. why is this program not compiling (error: Using uninitialized memory 'total' - I have it defined as a variable??). Could someone explain how the function outside of the main (sumUpT...
Errors in your code - int userInput, n, total; . . . std::cout << sumUpTo(nums, total); Here you are declaring total and directly using it as a parameter to sumUpTo function. In that function you are using it in an comparison ( if (total > vec.size()) ). But, since you have never initialized it while declaration ...
63,319,482
63,321,831
Time complexity analysis in data structures and algo
Can we compare O(m+n) with O(n), are both same because we need to focus only on the highest power?
O(m+n) is two-dimensional (it has to parameters, m and n) and you can't reduce it to one dimension without more information about the relationship between m and n. A concrete example: Many graph algorithms (e.g. depth first search, topological sort) have time complexity O(v + e), where v is the number of vertices and ...
63,319,633
63,320,305
Extracting tokens from string in C++
Edit: I'm looking for a solution that doesn't use regex since it seems buggy and not trustable I had the following function which extracts tokens of a string whenever one the following symbols is found: +,-,^,*,! bool extract_tokens(string expression, std::vector<string> &tokens) { static const std::regex reg(R...
In an attempt to salvage the regular expression-based solution, I came up with this: [-+^*!()]|\s*[^-+^*!()\s][^-+^*!()]* Demo. This reports delimiters, and anything between delimiters including leading and trailing whitespace, but drops tokens consisting of whitespace alone. A similar expression that also strips lea...
63,319,838
63,320,396
Can increasing the capacity of a HashSet create Collisions?
I am attempting to implement a simple HashSet using a C++ vector as the underlying data structure. To keep things simple, I will double the size of the vector and re-hash all existing elements whenever the user inserts a new element that causes a collision (i.e. when another element already exists at the index at which...
If you double the number of buckets, you won't get any new collisions but you might not resolve your current collision. The original hash value is computed as hash = x % N; where x is is some value, and N the number of buckets. When you double the number of buckets, this becomes new_hash = x % (2*N); new_hash will e...
63,320,008
63,320,108
splitting one vector into almost-equal sub vectors then storing into another vector
I am trying to split one large user given vector into x sub vectors. Everything "seems" to work as it should but the outcome is not right. std::vector<std::vector<std::string>> split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) { std::cout << "initial size: " << initial_vector.size() ...
Even if hm starts at 0, you increment it before you use it. Probably if you increment at the end of the internal for loop, you might get the output you expect. It's hard to tell the problem because I don't know what's in 'initial_vector', I assume initial_vector[0] = 1?
63,320,226
63,330,851
Botan AutoSeeded_RNG can not be initialized, unknown reference, although libs are correctly linked
I simply try to initialize the Botan AutoSeeded_RNG but it fails because of a bad reference. I just wanted to test if i can initialize any kind of botan RNG, corse i have trouble with it in another project. I have the correct header included and am linking to the lib of Botan, therefore i don't know, why it can not fin...
You are not linking against the botan library. The -L <dir> flag only adds the directory to the library search paths, it does not tell g++ to link against any specific library. To link against a library, you have to use the -l <lib> parameter. The linker will then search for this library in its library search paths, in...
63,320,498
63,320,561
For-loop-condition (vector of ints). How to get the previous value?
I have vector of integers which is filled only by 1 or 0 values. What I am trying to make is that when the current value is 1 and previous/old is 0 or opposite if Current=0 and Previous=1, then to assign another variable(AvgCan) to 0. I am trying to get from FOR condition previous value. However, if I try it the usual...
Here iteration = i; iterationDecrease = i - 1; if ((resultINT.at(i)) != (resultINT.at(iteration - iterationDecrease))) the iteration - iterationDecrease is equal to i - (i - 1) which is always 1. Meaning in effect that if the statement is equivalent to if ((resultINT.at(i)) != (resultINT.at(1))) You probably mea...
63,320,646
63,320,680
Does GCC STL have a trait that gets the primitive type from typedef aliases?
I can't find a metafunction which returns the primitive type from its typedef aliases, like in that possible example: typedef int ivar; typedef ivar signIvar; ... // true std::cout << std::is_same< int, std::get_primitive<signIvar>::type >::value; It may exist, but I cannot find it. Implementation is possible in prin...
There is conceptually no such thing as "get primitive type from its typedef alias". An alias of a type is simply a name for the same type. As such, you can do: std::cout << std::is_same_v<int, signIvar>; // output: 1
63,321,079
63,321,134
Why does this code always generate zero when I want to generate random numbers? How can I fix the problem?
#include <iostream> #include<stdio.h> #include<stdlib.h> #include<time.h> using namespace std; class mRND { public: void seed() { srand(time(0)); _seed = rand(); } protected: mRND() : _seed(), _a(), _c(), _m(2147483648) { } ...
Your problem is here: return (_seed = (_a * _seed + _c) % _m); _a is 0 so the returned value is 0 and it never changes (since _a is always 0).
63,321,087
63,321,323
dynamic base class constructor call in derived class constructor in c++
I have a base class in a library which I don't want to modify for compatibility reasons. This class stores certain settings that cannot be modified after construction; the correct arguments must be provided at the time of construction. My own code contains a class that is derived from that class. The argument structure...
This is a case where a helper function to build derived instances would probably work better for you. class derived : base{ int variable; derived(char a, char b, int c) : base(a, b), variable(c) { } public: static derived build(int a, int b, int c) { if(/* a,b match first scenario */) { ...
63,321,181
63,321,207
Unknown output of a C++ code defining classes and objects
I have the following piece of code: In the last line, it prints a strange value of 6295680. What is that ?! #include<iostream> #include<iomanip> using namespace std; class c{ private: int a; public: c(int b=1): a(b) {} int f() { return a++; } int g...
it prints a strange value of 6295680. What is that ?! It is result of undefined behaviour. You've declared that the function returns int. The function doesn't return a value, nor does it throw an exception. As the consequence, the behaviour of the program is undefined.
63,321,242
63,321,298
how to add backslashes to a path string in c++ so that the ifstream function works correctly without any errors
in my C++ script, I am collecting a path through a file and storing it in a string. I want to work with the path file through ifstream but the path comes with only one backslash, example: path\dir1\dir2\file.cfg I need to convert this path, adding another backslash so that it works within the ifstream, example: path\\...
// Example program #include <iostream> #include <string> using namespace std; int main() { string path = "path\\dir1\\dir2\\file.cfg"; string new_path = ""; for(int i = 0; i < path.size(); i++) { if(path[i] == '\\') { new_path += path[i]; new_path += path[i]; ...
63,321,259
63,321,290
Is there any reason to wrap a Lambda in a named function?
I recently stumbled upon this example code and I was confused: auto named_funct(const MyClass& some_class) { return [some_class](const MyClass2& some_other_class) { return some_class <= some_other_class; // some expression between capture and input parameter to the Lambda }; } Is there any reason a...
named_funct doesn't execute the lambda, it returns it. You could use it like this: auto it = std::find_if(std::begin(some_vector), std::end(some_vector), named_funct(some_instance)); The odd thing is that named_funct takes a parameter that it doesn't do anything with, unless you have a copy/pas...
63,321,276
63,323,495
Finding closest triplet in a set of three vectors?
Given three vectors of double, I want to pair every element in each vector such that the difference between the largest and smallest element in each triple is minimized, and every element of every vector is part of a triple. Right now, I'm using std::lower_bound(): double closest(vector<double> const& vec, double value...
My solution was to implement a binary search terminating in a comparison of neighboring elements. Another possible solution is to iterate over the elements of each vector/array, adjusting the index as necessary to minimize the difference (which may compare to binary search with an ideal complexity of $O(\log{n})$?): in...
63,321,398
63,322,953
EM_JS: How to convert int argc, char **argv to a JS array of strings?
I'm trying to call JS function from C/C++ with an array of strings as an argument. Here's my example code: main.c: #include <stdio.h> #include <emscripten.h> EM_JS(void, call_myFunc, (int argc, char **argv), { var arr = []; for (let i = 0; i < argc; i++) { arr.push(UTF8ToString(argv[i])); } ...
How can I properly convert char **argv to a JS array of strings? From the documentation of emscripten.h: Null-terminated C strings can also be passed into EM_JS functions, but to operate on them, they need to be copied out from the heap to convert to high-level JavaScript strings. EM_JS(void, say_hello, (const char...
63,321,992
63,322,026
'this' argument to member function 'attacked' has type 'const Pokemon', but function is not marked const
I'm trying to call a function on a polymorphic item. But I get the following error message at compile time: 'this' argument to member function 'attacked' has type 'const Pokemon', but function is not marked const The question is, I don't even use const in my code. Here's my code. class Pokemon { public: QStr...
The lambda has a default capture [=], and so captured variables are const. If you want to call a non-const function on a captured variable in the lambda, you can capture it by reference with [&] like this: QTimer::singleShot(200, this, [&] { sPokemon.attacked(42); // ok }); Note that I used a dummy arg...
63,322,525
63,322,768
Smallest number whose sum of the digits is equal to the given number n
Below statement gives smallest number whose sum of digit is equal to the given number n. If the input is 10 output will be 19 (1+9=10) digits=(c % 9 + 1) * pow(10, (c / 9)) - 1 But when the input is greater like 100000, the output shows Inf. Can anyone help me to solve this, I even tried with unsigned long long int.
Assuming you just want to print the answer and not keep it stored in an integer variable, you can avoid overflow by taking the first digit as c%9and append c/9 number of '9' chars to complete the summation. std::string getDigits(long long c) { if (c == 0) { return "0"; } if (c < 0) { ...
63,322,573
63,322,613
Using a parameter without name
I'm working on a project my professor gave me. One of the functions that I have to implement uses a parameter passed in as such. Normally I am used to using parameters with variables. Instruction as to what the function is supposed to do: binMinHeap<Type>::binMinHeap(int capacity)-default constructor that sets this->...
but how do I access the parameter of just "int=10"? int = 10 declares an unnamed parameter with type int and default argument 10. If you want to use it, you need to specify the name for it. In the declaration the name is not used and not required, you can specify the name in the definition. class binMinHeap { publ...
63,322,837
63,322,912
Why tellg() returning -1 at th end of code?
#include<iostream> #include<fstream> using namespace std; int main() { system("cls"); fstream obj; obj.open("today.txt",ios::in); char ch; while (obj) { cout<<endl<<"file pointer at :"<<obj.tellg(); obj>>ch; } cout<<endl<<obj.tellg(); return 0; } output : file point...
tellg is returning -1 because it has encountered an error while reading the obj!! As while loop exits once the file has reached its end (no more data to read) and so obj is null and hence tellg return -1. Refer to this site for more information- http://www.cplusplus.com/reference/istream/istream/tellg/
63,323,002
63,323,025
Using nested if statements vs logical operator && in c++
Let us say I have an integer array representing the chess pieces on a board; int board[8][8]; In my chess game, I am currently coding a generator function that will return an integer vector of all legal moves. Naturally, I will be using if statements I am at a point where I need to check a certain element in the board...
For the first example, if pieceisnotonedge returns false, will it also check the next condition? No. It will "short-circuit" because if the first condition is false, checking the conditions after it is unnecessary. Read more here and here. This is guranteed by the C++ standard: 7.6.14 ... && guarantees left-to-righ...
63,323,111
63,323,326
Problems of cin and scanf() on MinGW-w64
My MinGW-w64's version is: x86_64-8.1.0-release-posix-seh-rt_v6-rev0.7z My System's version is: Windows 10 2004 When I tried to use MinGW-w64's g++ to compile and run this source file, I ran into troubles. this file's name is "temp.cpp" #include <iostream> using namespace std; int main() { char player1[8] = {0}, pl...
Oh... Your array is one-character too short for Scissors. You require 9-characters 8 + 1 for the nul-terminating character. So what happens on your stack is you have Player1 followed by Player2 (but since the stack grows down, Player1 is in the memory above Player2), e.g. | Player2 | Pl...
63,323,661
63,323,696
C / C++ clearer #includes
I really don't like when I have to navigate backwards in my includes. I'd mutch more prefere if there would be a way to avoid that. Look at this folder for example: Is there any way to tell the compiler (gcc) to start looking for includes from RootFolder, so I can say #include "Logic/Entitiy/Player.h" in my MainView.h...
You can pass include directories to your compiler. The configuration depends on the compiler. For gcc you set an include directory with -I. https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html
63,323,671
63,324,840
Is g++ linker statically or dynamically linking libusb and pthreads?
When adding -lusb-1.0 and -pthread to compilation command, are they statically or dynamically linked? g++ -pthread -o myprog obj1.o obj2.o -lusb-1.0 ldd gives the following output libusb-1.0.so.0 => /lib/x86_64-linux-gnu/libusb-1.0.so.0 (0x00007fc4662b7000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x0...
When adding -lusb-1.0 and -pthread to compilation command, are they statically or dynamically linked? By default, the shared libraries are linked on Linux. Unless you ask for static linking, the respective shared libraries for -pthread and -lusb-1.0 will be linked. You can tell the linker that you want static linking...
63,323,804
63,323,837
How to find the length of an array of objects in C++
How can I find the length of an array of objects in C++ class patient { public: int id; char p_name[20]; char f_name[20]; char m_test[20]; char c_report[20]; }; void p_detials(patient s[]) { char ch='y'; int i=0; while(ch == 'Y' or ch == 'y') { cout<<"\nEnter Patient id : ";...
You will have to have it return the length. #include <iostream> using std::cin; using std::cout; class patient { public: int id; char p_name[20]; char f_name[20]; char m_test[20]; char c_report[20]; }; int p_detials(patient s[]) // use int instead of void { char ch='y'; int i=0; while(...
63,324,200
63,324,260
inconsistent diagnostics across compilers for narrowing conversions in non-type template argument
template <bool> void f() { } int main () { constexpr long long int num = 5; f<num & 4>(); // bitwise & is intended return 0; } gcc 9 has a problem: error: no matching function for call to 'f<(5 & 4)>()' error: narrowing conversion of '4' from 'long long int' to 'bool' [-Wnarrowing] clang has a problem: e...
This is ill-formed because for template non-type argument, The template argument that can be used with a non-type template parameter can be any converted constant expression of the type of the template parameter. And the narrow conversion is not considered as converted constant expression. A converted constant expre...
63,324,263
63,325,069
Is it possible to use starts_with/ends_with from C++20 to compare case insensitive?
With C++20 and P0457 we get member functions for string and string_view that checks prefixes and suffixes: starts_with(), ends_with() Is there a way to compare strings case-insensitively? For example this check returns false: const std::string url { "https://isocpp.org" }; if (url.starts_with("HTTPS")) std::co...
starts_with and ends_with use the char_traits of the string. You can extend the default char_traits to uses case-insensitive comparison: struct case_insensitive_traits : public std::char_traits<char> { static bool eq(char c1, char c2) { return std::toupper(c1) == std::toupper(c2); } static bool lt...
63,324,490
63,324,526
Why is template parameter a reference in this case?
Stubled upon a weird behaviour when playing with std::forward. Here is a small example: #include <type_traits> #include <iostream> template <typename A> void func(A&&) { std::cout << std::is_pointer<A>::value << std::is_lvalue_reference<A>::value << std::is_rvalue_reference<A>::value ...
This is how forwarding reference works; when being passed an lvalue, the template parameter A will be deduced as an lvalue-reference. For this case, it's int*&, i.e. an lvalue-reference to pointer. (After reference collapsing, the function parameter's type would be int*& too.) When being passed an rvalue, A will be ded...
63,324,660
63,325,145
Face contours getting detected as 2 contours with the same drawing
I am doing a Project about Face Detection, thus far I want to detect the face as one whole contour, but here it's not the case. I have the following: std::vector<std::vector<cv::Point>> biggestcontours; Mat canny_output; vector<Vec4i> hierarchy; Rect bounding_rect; /// Detect edges using canny ...
Its because of the retrieval mode you are using. You chose RETR_TREE mode to find contours. As the documentation says: CV_RETR_TREE retrieves all of the contours and reconstructs a full hierarchy of nested contours Its finding inner and outer contours at the same time thats why it detects 2 contour. It can be better ...
63,324,985
63,325,038
error: no match for ‘operator+’ (operand types are ‘std::vector<int>’ and ‘int’)
I am trying to resolve Fractional Knapsack problem (Maximum Value of the Loot), there is my code : #include <iostream> #include <vector> #include <algorithm> using std::vector; double get_optimal_value(int capacity, vector<int> weights, vector<int> values) { double value = 0.0; vector<int> ratio; for(int i=0; ...
Shouldn't that line be something like value += a * (*it);? That appears to be a typo to me. Probably, you have got confused between value and values. The latter one is a std::vector<int>. You surely cannot add a number(double) to a vector in it that way. If you instead want to add a * (*it) to every value then probably...
63,325,129
63,326,293
Can't connect to host using OpenSSL in C++
When I try to connect to some hosts(not all) through HTTPS using OpenSSL in C++ I gets OpenSSL error error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure. I'm using TLS_client_method SSL method. But if I use openssl test executable, it's ok - openssl s_client -connect host:443 -tls1_2. My connect c...
Your code does not use the SNI extension when connecting to the server, i.e. does not include the hostname of the server into the TLS handshake. Multi-domain sites usually require SNI and might fail or return some unrelated certificate when SNI is not provided. This is also true for CDN like Cloudflare where different ...
63,325,244
63,325,347
What is the purpose for std::construct_at to cast through a pointer to volatile when using placement new?
According to cppreference, std::construct_at(T*p, Args&&... args) is equivalent to return ::new (const_cast<void*>(static_cast<const volatile void*>(p))) T(std::forward<Args>(args)...); What is the need/purpose for the cast 'through' const volatile void*? In other words, why is construct_at not simply equivalent t...
std::construct_at accepts as T any type... which may have cv-qualifiers. Meanwhile, static_cast may not cast away constness. The version you propose would fail for const foo * ptr = get_mem(); ptr = std::construct_at(ptr); // Error here when naively static casting to void* But static_cast may add cv-qualifiers. So in ...
63,325,411
63,325,692
Error: redefinition of class, despite using include guards
I'm a javascript/typescript developer but newbee to Arduino/c++ I have a class (see h and cpp below) and have this compiler error: DotMatrix.cpp:13:1: error: redefinition of 'DotMatrix::DotMatrix(uint8_t, MD_MAX72XX::moduleType_t, uint8_t, uint8_t, uint8_t)' DotMatrix::DotMatrix(uint8_t maxDevices, MD_MAX72XX::moduleT...
You defined the constructor twice. The first one definition of DotMatrix is within the class definition itself in the header DotMatix.h: class DotMatrix { public: DotMatrix(uint8_t maxDevices, MD_MAX72XX::moduleType_t hardwareType, uint8_t clkPin, uint8_t dataPin, uint8_t csPin) : _parola(hardwareType, csPin...
63,325,434
63,325,513
Can I use std::string* argv as main function argument?
Usually I see: int main(int argc, char** argv) But can I use: int main(int argc, std::string* argv) instead? If it's not possible how can I convert char* to std::string? PS: I am using C++11.
main argument must be char** argv or char* argv[]. [basic.start.main] 2. An implementation shall not predefine the main function. This function shall not be overloaded. Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined. An im...
63,325,596
63,325,734
SFML: Vector2<double> can't compile
I have this code that I can't compile. It works fine if I replace sf::Vector2<double> with sf::Vector2f. I've tried typedef, but it didn't make any difference. #include <SFML/Graphics.hpp> int main() { sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); sf::Vertex line[] = { sf...
sf::Vertex constructor does not take double vectors, only float vectors. See the documentation.
63,325,639
63,327,121
How to perfect forward a value returned from a function while returning a second value?
I want to make a benchmark function that, given an invocable and its parameters, will time the execution of the given invocable and return the measured std::chrono::duration<...> as well as the value returned by the invocation of the invocable. I am having problems with perfect forwarding the value returned from the in...
Yes, you are right. You need to handle the void return case when you invoke the function func inside the benchmark function. Since you have used std::invoke_result_t and std::conditional_t, I assume that you have access to c++17. Then this can be easily solved by an if constexpr checking. #include <iostream> #include <...
63,325,643
63,328,453
How do I use std::constructible_from
I am starting on C++ concepts and have trouble using them. E.g. Here I want to make an optimistic create_unique function. template<typename Arg, constructible_from<Arg> CreatedClass > *1 unique_ptr<CreatedClass> create_unique( Arg && arg ) { return make_unique<CreatedClass>( forward<Arg>( arg ) ); } template<...
Just do: template <typename CreatedClass, typename Arg> requires std::constructible_from<CreatedClass, Arg> auto create_unique(Arg&&) -> std::unique_ptr<CreatedClass> You don't have to use the terser constraint syntax - requires is always available. The negative case would then be an overload with no constraint: t...
63,325,805
63,325,893
Open MP bottleneck issue
I was trying to observe a basic openMP based parallelism with the following code, #include<stdio.h> #include<omp.h> #include<stdlib.h> #include <time.h> int main(){ long i; long x[] = {0,0,0,0}; omp_set_num_threads(4); clock_t time=clock(); #pragma omp parallel for for(i=0;i<100000000;i++){ x[omp_get_th...
Note that the 4 integers that you are operating on lie very closely together, probably on one cache line. Since cache lines are loaded into the CPU cache in one go, each thread needs to ensure that it has the latest version of that cache line. Since all threads want to modify (and not just read) that one cache line, th...
63,325,816
63,328,197
CMake No such file or directory
I have a problem building my Qt5 project via cmake. I run the command cmake .. && make from the directory build and I receive the following error: /usr/bin/ld: cannot find -lengine-lib collect2: error: ld returned 1 exit status make[2]: *** [src/CMakeFiles/blacklist-engine-cli.dir/build.make:102: src/blacklist-engine-...
The reason for the error is because engine-lib is never built, and its CMake file is never even processed. The offending line in your CMake file is this one: add_subdirectory( db engine ) When using add_subdirectory in this manner, the second argument becomes the binary directory for the generated content r...
63,325,888
63,326,458
Numerous LD linking errors while linking against downloaded package
I've been trying to compile an open-source C++ project Typesense, which has this list of dependencies: Snappy zlib OpenSSL (>=1.0.2) curl ICU brpc braft Host and target OS is Debian Linux. Compilation is handled via cmake->make sequence of commands. I was able to install some of dependencies through a package manager...
Your dependency list is incomplete. It only includes immediate dependencies. Your version of libcurl is built with ssh, gssapi, nghttp2, ldap, rtmp and possibly other goodies, none of which you are linking against. You are using static linking, and static libraries do not have a built in concept of dependencies. This m...
63,326,181
63,326,680
MSVC - C2668 ambiguous call to overloaded function - Is it a compiler bug?
MSVC 19.28 rejects the following code with the error message: C2668 ambiguous call to overloaded function A::Foo. Is it a compiler bug? It compiles fine with gcc, clang and even msvc 19.10. It fails since MSVC 19.14, see here #include <iostream> class A { public: template<typename T> void Foo(int = {}) { ...
For the call Foo<int>() the compiler can deduce Foo<int>() for the first template, and Foo<int>(void) for the second. From temp.deduct.partial#11: ... if G has a trailing function parameter pack for which F does not have a corresponding parameter, and if F does not have a trailing function parameter pack, then F is mo...
63,326,245
63,326,317
Initializer list, parameter pack expansion, fold expressions and order of evaluation
I have the following code to address a n-dimensional tensor class (offset is a std::vector of std::size_t): template <typename ...Ts> double Tensor::at(int first, Ts... others) { int i = 0; std::size_t index = static_cast<std::size_t>(first)*_offset[0]; (void)std::initializer_list<int>{(index += _offset[++i...
1. Your understanding is correct. 2. I'm not sure what you mean by "composed expressions", etc, but yes, initializers in braces are always evaluated left-to-right. See cppreference: In list-initialization, every value computation and side effect of a given initializer clause is sequenced before every value computatio...
63,326,289
63,326,487
OpenSSL occasionally printing random garbage
I have just started using OpenSSL in order to make HTTPS requests. I'm using C++. Sometimes, I get a proper response which looks something like this: HTTP/1.1 200 OK Server: nginx/1.16.1 Date: Sun, 09 Aug 2020 12:14:03 GMT Content-Type: application/json; charset=UTF-8 Content-Length: 159 Connection: keep-alive Access-C...
There are multiple bugs in the shown code. ret+=retc; This only works, when retc is a plain char *, when the string it points to is terminated by a '\0'. SSL_read does not do anything of that sort. You should use std::string's append() overload that takes a pointer and an exact number of character to add to this strin...
63,326,413
63,326,471
Can I add class template to tuple?
I'm trying to add class template to tuple These are my classes: class Parent { // ... } class Child1 : public Parent { // ... } class Child2 : public Parent { // ... } My purpose is to add class like this way: v.push_back({"child1", Child1}); so that I can save class template to create an object like this way...
No, you can't store a type directly. But you can store a function pointer, pointing to a function that constructs one of the derived classes when called. std::vector<std::tuple<std::string, Parent *(*)()>> v; v.push_back({"Child1", []() -> Parent * {return new Child1;}}); Parent *ptr = std::get<1>(v[0])(); Here, Pare...
63,326,536
63,326,721
Question about constructor matching and implicit conversion
I am doing an old school exam in preparation for my current exam and in one of the questions I am given this code: #include <iostream> using namespace std; struct A { A() : m_a(17) { cout << "A_default" << endl; } int m_a; }; struct B1 : A { B1() : m_b(1) { cout << "B1_default" << endl; } B1(const A& a) { ...
Why does B1 b4 = b2; print B1_constructor_with_a_parameter_A when it doesn't match any constructor pattern in struct B1? It does that because b2 is of type B2, which inherits from A, which makes it implicitly convertible to A. Why doesn't the line B1 b3 = b1; print anything? Because for this line copy-constructor(w...
63,326,542
69,515,693
Checking for constexpr in a concept
I just started doing concepts. The syntax for checking expressions is really useful and removes me a lot of boilerplate I had with sfinae. However I wondered how can I check if an expression can be used in a constexpr context. Sometimes those expression results in void. The way I can imagine would look like this, with ...
I think the expected concept can be created using std::bool_constant, which has the property that the failure of substitution in its argument of not-constant expression is not a compilation error, but just makes the concept false. The proposed solution is #include <concepts> #include <type_traits> template<typename T>...
63,326,827
63,331,718
Is there a way to use DirectXTex without Visual Studio?
So far, I tried to do this with my DirectX 11 project to load a texture: I downloaded DirectXTex source, included source files into my project and tried to compile, but got errors. I got errors from these header files: WICTextureLoader.h, DDSTextureLoader.h, and DirectXTex.h. The errors were from header files, and not ...
The DirectXTex library can be built with clang/LLVM for Windows or Visual C++. The project includes a CMakeLists.txt for building the DirectXTex library, and optionally the command-line tools, using CMake. If you have your own make solution, you can work out the details by referencing that file. To use the DirectXTex l...
63,326,876
63,327,049
best practice - where should const data for the class should be defined
I write a class which defines and uses const string (This string defines a path or a part of the path) Where should I define it : in cpp or h? should it be part of the class? For now this data is used only inside internal member functions. Which option is better? myClass.h // const std::string PATH = "Common\\Data\...
I write a class which defines and uses const string (This string defines a path or a part of the path) Where should I define it : in cpp or h? It depends. Is the value of string m_path same for all instances of class? If yes, then it should either be static const, or just defined globally or in an unnamed namespace ...
63,326,947
63,327,020
How do I construct a string consisting of doubles and " " and then give it as const char* to a cMessage constructor?
I'm working on a simulation in OMNet++. I want to send multiple double values in on message, that would look like this: "0.005044 0.345209 0.032458" For this, I generate 3 double values and then cast them into a stringstream. Then I convert this string stream into a string via str() and this string into a const char*: ...
On this line: return ss.str().c_str(); you are constructing a const char * from a string that will die when you return from the function. This leaves a dangling pointer at the call site. Instead, you can return a string from the function: std::string Provider::getSensor() { // ... return ss.str(); } and then you ...
63,327,260
63,328,658
Are pragma push/pop_macro directive stacks unique to each macro?
Microsoft provides the following example: // pragma_directives_pop_macro.cpp // compile with: /W1 #include <stdio.h> #define X 1 #define Y 2 int main() { printf("%d",X); printf(" %d",Y); #define Y 3 // C4005 #pragma push_macro("Y") #pragma push_macro("X") printf(" %d",X); #define X 2 // C4005 ...
Each macro has its own stack. As the documentation you link to says, push_macro “Saves the value of the macro-name macro on the top of the stack for this macro,” and pop_macro “Sets the value of the macro-name macro to the value on the top of the stack for this macro.” We can confirm this interpretation with code that ...
63,327,288
63,328,237
Why does using the ternary operator to return a string generate considerably different code from returning in an equivalent if/else block?
I was playing with the Compiler Explorer and I stumbled upon an interesting behavior with the ternary operator when using something like this: std::string get_string(bool b) { return b ? "Hello" : "Stack-overflow"; } The compiler generated code for this (clang trunk, with -O3) is this: get_string[abi:cxx11](bool):...
The overarching difference here is that the first version is branchless. 16 isn’t the length of any string here (the longer one, with NUL, is only 15 bytes long); it’s an offset into the return object (whose address is passed in RDI to support RVO), used to indicate that the small-string optimization is in use (note th...
63,327,379
63,327,479
How that works ! (template<std::size_t Size>)
#include <iostream> #include <array> #define print(x) std::cout << x #define println(x) std::cout << x << std::endl template<std::size_t Size> void Print(std::array<int, Size>& arr) { for (int i = 0; i < Size; i++) { println(arr[i]); } } int main() { std::array<int, 5> arr = {1, 2, 3, 4, 5}; ...
How does the size got passed to the function template without defining it like Print<5>(arr) ? It is thanks to template argument deduction. The size is deduced from the call Print(arr). Print() is a function template with a non-type template parameter (i.e., Size) of type std::size_t: template<std::size_t Size> void ...