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
67,320,438
67,320,626
How to fail a consteval function?
I have the following function: template <size_t TSize> consteval size_t indexOf(SomeEnum someEnum, const std::array<SomeEnum, TSize> &arr) { for (size_t i = 0; i < TSize; ++i) { if (arr[i] == someEnum) { return i; } } // How to fail here? return SOME_DEFAULT_WRONG_VALUE; }...
You might simply omit the return template <size_t TSize> consteval size_t indexOf(SomeEnum someEnum, const std::array<SomeEnum, TSize> &arr) { for (size_t i = 0; i < TSize; ++i) { if (arr[i] == someEnum) { return i; } } } Demo (clang warns though about that method). Compiler ...
67,320,794
67,320,795
Spliting multiple variable C++ functions for quadrature integration
I want to numerically integrate with boost::math::quadrature::trapezoidal(g, a, b, 1e-6); Here I'm integrating the function g(x). The problem is that I have to perform a double integral. Furthermore, I have 4 variables in the function I want to integrate. 2 of them I pass while integrating (m,n) and the other 2 are the...
The basic idea is, as usual, to integrate in two steps. For this you first solve the inner integral and make another one-dimensional function out of it, which you then pass again to the integrator. The lambda is used whenever you want to cut down a multi-parameter function to a single-parameter function. In this case, ...
67,320,969
67,321,252
MFC MDI Function calling vs SendMessage. C programmer trying to understand a basic concept
As a Senior hardware EE, most of my programming time uses C for firmware and inline assembly as needed. I've been working on an MFC MDI which a few of you have helped me out beautifully. I am creating a settings dialog and moving away from the menu items to write to the registry for storage and retrieval of the apps us...
There are two easy ways you can call a non-static member function of your application class from 'outside' that class. But they are essentially the same, in that you just need to call that member function via the actual application object (instance). First, you can use that object itself. Somewhere in your code, you wi...
67,321,480
67,322,062
what is wrong with printing an int or char array at specified location
I have got a namespace in a header file ,implementing a basic stack. Now on the push function ,it should push a char on to the stack and with the pop function it would remove a character from the stack AND here is my problem, print the popped element to the console, but it actually never does so. My question is why thi...
Note that a call to push assigns to v[top] before incrementing top, so in your pop function, the value of top is an unassigned integer. You just need to decrement top before printing the value of v[top]. void pop() { top--; printf("%d\n",v[top]); }
67,321,593
67,321,733
Passing a class instance to another instance via constructors in C++
I have a question about passing class instances to each other in C++, my question includes 3 parts. Assume this example: struct A{ int num; }; struct B{ int num; B(A input) : num(input.num){} }; 1: int main(){ // return 0; } Here constructor of B takes in input.num even though input.num is not even initialized ...
The constructor of B takes as an input argument an object of type A. In this snippet, we see the definition of the structures/classes, thus no object is created, neither of type A nor of type B. This will be undefined behavior, since a is not initialized when it's copied into input. This is a properly initialized co...
67,321,629
67,321,722
Whats the purpose of the __thiscall keyword?
When reading through the calling conventions there is a thiscall convention which purpose is pretty clear. I understand that thiscall defines a function which is part of a class, because these functions require an object as their first hidden parameter for non-static functions. So if I understand it right, then the fol...
these functions require an object as their first hidden parameter for non-static functions Ironically, you half answered yourself, because what you describe here is called fastcall, not thiscall, an ancient alternative to call member functions. thiscall stores this in a register, not on the stack. So that's your answ...
67,321,666
67,321,852
Generator called twice in C++20 views pipeline
Here in a simple pipeline of views adaptors, there is the gen function called to generate a sequence of values (using an internal state) and then a filter on it. What is surprising and counterintuitive (at least for me) is the fact that the generator function is called twice at each iteration, so that the next check on...
Do you have an idea if this is the correct expected behavior (and why)? Yes: this is the expected behavior. It is an inherent property of the iteration model where we have operator* and operator++ as separate operations. filter's operator++ has to look for the next underlying iterator that satisfies the predicate. Th...
67,321,791
67,325,793
cin gets skipped without valid input (string)
Im writing a program requiring input. But somehow the input argument in the console seems to be blocked. Because cin just get's skipped. I tried to force input with to see if any input gets taken with: while (!(cin >> exit_theloop)){ if (exit_theloop == "EXIT" || exit_theloop == "exit"){ bre...
When the user puts an EOF, std::cin will be put in a fail state. This means no input can nor will be read from std::cin, among other things. What you need to do is reset the state using cin.clear(), like so: #include <algorithm> #include <iomanip> #ifndef __GNUC__ #include <ios> #endif #include <iostream> #include <str...
67,321,837
67,322,356
How can I simplify this program?
I'm writing a program that finds the roots of a quadratic equation using exception handling and i'm wondering if there's a way I can simplify the program, I have a bunch of empty classes for the catch cases // Program to solve quadratic equation #include <iostream> #include <cstdlib> #include <cmath> using namespace st...
Note that the dynamic excpetion specification you are using is deprecated in C++11 and removed in C++17: void roots(double a, double b, double c) throw (all_zero,negative,zero_division) // ^^ You can just remove it. using namespace std; is considered bad practice. Do not use st...
67,321,876
67,322,763
Problem with the SetConsoleCursorPosition() function
I need a hand because I can't get the SetConsoleCursorPosition () function to work, I made a dll project and then I allocated the console with its main functions (cout and cin), but I don't know how to make that function work as well , in the sense that I do not go to the line that I have set, as the code ignored that ...
Per SetConsoleCursorPosition, the first argument must be "a handle to the console screen buffer". Per GetStdHandle, the handle to the active console screen buffer is returned by STD_OUTPUT_HANDLE, not STD_INPUT_HANDLE which is the handle to the console input buffer. Using the correct handle will get SetConsoleCursorPos...
67,322,409
67,322,489
Sorting a vector within a vector pair
Consider this snippet in C++ vector<pair<int, vector<long long int>>> strengthVector; // sorting for (auto x : strengthVector) { sort(x.second.begin() + 1, x.second.end(), greater<long long int>()); } // calculate prefix sum for (auto x : strengthVector) { for (j = 1; j < x.second.size(); j++) { x.second[j] +...
This loop for (auto x : strengthVector) makes a copy of every element in strengthVector so you're not actually modifying it. You need to iterate by reference for (auto &x : strengthVector)
67,322,503
67,325,390
Cannot run multiple C++ files in Visual Studio Code
Whenever I try to run my code if I have more than one .cpp file, I get the following message: The preLaunchTask 'C/C++: g++.exe build active file' terminated with code -1. I can debug anyway, show errors or abort. If I press show errors, nothing happens, it doesn't take me anywhere. If i press debug anyway, I get anoth...
To build a program that consists of multiple files you need to use sort of a build system. Two most popular ones are make and cmake. You need to get more familiar with them. make comes with mingw. cmake needs to be downloaded and installed separately, and finally also requires either make, ninja or full version of Visu...
67,322,575
67,338,736
Finish drawing a polygon by right-clicking, but displaying a menu instead
I am writing a program that will continuously draw a polygon until the user right-clicks. The user can only draw if and only if the user makes a selection in the menu, if the user does not make a selection in the menu, the program will not draw. Up to now, my program has successfully drawn a polygon with the mouse, but...
Capture the return-value from glutCreateMenu(), that's the handle for the new menu. Detach the menu in the menu callback via glutDetachMenu() and set a bool indicating you're in "add points" mode. If you're in "add points" mode and detect a right-click, set the current menu to the menu handle from #1 via glutSetMenu()...
67,322,651
67,322,807
how can I print a message in if statement?
#include <iostream> #include<string> using namespace std; int main() { string username, password, option, admin, client,type; cout << "enter the username" << endl; cin >> username; cout << "enter the password" << endl; cin >> password; cout << "are you admin or client?" << endl; cin >> optio...
If you change the two if statement checks to something like this: if (option == "admin") { ... } else if (option == "client") { ... } it might work a it better since at the moment it's checking against empty strings.
67,323,268
67,323,659
Why the output is not showing?
My program is to find the smallest positive number missing from an array. With the following input I expect an output of 2. 6 0 -9 1 3 -4 5 My problem is that it does not give any output. Can anyone explain this please? #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a...
I think because int array[n]; makes an array called array with n elements in it, with the first one starting at array[0]. cin >> array[n]; needs to modify array[n], but because the first element is array[0], the last element is array[n-1], and array[n] does not exist. Your code gave an error and exited. Try changing fo...
67,323,455
67,325,982
Calculate prefix product with std::exclusive_scan and execution policy std::execution::par
I'm calculating the prefix product with std::exclusive_scan #include <algorithm>/ #include <iostream> #include <vector> int main() { std::vector<int> input{1,2,3,4,5,6,7,8,9}; std::exclusive_scan(std::begin(input), std::end(input), std::begin(input), 1, std::mult...
When you use exclusive_scan with default execution policy, as: exclusive_scan(input.begin(), input.end(), output.begin(), initial_value, operate) what happens is: initial_value_temp = operate(input[0], initial_value); output[0] = initial_value; initial_value = initial_value_temp initial_value_temp = operate(input[1],...
67,323,766
67,326,492
Effectiveness of unique_ptr
I liked std::unique_ptr the moment I saw it back in c++11, but I questioned it's effectiveness for quite a while. (see link below for link to live code) : #include <memory> std::unique_ptr<int> get(); extern std::unique_ptr<int> val; void foo() { val = get(); } This gave me 16 instructions on last clang with -O...
The order of operations for move-assignment must be: Make a copy of the managed source pointer, and null it in the source object. If the destination managed pointer is not null, delete it. Set the destination managed pointer in the destination object. Note that this logic happily results in a no-op for self-move-assi...
67,324,034
67,555,570
How to Remap a YUY2 image?
I have a distorted image in YUY2 data form, YUY2 comes under the family of YUV 4:2:2 (not 4:2:0). And I have mapx and mapy (height-720, width-1280), which I obtained from cv::fisheye::initUndistortRectifyMap(K, D, cv::Mat::eye(3, 3, CV_64F), new_K, Size, CV_32FC1, mapx, mapy); How can I have undistorted YUY2? My fina...
I tried modification in mapx & mapy to make it suitable for YUV422. Result is very good in terms of computation time. Just one remapping is required in real time. But the quality is not the best. Then I tried YUV422 -> YUV444 -> remap(YUV444) -> YUV422 through libswscale, but again YUV conversion was taking time. Final...
67,324,038
67,324,219
C++20 Coroutines and iostream
I am playing around with C++ 20's Coroutines. The sample is compiled with clang++. The compiler error I am facing is error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream') and 'cppcoro::generator') which is about the following line std::cout << numbers << " "; the full code snipped look...
From the documentation of cppcoro::generator, the only "meaningful" operations you can do to a generator is get begin and end iterators via begin() and end(). This is precisely why your second use for (auto n : generatorForNumbers(0, 5)) works. It iterates over the generator. Though you technically hit undefined behavi...
67,324,232
67,324,642
When passing gmock object as reference the setup expectations doesnt match
I want to test the behaviors of the following class. class DAO{ otl_connect *conn; public: DAO(otl_connect* _conn){ conn = _conn; } bool init(){ bool ret = true; try{ conn->rlogon("ABC"); }catch(otl_exception &e){ ...
Problem is wrong matcher. By writing: EXPECT_CALL(mock, rlogon("ABC")); You are not expecting call of rlogon with a string "ABC", but you are expecting call with some pointer value which you do not have control over it. Reason is that your argument type of is const char * To fix it use StrEq() matcher. EXPECT_CALL(moc...
67,325,010
67,325,218
Does the implicit conversion of a literal to a class type happen at compile time?
I'm trying to write a class that is closely related to integers, and because of that I included a conversion constructor with the form constexpr example::example(const int &n); My question is: if I subsequently define the function void foo(example n); and I use it like this foo(3); in my code, is the integer literal...
The fact that the constructor is constexpr does not force the computation to happen at compile time. It only means that the constructor is eligible to be used within both constant expressions and non-constant expressions. If on the other hand you declare the constructor consteval, then it means that only constant expre...
67,325,623
67,325,723
error: no matching function for call to 'Processus<std::vector<double> >::minmax(const std::vector<double>&, std::vector<double>&) const'|
I have a problem, I have my class and my minmax function coded as below template<typename T> class Processus { public: typedef pair<double, T> state; typedef vector<state> result_type; Processus(int n = 0) : v(n+1) { Schedule w(n); auto i_w = w.begin(); for (auto it = v.begin();...
Inside of Processus::minmax(), your intent is to call your standalone 2-parameter minmax() function. However, from the error message, it is clear that the compiler is trying to call Processus::minmax() recursively instead, which does not work since Processus::minmax() does not take in any parameters. To call the stand...
67,325,644
67,325,832
How to Define CountProbation() function using Functions from other Files?
I have been racking my brain on how to properly define the function CountProbation() properly in the Course.css file. I know that a for and if loop should probably be included but I am having trouble including functions from other files, even though I am including a header tag at the beginning of the current Course.css...
This loop (as it was coded in the original question, before it was edited): for (int i=1; i < roster.size(); ++i) { if (Student.GetGPA() < 2.0) { probCount = probCount + 1; } } is flawed for three reasons: i should start from 0, rather than 1 i should be of type size_t, rather than int Student is a type...
67,325,803
67,325,837
C++ lambda capture single struct field by value
I have a large struct and want to capture a field out of it by value. The below code apparently WORKS, but I was confused and led to believe by this (from SO) that it shouldn't. Have I misunderstood that post, or will this fail in some way I do not see? I am using C++14. struct Foo { int Bar; /* ... */ }; Foo foo; IAcc...
You can use such Bar from inside the lambda without any troubles. Just note that it's a copy of the original foo.Bar, not a reference. The post you linked talks about a situation when we want to look what a specific lambda has captured without actually calling it, some kind of introspection.
67,325,883
67,325,924
Serialize C++ classes between processes and across the network
I'd like to understand how to transmit the contents of a C++ class between processes or across a network. I'm reading the Google Protobuf tutorial: https://developers.google.com/protocol-buffers/docs/cpptutorial and it seems you must create an abstracted, non-C++ interface to represent your class: syntax = "proto2"; p...
That's how Protobuf works. You have to use something else if you want to serialize your manually-written C++ classes. However, I'm not sure you really want that, because you then will have to either restrict yourself to very simple fields with no invariants (just like in Protobuf) or write custom (de)serialization logi...
67,325,944
67,326,053
read or display specific line from text a file
for example, there are 100 lines from the file, and I only want to show 20 lines and ask the user to press enter and then another 20 line display and so on to the end of the file. here is my code int main() { ifstream infile; string filename; string line; int lineCount = 0; cout <<...
You just have to count the lines. Example: #include <string> #include <iostream> #include <fstream> using namespace std; int main() { ifstream infile; string filename; string line; int lineCount = 0; cout << "Enter file name: \n"; cin >> filename; system("cls"); infile.open(filename)...
67,326,131
67,326,164
getline(file, text) exhibits strange behavior : stuck reading a ghost line
I am stuck with the strange behavior that getline is exhibiting in the following code #include <iostream> #include <fstream> #include <sstream> using namespace std; int main() { string password = "cat"; string inputFileName = "text.txt"; string content = ""; ifstream file; file.open(inputFileNam...
Obviously, your program is not running from the directory you think it is. Visual Studio is particularly bad about this, I find. You'll need to go into the Properties for the project and see where the current directory is set to. Either that or run it from a terminal yourself. Edit every copy of that text file that you...
67,326,410
67,326,456
Can I use union to convert between integers of various size?
Let's consider a union of integers of different sizes. Is it guaranteed that if a number fits the range of each of the integer types, it can be written to and read out from any of the union data members correctly? E.g. this code union U { int32_t i; int16_t s; } u; u.s = 1000; std::cout<<u.i<<std::endl;...
No, that only works in little endian. In big endian the bytes are stored from the most significant position down. 0xdeadbeef will be stored in memory as ef be ad de in little endian and de ad be ef big endian in memory so reading 2 bytes from the start address will result in 0xbeef and 0xdead in those machines respecti...
67,326,417
67,326,467
write an overloaded operator for less-than-or-equal-to
#include <iostream> using namespace std; class Card { private: // suit contains values 1-4, to represent suits below // 1 - Diamonds, 2 - Hearts, 3 - Clubs, 4 - Spades int suit; // value contains values 1 - 13 // Ace - 1, 2-10, J - 11, Q - 12, K - 13 int value; ...
Add extra if checks for aces. bool operator<=(Card &card) { if (card.value == 1) { return true; } else if (value == 1) { return false; } else { return value <= card.value; } }
67,326,423
67,326,531
Does wrapping a pointer in shared_ptr guarantee it will be deleted if I continue to use the raw pointer?
I have a hash table generated at runtime, populated by global variables. inline A* global1 = new A(); inline A* global2 = new A(); inline A* global3 = new A(); std::map<A*, int> createMap() { return std::map<A*, int>({{global1, 1}, {global2, 2}, {global3, 3}}); } I want to add new entries to map during runtime, ...
You are a bit betwixt and between with this. What you are proposing won't end well. Assuming that you actually need a map of pointers... If the map has sole ownership of the objects contained within it, use std::map<std::unique_ptr <A>, int>. If it shares ownership with other parts of your code, use std::map<std::sh...
67,326,509
67,326,637
It is referenced and I still get undefined reference issue
class base_rec { public: base_rec():str(" "){}; base_rec(string contentstr):str(contentstr){}; void showme() const; protected: string str; }; class u_rec:public base_rec { public: u_rec():base_rec("undergraduate records"){}; void showme() { cout <...
There are 3 issues with your program. First the way you define an override in C++ is by making the function in base class pure virtual. Then you can override the implementation in child class. Since you are defining an array of base class type objects which has no definition, C++ assumes you want to call the functions ...
67,326,570
67,326,710
How to avoid duplicating functions with a modular architecture
I am trying to implement the modular architecture with C++ where I have a .h file for every .cpp file. The files currently only have empty functions: cycle.h #include <iostream> #ifndef CYCLIST_H #define CYCLIST_H #pragma once class cyclist{ private: double width; double length; int helment; public: vo...
Step One: Apply Liskov Substitution Principle to make sure inheritance makes sense. Step One-A: Make sure Composition isn't a better fit. Step Two: Make base class class Base // For demonstration purposes only. Give this a more descriptive name in your code { public: virtual ~Base() = default; virtual void ...
67,326,751
67,327,738
Attempting to use debug tools in Visual Studio 2019 results in "Source Not Available" screen
I'm learning C++ and part of that is learning how to debug. My code works as written, but I want to be able to step through it line by line. I can start debugging just fine, but I can't use the debugging tools "Show next statement", "Step into", or "Step over". They all show a screen that says "Source not available; So...
You can confirm these options on your side: Project Properties > C/C++ > General > Debug Information format, the Program Database for Edit And Continue (/ZI) has been selected In visual studio, Menu Debug > Options > General, the Enable Just My code has been enabled After that, you can clean > build your project and ...
67,326,914
67,328,923
Standard Deviation of Linked Binary Search Tree
I am currently working on a project for my Data Structures Course that involves a Binary Search Tree built using a doubly linked list-type format (where each node has a left, right, and parent pointer). The class managing the tree also has a root pointer and a current pointer (like a cursor). One of the functions I nee...
I understand how to get the sum of the entire tree So you know how to inspect the value of each node and do something like: sum += current_node->value; Then keep track of a count too (unless you already keep track of the count as a list property): sum += current_node->value; node_count++; After you have visited all...
67,327,227
67,327,257
Random shuffle function works in main(), but not a class
I'm attempting to use a seeded random_shuffle to simply shuffle a vector, before I use it. I tested this out by doing #include <iostream> #include <map> #include <vector> #include <algorithm> #include <cstdlib> #include <bits/stdc++.h> using namespace std; int seed; int rng(int i) { srand(seed); return rand(...
rng is a global function. r is a member function of a class. Consider it from the viewpoint of random_shuffle. When it wants to call r, on what object will it call it? Since it knows nothing about your class it simply won't be able to. This is what the error message is trying to tell you (clumsily). One typical way wou...
67,327,598
67,341,593
How to initialize a vector of user defined objects, with member initializer lists, using size and value constructor
First, this is the code: #include <vector> enum class Color { black = 0, white = 1, }; class Pixel { private: Color m_color; public: Pixel(Color color = Color::black) :m_color{ color } { } }; class ScreenBuffer { private: std::vector<Pixel> m_screenbuffer; std::size_t m_width;...
I found the answer that I was looking for in here: learncpp.com/cpp-tutorial/anonymous-objects There is a concept called anonymous objects that let me use Pixel(some_color) as an rvalue and pass it as an argument of another constructor.
67,328,476
67,328,566
Why does the standard library have a template<>?
I saw code in the standard library where the template was declared but the typename was not specified. https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/cpp__type__traits_8h-source.html 00211 template<> 00212 struct __is_integer<int> 00213 { 00214 enum { __value = 1 }; 00215 typede...
Thanks to @Scheff, @chris. This is a template specialization of a template <typename T> struct __is_integer; https://www.cplusplus.com/doc/oldtutorial/templates/ https://en.cppreference.com/w/cpp/language/template_specialization 00147 // 00148 // Integer types 00149 // 00150 template<typename _Tp> 00151 s...
67,328,649
67,333,194
SetupGetInfFileList function is failing with ERROR_INSUFFICIENT_BUFFER if the directory path is too long
Can someone please tell me how to remove the ERROR_INSUFFICIENT_BUFFER in SetupGetInfFileList function when Directory path is long. TCHAR *aBuffer; DWORD BufferSize =0 , RequiredSize =0; BOOL bError = SetupGetInfFileList(DirectoryPath, INF_STYLE_WIN4, NULL, BufferSize, &RequiredSize); //First Call if (bError == FALSE...
ERROR_INSUFFICIENT_BUFFER indicates that the basic problem is that the buffer you provided is too small to hold all the data. Luckily, the function SetupGetInfFileListA (and also the SetupGetInfFileListW variant) has the parameter RequiredSize: If not NULL, points to a variable in which this function returns the requi...
67,328,896
67,329,255
Should we use or not constant type reference in arguments of a function?
Example 1. void f(int a); Example 2 (constant type reference). void f(const int& a); Is it better to use the second example because we don't create a copy of an argument object within a function? But why in most cases, even companies, use exactly the first example? I know about big objects - via the second example we...
Technically, a reference passed as function argument will be a pointer, it‘s just some syntactic sugar which makes the reference a bit different to handle compared to a pointer. Memory wise, the size of an int is 32 bit on most common platforms. The size of a pointer (and thus also the size of a reference passed as arg...
67,329,178
67,329,499
Why QFont and QFontInfo family poperties of one widget are different
So, these two lines: qDebug() << "ff1" << m_titleTreeView->font().family(); qDebug() << "ff2" << m_titleTreeView->fontInfo().family(); returns this result: ff1 "Verdana" ff2 "Noto Sans" My widget is QTreeView. Why it happen? I think that my result should be the same. All other props like pixelSize, weight, and po...
The difference is that QFont::family() gives you the requested font name, while QFontInfo::family() gives you the effective name. In more details, whenever you as for a specific font via the constructor of QFont, for instance, the OS looks for the best match via a rather elaborated font matching algorithm. QFont keeps ...
67,329,861
67,330,683
The reason why all pointers not-freed?
I am working on stack data structure implementation using linked lists , building destroyStack() function by which i can free all allocated memory once the i finish using stack class as i execute the main i expected to get all the pointers freed after destroyStack() has been called. class Stack{ private: in...
As @AlanBirties already mentioned in the comments, the problem is Node *temp = new Node(); in your pop() function. You have to do a delete for every new, so that's a block you are not deleting. However, you don't even need that new node... because that pointer's purpose is to hold the last, already existing, top node,...
67,330,077
67,350,523
How to implement text auto-completion of commands using dbgeng.h?
I am working on a front end for windbg which uses the pretty well documented dbgeng.h API. However there is some functionality that I don't know how to implement, such as tab auto-completion. I believe what I need are the following APIs: IDebugAdvanced3::Request DEBUG_GET_TEXT_COMPLETIONS_OUT DEBUG_GET_TEXT_COMPLETIONS...
the partial input is a wildcard so you need an asterisk following your input like ".db*" the out needs two iterations one for getting the size with S_FALSE and size of completions available the second with allocated memory after OUT as a typedeffed structure as IN the code below has a fixed size buffer in OUT as poc ...
67,330,405
67,331,515
Linear search vs binary search real time performance in C++
Getting totally unexpected results while comparing binary search vs linear search's real time performance in C++ using the code below - typedef std::chrono::microseconds us; int linear_search(uint64_t* val, int s, int e, uint64_t k) { while (s < e) { if (!less<uint64_t>()(val[s], k)) { break; ...
I benchmarked your code with https://quick-bench.com and binary search is much faster (for m = 100, it breaks for m = 1000). That's my benchmark code: int linear_search(uint64_t* val, int s, int e, uint64_t k) { while (s < e) { if (!std::less<uint64_t>()(val[s], k)) { break; } ++s; } ...
67,330,422
67,330,786
How to obtain O(log(N)) complexity of the counting std::map of specific value
I am thinking about the problem of counting elements of specific values of map and how to achieve O(log(N)) complexity in C++. It is would be only possible when it is sorted by the values I guess, but then it would not be sorted by keys and the get from map would be then O(N). In the first version I use std::count_if. ...
Boost's bimap allows lookup by either key or value. auto range = map.right.equal_range(val); std::distance(range.first, range.second);
67,331,181
67,331,270
Using getline to read but user need to use enter twice
To allow a multiple words user input I use getline and I flush the stream according to this answer with this code : while(!everyoneAnswered()){ string name; std::cout << "enter your name : "; if (getline(std::cin, name)) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize...
The problem are these two lines: if (getline(std::cin, name)) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); The getline call includes the newline, so your ignore call will read the next line of input. You need the ignore call after reading the age (with >>), but not after getline.
67,331,428
67,331,587
Calling a template with template parameters from a std::integer_sequence
Scratching my head. Given that I have the following integer sequence: std::integer_sequence<int,0,1,2> And I have the following template: template<int a, int b, int c> void myFunction() {} Is there any way to call the template with the integer sequence as template parameters? myFunction<std::integer_sequence<int,0,1,2>...
You might write a helper template, e.g. template<typename T, T... I> auto helper(std::integer_sequence<T, I...>) { myFunction<I...>(); } Then call it as helper(std::integer_sequence<int,0,1,2>{}); LIVE
67,331,445
67,332,653
Concept for string-like object
Is there a concept for a string-like object in standard library? What I mean is something like template<typename T> concept StringLike = requires(T x) { /* is same as const char*, char*, std::string etc */ } There is a question about handmade Type trait for strings. But I cannot found anything about concepts. Why i...
I was looking for a concept for a function, which accepts only const char*, char* and strings template<class T> concept StringLike = std::is_convertible_v<T, std::string_view>; did the trick for me :)
67,331,669
67,331,670
How to compile/use header units in MSVC from command-line?
For example I have following toy files: mod.hpp #include <iostream> use.cpp import "mod.hpp"; int main() { std::cout << "Hello, World!" << std::endl; } But if you compile it like cl use.cpp /std:c++latest then I get error error C7612: could not find header unit for 'mod.hpp' How do I create/use header units in ...
To create precompiled header unit issue next command: cl /EHsc /std:c++latest /exportHeader mod.hpp this command creates mod.hpp.ifc file, which is a precompiled header unit module. Here is documentation about /exportHeader flag. Then to use header unit issue command: cl /EHsc /std:c++latest use.cpp /headerUnit mod.hp...
67,332,197
67,332,352
Can you dynamically allocate a class with a vector as a field in C++?
I have a vector inside a dynamically allocated object. Like so: class VectorUser{ vector<int> v; //other stuff }; //somewhere VectorUser * vu = new VectorUser(); delete vu; Is this code safe? If so, how does c++ know how much memory to allocate when the size of the vector could be anything?
A vector<foo> consists of two parts: a fixed-size block consisting of a pointer and a count of elements, and a variable-sized block which the pointer points to. When you create a new vector<foo>, it contains no foos; the count of elements is zero, and the pointer (depending on implementation) is likely null. When you d...
67,332,217
67,332,410
Select an overloaded non-template function with std::function parameter
I have both template and non-template member function overloaded like the code below: struct TypeI {}; using FuncI = std::function<void(TypeI&)>; struct TypeA { FuncI m_fn; TypeA(FuncI const& p_fn = nullptr){ m_fn = p_fn; } }; struct TypeX { void add_A(int p, FuncI const& p...
The non-template version is taking std::function as parameter, and you're passing lambdas, which requires user-defined conversion. The template version is exact match and wins in overload resolution. You can impose restriction on the template parameter to make it unusable when object being passed could convert to FuncI...
67,332,244
67,332,265
Why C++ allows repeated + operators, like in x = 1 + + + + + + + + 2;
To my surprise this compiles fine: int main() { constexpr int x = 1 + + + + + + 2; static_assert(x==3); } I know C++ has weird complex grammar(and it tries to allow all C code to be valid), so I presume that is the case why this is allowed, but is there some good positive reason why we would not want this code...
In C++ it's possible to overload operators. Boost Spirit is a particularly good use case; using the C++ grammar to represent EBNF grammars. In such contexts, it might be useful to be able to have repeated + operators. (A personal example: I have some cash flow modelling code that uses + to advance by a period. Naturall...
67,332,691
67,332,738
C++ template-id does not match any template
Hi I'm trying to overload the << operator #include <iostream> using namespace std; template <class T, class U> class Couple { public: T cle; U valeur; public: Couple(); Couple(T, U); friend ostream &operator<<<>(ostream &, Couple<T, U>); }; template <class T, class U> ostream &operator<<(ostream &...
You need to declare the operator template in advance. e.g. // forward declaration for class template template <class T, class U> class Couple; // declaration template <class T, class U> ostream &operator<<(ostream &os, Couple<T, U> Cpl); template <class T, class U> class Couple { ... // friend declaration ...
67,332,749
67,333,146
c++ : warning comparing iterators
I have the following function to merge output for 2 containers : template <typename IteratorType1, typename IteratorType2> void Merge(IteratorType1 src1_begin, IteratorType1 src1_end, IteratorType2 src2_begin, IteratorType2 src2_end, ostream& out) { size_t i1 = 0, i2 = 0; size_t src1_size...
If you're sure that both containers contain values in the same range you can cast the values to the same type. Following code removes the warning: #include <climits> #include <iostream> #include <list> #include <vector> using namespace std::literals; template <typename IteratorType1, typename IteratorType2> void Merge...
67,334,310
67,334,332
error: 'vector' in 'class Processus<double>' does not name a template type|
I have an issue with my following code : template<typename T> class Processus { public: typedef pair<double, T> state; typedef vector<state> result_type; Processus(int n = 0) : v(n+1) {} ~Processus() {}; virtual result_type operator()() = 0; auto begin() const { return v.begin(); }; auto e...
It looks like because vector is not defined in the class Processus. Probably you mean this: ostream& operator<<(ostream& os, const Processus<double>::result_type& P) {
67,334,663
67,335,007
C++ map of polymorphic functions
I want to use a C++ map of function to execute some subroutines. Since, such a map of function requires to have the same type of input and output for all the mapped functions, while my functions can have different input type, I though I could made all these different types derive from a SuperParentClass. However, this ...
Rather than having a map go to functions it can map to a SuperParentClass pointer. Then use a virtual function in each class to encapsulate the desired behavior. int areaRect(ChildClassRectangle rect); int areaCircle(ChildClassCircle circ); class SuperParentClass { public: virtual int area() = 0; ... // more ...
67,335,254
67,335,398
What is std::views::all introduced for in C++20?
#include <vector> #include <ranges> int main() { auto v = std::vector{1, 2, 3, 4}; v | std::views::drop(2); // ok std::views::all(v) | std::views::drop(2); // also ok } Successfully compiled with g++11 -std=c++20. But I cannot tell any difference between v | std::views::drop(2) and std::views::all(v) | st...
But I cannot tell any difference between v | std::views::drop(2) and std::views::all(v) | std::views::drop(2). Indeed, there is no difference between the two - because v | views::drop(2) already means views::all(v) | views::drop(2). views::all is an implementation detail of Ranges to ensure that range adaptors always...
67,335,384
67,335,446
Why do I get a seg fault when trying to access a character in a string
I'm trying to store commands in a queue and read them from the queue later on. I'm using this queue because the code needs to run on an Arduino. When accessing the first (or any) character, I'm getting a segmentation fault. What am I doing wrong here? int main() { cppQueue q(sizeof(char*), 10); char c1[] = {'a'...
Arrays are not pointers. Arrays can automatically converted to pointers in most case of expressions, but one of the exception is used with unary & operator. With q.push(&c1);, the queue will read the contents of the array (plus some garbage for out-of-range region) instaed of a valid pointer value. Use a pointer variab...
67,335,616
67,335,998
What is wrong with parsing this time string for 'std::chrono'?
I simple want to parse a time-string to a chrono::system_clock::time_point using: #include <iosfwd> #include "date/date.h" std::stringstream ssTime; ssTime << "17:34:05"; std::chrono::system_clock::time_point tp_time; ssTime >> date::parse("%H:%M:%S", tp_time); I expected to get the time_point of the specified time a...
The design of the parse function is that if you don't parse enough information for the type being parsed, the failbit is set on the stream. parse considers the {h, m, s} information insufficient for uniquely determining an instant in time (a system_clock::time_point), so this parse fails. You can make this work by par...
67,335,916
67,336,557
float for loop, core dumped c++
I don't understand what I'm doing wrong. My code should just increment i: 0.1 from zero, and add 0.5 to each position, really simple, but instead I get segmentation fault (core dumped). Can someone give me hand? vector<float> sinal; int main(){ sinal[0] = 0; for (float i = 0.1; i <= 1; i += 0.1){ sinal[i] = si...
Two problems here: 1. When you access sinal[0] and sinal[i], sinal does not have any capacity yet. 2. Using a floating point number as a subscript is unusual, and could make errors happen. The subscript is normally the offset of the item you want to access, so if I want to access the fifth element, I use a subscript of...
67,335,987
67,338,686
C++: "Iterable<T>" interface
What I want to achieve is probably easily explained: Consider I have an abstract class that I know will contain multiple objects of known type. However the actual container holding these objects will be implemented in sub-classes. In my abstract base class I now want to provide an interface to iterate over these object...
With the help of @FrançoisAndrieux and a hint from https://stackoverflow.com/a/4247445/3907364, I was able to come up with an approach to my problem. Essentially the idea is to create an iterator-wrapper that stores a function to obtain an object of the given type if given an index. That index is then what is iterated ...
67,336,159
67,336,355
c++ code not giving output (topic : recursion and 2D vector)
You are given a number n, representing the number of rows. You are given a number m, representing the number of columns. You are given n*m numbers, representing elements of 2d array a. The numbers can be 1 or 0 only. You are standing in the top-left corner and have to reach the bottom-right corner. Only four moves are...
You need to add references to your vectors. C and C++ are pass by value languages you need to explicitly tell C++ that you are passing by reference. void floodfill(vector<vector<int>>& maze, int sr, int sc, string psf, vector<vector<int>>& visited) { if (sr < 0 || sc < 0 || sr == maze.size() || sc == maze[0].size()...
67,336,201
67,336,495
Why using global variabes makes the multi-threaded execution 2x slower while in other environment it makes it 2x faster?
The code below was taken from an example compiled with g++. The multi-threaded was 2x faster than the single-threaded. I'm executing it in Visual Studio 2019 and the results are the opposite: the single-threaded is 2x faster than the multi-threaded. #include<thread> #include<iostream> #include<chrono> using namespace s...
You are a victim of false sharing. odd and even reside next to each other, and accessing them from two threads leads to L3 cache line contention (a.k.a false sharing). You can fix it by spreading them by 64 bytes to make sure they reside in different cache lines, for example, like this: alignas(64) ll odd, even; With ...
67,336,225
67,466,959
Why is this binary vulnerable to buffer overflow?
This is an extract of a binary that is buffer overflowed. I decompiled it with Ghidra. char local_7 [32]; long local_78; printf("Give it a try"); gets(local_7); if (local_78 != 0x4141414141414141) { if (local_78 == 0x1122334455667788) { puts ("That's won") } puts("Let's ...
This binary is vulnerable to a buffer overflow because it uses the gets() function, which is vulnerable, and deprecated because of that reason. It will copy the user input to the passed buffer, without checking the size of the buffer. So, if the input of the user is larger than the available space, it will overflow in ...
67,336,260
67,336,280
char array not returning correct size
Serial.begin(57600); char testArray6[6] = {'1', '2', '3', '4', '5', '6'}; Serial.println(testArray6); Serial.println(strlen(testArray6)); char testArray5[5] = {'0', '0', '0', '0', '0'}; Serial.println(strlen(testArray5)); char testArray4[4] = {'0', '0', '0', '0'}; Serial.println(strlen(testArray4)); c...
Strings in C are null-terminated sequences of characters, so what are passed to strlen() must be pointers to null-terminated sequence of characters. Add terminating null-characters to the array to fix: Serial.begin(57600); char testArray6[7] = {'1', '2', '3', '4', '5', '6', '\0'}; Serial.println(testArray6); Se...
67,336,264
67,336,360
Casting a negative const double to unsigned results in 0 while non-const double is fine
I have this code: #include <iostream> int main() { double val = -400.0; const double constVal = -400.0; std::cout << val << std::endl; std::cout << static_cast<unsigned>(val) << std::endl; std::cout << constVal << std::endl; std::cout << static_cast<unsigned>(constVal) << std::endl; return...
From cppreference.com: A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithm...
67,336,499
67,336,825
cmake cannot find libsndfile
Cmake seems not to find the lib libsndfile. However, it installed on my machine. find_library(sndfile REQUIRED) And installed : yum list installed | grep libsnd libsndfile.x86_64 1.0.25-11.el7 @base libsndfile-devel.x86_64 1.0.25-11.el7 @base The...
It doesn't mean much if it is installed on your machine or not. CMake won't search all your computer for the library. The best thing you can do is to add the location of the installed library to your PATH environment variable. Here's what CMake documentation says about find_library() HINTS and PATHS arguments: HINTS, ...
67,337,271
67,338,367
How to handle multiple possible early returns from function without lots of duplicate checking code
Given that I do not want to use exceptions in this code, how can I remove the duplicated: if (rc != SQLITE_OK) { return rc; } checks after most statements in this function below? int sqlite::update(const std::string& table_name, const std::vector<column_values>& fields, const std::vector<column_values>& where) { ...
First off, you are leaking the sqlite3_stmt if something goes wrong. You need to call sqlite3_finalize() before return'ing anything. As for your question, you can wrap the duplicate if..returns in a preprocessor macro, eg: #define CHECK_RC(rc) \ if (rc != SQLITE_OK) \ { \ sqlite3_finalize(stmt); \ return rc; \...
67,337,295
67,364,897
Can't set CMake configuration parameters from Visual Studio
I am trying to use the entire CMake workflow from Visual Studio. I created a folder with a CMakeLists.txt file along with the code, and Visual Studio magically builds and configures it with the parameters I specified in the CMakeLists.txt file. However, I can't seem to configure the parameters that I am able to configu...
I suggest you could refer to the following docs: Configure and build with CMake Presets in Visual Studio Customize CMake build settings
67,337,740
67,337,992
Initialising a 2d map c++
I have been thinking lately about 2d structures (of integers) in which their sizes can grow dynamically. I came across 'map' which I think that it meets my following need: Essentially, what I want is to check whether a random entry has been initialized or not (do something if it has not been initialized yet). int main(...
If what you mean by checking whether an entry "has been initialized" is checking that a pair of keys has a value assigned to them -- one key for the outer map and one for the inner map -- you can test contents of a map of maps as below: bool contains_keys(const std::map<int, std::map<int, int>>& map_of_maps, int key1, ...
67,337,750
67,337,776
Declared a structure variable which is a dynamic array of another structure. Why is the following C++ program being crashed?
I have declared a structure variable which is a dynamic array of another structure but the program crashes every time. Where am I doing wrong? What are the necessary steps to be taken? I am using DEVC++. #include<iostream> #include<cstdlib> using namespace std; struct Project{ int pid; string name; }; struct...
malloc() does not initialize compilcated classes properly and shouldn't be used in C++. You should use new or new[] instead. e.project_list = new Project[2];
67,337,761
67,337,824
I keep get the same error everytime I compile a C++ code with VScode
I made some code a long time ago that actually worked, but recently when I try to compile it with VScode, this error keeps showing up even when I delete all the modification i did: Au caractère Ligne:1 : 22 + g++ main.cpp -o main && main + ~~ Le jeton « && » n’est pas un séparateur d’instruction va...
Apparently it's a bug in VSCode. Install a fixed version and try again.
67,337,781
71,285,121
How to dump CLion's default clang-tidy configuration?
I want to use the default configuration of enabled/disabled checks from CLion (with some small changes) and I want to enforce it when building my application. Enforcing clang-tidy works perfectly by using the cmake directive for clang-tidy, for example with all checks enabled: set(CMAKE_CXX_CLANG_TIDY clang-tidy; -ch...
Copy the list of rules from Clion to a file named rules.txt: Then: clang-tidy -checks="$(cat rules.txt | tr '\n' ',' | sed 's/,$//')" --dump-config > .clang-tidy Here is a gist with the result as the day of writing this: https://gist.github.com/ArnaudValensi/0d36639fb84b80ee57d0c3c977deb70e
67,338,370
67,339,186
Why does my project/VS/Task Manager all show different memory usage? C++
Me and a small team have been working on a project that is starting to take up quite a lot of memory (for a domestic program). We are using C++20, and to my knowledge don't use anything other than smart pointers in the project. We believe we have a memory leak somewhere, but are finding it hard to track down, and have ...
Check this out: msdn page Task manager provides the working set (i.e. how much memory you use). Visual Studio Profiler shows the total virtual memory used for storage and not shared.
67,338,403
67,338,446
Pointer to a base virtual member function
Is there a way to make a pointer on member function in base class if it is a virtual function and it is overridden in derived class? Consider the code as follows #include <iostream> #include <functional> struct Base { virtual void g() const { std::cout << "Base" << std::endl; } }; struct Derived :...
You might define a non-virtual function real_g called from g so code struct Base { void real_g() const { std::cout << "Base" << std::endl; } virtual void g() const { real_g(); }; }; Then later in main std::mem_fn(&Base::real_g)(d); See wikipage on virtual method table, this C++ reference and the C++ standar...
67,338,884
67,344,602
Passing array from nodejs to C++ using node addon
I previously asked this question and got berated NodeJS/C++ addons - Passing an array from node to C++. However I made it very clear in the question that I want to pass this array from NodeJS to C++ via a C++. One of the answers was to use JSON, is there any other way to do this?
Please checkout this example passing array to c++
67,339,059
67,527,334
Assimp update to 5.0.1 issue with bone mname and mnumweights
Assimp was working fine previously, but with the update to 5.0.1 it seems bone mName and mNumWeights are messed up. What am I doing wrong here? I changed nothing regarding the model or the following printf statements.
Yep, it was an error on my end. Just set up another project with 5.0.1 and it works fine. I think I forgot to copy over the config.h after building assimp. Okay, I'll follow the link if I run into any issues
67,339,061
67,342,241
g++ Show warnings for uninitialized variables without optimizing out variables
I have the following example program that I want to debug: #include <iostream> #include <assert.h> using namespace std; int f(int x) { assert(false); // something bad happens return 2 * x; } int main() { int a; for (int i = 0; i < 5; i++) { a++; // a is uninitialized cout << a << e...
Is this possible with g++? No. Unfortunately, GCC performs the "is value used uninitialized?" analysis in one of its optimization passes, and disabling optimization also disables that pass. Contrast this with Clang/LLVM, which had an explicit goal of not making warnings dependent on optimization. clang++ -Wall -Wextr...
67,339,980
67,340,716
Is it possible to create a template that generates a fully const implicitly convertible struct from another struct?
I have a problem where I need to bundle an ID with a reference/pointer to a value in C++, e.g.: struct ProductWithID { int id; Product* product; } Sometimes I want to use this with a mutable Product* so the above will work, but other times I want to pass this to functions when I originally have a const Product...
Okay, so I solved this by utilizing the nice property that a std:tuple with type T at position N is implicitly convertible to another tuple with type const T at position N: template<typename T> class Keyed : public std::tuple<int, T*> { public: using std::tuple<int, T*>::tuple; int id() const { return std::ge...
67,340,266
67,340,515
Uninitialized memory warning on structs instantiated with new
So I have a Node struct struct Node { int x = 0; }; I make 20 Node*s. My understanding is that Node** is a pointer to the start of an array that holds pointers to Nodes. constexpr int mazeSize = 20; Node** testMaze = new Node * [mazeSize]; After this, I started getting warnings and errors when I tried to do anyth...
Always remember that pointer types are separate, concrete types with their own type and size. A pointer to T T* basically boils down to a small chunk of memory that is used to store an address to another memory area, which (hopefully) contains an instance of some type T. With Node** testMaze = new Node * [mazeSize]; yo...
67,340,334
67,343,376
C++ vector move semantics
Here is my situation: I have a class like this: class JSON { private: std::vector<JSON> children; ... public: JSON& operator[](std::string propertyName); ... } How are move semantics applied? Does it make any difference if they are used? I feel like if I do std::swap(json["hello"], json["world"]) The swap of the 2 JS...
From what I understand, if I wanted to use Move Semantics efficiently, I would need to have a pointer to my vector of children to std::move that pointer effortlessly, am I correct in saying that if my class has no pointers, it is useless to std::swap? No that's not true in general, the standard library container clas...
67,340,521
67,341,419
Call function pointer at void* on object at void* OR Identify function so you will be able to compare the bindings
I'm creating my own delegate implementation (I'm looking at C# delegates). I have an object-function binding struct struct ObjFunc { void* obj = nullptr; void* func = nullptr; ObjFunc(void* obj, void* func) : obj(obj) , func(func) { } }; And I have a Call function void Call(InTypes...
Well, even if it's impossible to call a function from pointer, second task (identify function in uniform format) still may be solved. You can use memcpy to copy data from function pointer. Example: template<typename FSIG> char* get_function_identifier(const FSIG& func_pointer, int& size) { size = sizeof(FSIG); ...
67,340,554
67,370,566
Enable Different Member Functions Depending On If Type Is POD
I believe this is fairly simply to achieve, but I can't figure out how. Take the following example class: class Example { public: template <typename T> size_t foo(T& v) const; }; How can I provide two implementations for this method depending on if T is a POD? I know there is an std::is_pod type trait, but I ...
Here is what I did to get it to work correctly: #include <type_traits> #include <iostream> class Example { public: Example(int a) : _a(a) {} virtual void bar() {} template <typename T, typename std::enable_if<std::is_trivially_copyable<T>::value, size_t>::type = 0> size_t foo(T& v) const { ...
67,340,584
67,342,053
How to open specific windows to specific buttons on wxWidgets?
I did my research before coming here and couldn't find anything helpful. Please bare with me as I'm a newbie in wxWidgets and C++ GUI. I created a 3x3 grid, each button with its own purpose. When clicked, some should open a new page containing at least what the button text says, and other buttons should direct you to t...
The button ID and the EVT_BUTTON(id) don't match. e.g. Button 0's id is 10000, not 0.
67,340,908
67,340,945
What's the difference between a coroutine and a function with static variables?
I've been learning about what's new in C++20 and I'm trying to understand the commonly discussed "Generator" use case of co-routines. I've tried to create a small example here but apologies if there is some mistake: generator<int> Generate() { int i = 0; while(1) { co_yield i++; } } int main() { ...
Perhaps the most obvious difference is that static local variables means you effectively have one instance... total. Whereas each generator is completely independent. // with coroutines assert(Generator().next() == 0); assert(Generator().next() == 0); assert(Generator().next() == 0); assert(Generator().next() == 0); E...
67,341,251
67,346,359
Should `typename T::value_type` fail to compile when it is meant to be rejected by a constraint that comes later in the definition?
The following code: #include <concepts> template <typename T> struct Foo { template <std::convertible_to<typename T::value_type> U> requires requires { typename T::value_type; } void bar() { } template <typename U> void bar() { } }; int main() { auto foo = Foo<float> {}; foo.bar<int>(); } is rej...
The standard is quite clear that constraints are only substituted into at the point of use or when needed for declaration matching: The type-constraints and requires-clause of a template specialization or member function are not instantiated along with the specialization or function itself, even for a member function ...
67,342,085
67,342,115
Make a function in the base class aware of the class of the object calling it
I mean to define a function in the base class that is able to print the class of the object calling it, resolving correctly if it is of any derived class. For instance this (expectedly) fails: //====================================================== // demangle is copied from https://stackoverflow.com/a/4541470/2707864...
Simple solution, replace type(this) with type(*this). It works, although I don't know how to explain it.
67,342,228
67,342,337
Code gets stuck when I try to call a pointer method
I may or may not be dumb, but I don't see any reason why my code should work like this instead of how it's supposed to, but any explanation is welcome, as I'm completely lost in my assignment. The part where I run into a problem is this part: In this part, the problem occurs in the inner for in the do while loop, legre...
There are no lines that sets the member variable alakul to values other than nullptr. Then you dereferenced alakul (nullptr) in the function simulate() like: *alakul = Oxigen(newvastagsag*0.05, "Oxigen"); This is wrong. Instead of this, I guess you wanted to allocate new object and assign that to alakul like alakul = ...
67,342,436
67,342,490
What is best practice to delete dynamically allocated memory?
I have to reassign iScreen and oScreen many times with new keyword. I found that I have to delete them every single time before reassign new heap memory. It seems like bad practice to me. Is there any better way to solve this code repetition? Matrix* oScreen; Matrix* iScreen; iScreen = new Matrix(100, 100); oScreen = ...
Consider holding your dynamic objects in a container like std::vector if you can. Otherwise, they should be managed by a smart pointer like std::unique_ptr. std::unique_ptr<Matrix> iScreen; iScreen = std::make_unique<Matrix>(100, 100); // do something with iScreen iScreen = std::make_unique<Matrix>(150, 150); // no ...
67,342,473
67,342,509
Passing lambdas as C function pointers
I'm working on a C++ class that passes captureless lambdas to a C library. I'd like to remove some boilerplate, and the lambdas are all very similar (they find an instance of a class and invoke different methods that all take a single int parameter). I created a template function: typedef unsigned char (Foo::*FooMemP...
You can make callback template parameter, and specify template argument instead of passing function argument when calling createEditLineCommandDescriptor. E.g. template<typename Fn, FooMemPtr callback> tuple<const char*, const char*, Fn> createEditLineCommandDescriptor(const char* command, const char* helpText) { ret...
67,342,543
67,377,604
Prevent Child class from accessing protected member variable of "Grandparent" class
I have a base class called "Grandparent" with a special protected member variable like: class Grandparent { protected: MyClass m_obj; } I have a class "Parent" that derives from this and monitors access to the m_obj member variable with special getters and setters: class Parent : Grandparent { protected: void se...
MatG's comment about searching "c++ inheritance change member access specifier" answered by question. I didn't realize you could change the access modifier of a parent class member in a derived class. class Parent : Grandparent { protected: void setObj(val) { m_obj = val; } MyClass getObj { return val; } private:...
67,342,840
71,716,161
How to install Eigen3 on the docker image created by 'cibuildwheel' in GitHub actions
I am currently developing a C++/Python package using pybind11 for the Python bindings. This project is mixed: it has parts which are written in Python and other parts which are written in C++ and are compiled as an external module. The project uses cmake>1.7. Roughly this is the directory structure of the project: Pyth...
Use yum instead of apt-get: yum install eigen3-devel as per OP esocrats' prior edit to the question.
67,343,216
67,343,649
Automatically modifying C library to be used by C++
I'd like to make a tool that automatically wraps C libraries in: #ifdef __cplusplus extern "C" { #endif But I'm confused by what exactly needs to be wrapped with extern "C", and what needn't be. Only functions? What about any (shock-horror) global variables? Anything else? If I write a script that just finds all funct...
It does not matter, because anything that does not need it (such as macros and comments) will be unaffected by it, so you can just wrap the entire header content - and that hardly requires a a "tool". Also not this is not "modifying the library", just modifying the header. Nested wrapping is benign - applying C linkage...
67,343,574
67,343,676
Can't use std::filesystem in code built with make and g++
I have some problems with building my c++ app with make. I have such c++ code: #include <string> #include <iostream> #include <filesystem> using namespace std; namespace fs = std::filesystem; int main() { auto iter = fs::directory_iterator(fs::current_path()); while(iter._At_end()) { cout << iter...
Just don't use _At_end() and everything will be ok.
67,343,673
67,343,851
C++20 std::invocable syntax
I want to write this template <typename F, typename... Args> requires std::invocable<F&, Args...> void applyFunction(F&& f, Args&&... args) { } without requires clause, so I want something like template <std::invocable<F, Args...>> void applyFunction(F&& f, Args&&... args) { } ...but it fails to...
Using a concept in place of typename in a template parameter list only works when you are replacing one of the concept's template parameters. Specifically, the first one. If you have two (or more) template parameters that share a relationship, odds are good that you will need to have a requires clause. And you need to ...
67,344,216
67,345,533
Error:sorry, unimplemented: string literal in function template signature while Using decltype in function template
Hi i am trying to understand how templates work and trying out different examples. I am getting an error while executing the code below. First i am writing the code and then will write what i think is happening. Code snippet 1: #include <iostream> #include<vector> #include<string> template<typename It> auto fcn(It beg...
This is GCC bug 47488, which has been resolved in GCC 9. Upgrade your compiler. The function body is irrelevant. GCC simply couldn't deduce anything if the expression contained a string literal, so it gives up at decltype(*beg + "name"), which (like you correctly pointed out) should resolve simply to std::string when *...
67,344,683
67,344,771
How can I actually use the compilation options set during cmake?
This is probably a very simple thing but I can't find an answer for it. For example I have the following compilation option in CMakeLists.txt set(CMAKE_CXX_FLAGS_DEBUG "-O1 -g") How can I use it? Doing make CMAKE_CXX_FLAGS_DEBUG fails. I also can't directly do make -O1 -g CMakeLists.txt (shortened a bit and the name...
If you define a target in cmake after setting variable, cmake initializes the properties of the target with the value of the variable, if you specify the right build type. No make options necessary; (I recommend using cmake --build . instead anyways to be build system independent.) ... set(CMAKE_CXX_FLAGS_DEBUG "-O1 -g...
67,344,685
67,345,871
How do I control the behavior of multiple child process using wait();
I'm trying to create a program where a parent process does some computation and sends it over to the child process, The child process forks another process and does some more computation and sends it over to the child2 process for further processing. I can't seem to figure out how to do this. My Output is all messed up...
The wait call returns as soon as any child in the same process group terminates (thus including any grandchildren). When you want to wait for a specific process, use waitpid instead. You should also check the exit code and the status. Finally, you should wait for the child to exit after interacting with it via the pipe...
67,344,812
67,347,052
What does "non const-qualified" mean?
I'm trying to pass an array by reference to funcA. void funcA(int(&a)[], int k); int main() { int n = 5; int x[5]; funcA(x, n); return 0; } However when I try to, it throws this error. A reference of type "int (&)[]" (non const-qualified) cannot be initialized with a value of type "int [5]" I tried ...
First of all, you cannot have a reference to an array of unbound size. The closest thing is a reference to a pointer (to the array), i.e. int * (&a). This still gives a problem because a is not constant and the passed parameter x is a constant (the location of the array) - this is actually what the compiler error in th...
67,344,930
67,346,754
Conditional boost::range::join
I want to write a function like this: template<class IterableType> void CheckAndProcessIterables(IterableType& a, IterableType& b, IterableType& c) { IteratorRangeType range{}; // empty range if (Check(a)) { range = boost::range::join(range, a); } if (Check(b)) { range = boost::range::join(range, b); ...
You can use type erased iterator ranges, which Boost has in the form of any_range. Beware of the performance cost of these, which can quickly become very noticable. I'd rethink the approach unless you're very sure that this not on any hot path and readability is a much more of a concern than performance. Live On CoComp...
67,345,298
67,345,371
cpp having a property with the same type of the same class
Hello i wanted to have a chained object structure where in the class i have 2 properties of same the class type as the class inside of the class i working on. Like: class Base; class Base { private: Base * m_prev; Base * m_next; public: Base (Base prev, Base next) { m_prev = prev;...
Your constructor should be Base (Base *prev, Base *next): m_prev(prev), m_next(next) {} m_prev and m_next are pointers. You don't need the forward declaration. That's a working example: class Base { private: Base *m_prev; Base *m_next; public: Base (Base *prev, Base *next): m_prev(prev), m...