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
70,088,044
70,088,152
reversing coordinates in an array variable C++
I am not exactly sure how to phrase this question, sorry for the unhelpful title. I have a large array (5 columns, 50 rows) that I am using to draw out a level environment in ascii text (each entry in the array is a single character and they are all printed out to make an image) i.e: char worldarr[5][9] = { ...
Instead of trying to completely remap your array, you could instead wrap the array in a class. Something like: class World { private: static const size_t COLS = 5; static const size_t ROWS = 9; char worldarr[COLS][ROWS] = { {'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'}, //the length of these en...
70,088,319
70,088,351
Any possibility that I can remove the next line of the code?
... vector<pair<string,double> > wordsWeight; wordsWeight.clear(); ... I am reading a project's code and I often found that the author create variables like above: it first declares an empty vector and then immediately call clear() on it. If it is empty, why should clear() do anything useful? Can I safely remove it a...
If it is empty, why should clear() do anything useful? It doesn't. Can I safely remove it Yes. and similar statements Depends on details.
70,088,374
70,088,850
C++ - Overloading vs Overriding in Inheritance
As far as I learned, Overriding is when you have 2 functions which have the same name and function return type (void, int, float.. etc) and the same parameter numbers and types. And the overloading is when you have 2 functions which have the same name but either Parameter number/types or function return type should be ...
In C++, any method in a derived class only overrides the method in the base class if their declarations match (I say "match" but I don't know the formal term for that). That is, all arguments must have the same type, and const qualification of this must be the same. If anything there mismatches, the method in the deriv...
70,088,450
70,088,486
Default value for parameter of class where value is another class
Title may be a little bit confusing but basically I have a class 'Quaternion' which has 2 parameters, the first being another instance of a class Vector3 and the other being a float. Vector3 takes 3 floats as parameters and assigns them to x, y, and z. I want to set default parameters for the Quaternion class but I am ...
I think this is what you were looking for: class Quaternion { public: Vector3 axis; float scalar; Quaternion(Vector3 uAxis = Vector3(1.0, 0.0, 0.0), float uScalar = 0) { axis = uAxis; scalar = uScalar; }; }; It is possible to call a constructor of a class to set a default parameter. Here...
70,088,834
70,090,582
Replace C++ preprocessor macro with something that can initialize a struct
I'm working with WinAPI's CreateDialogIndirect function, which has some requirements on the DLGTEMPLATE and DLGTEMPLATEEX structures pointed to by the second parameter. My code works well, however, I would like to get rid of the #define macros. I created a simplified example to focus on the macros. This is a working pr...
A template is a reasonably common replacement for macro usage. Since you don't want to manually calculate the length of the string (I don't blame you), let's make a length (the array length, not the string length) the template parameter. Your anonymous struct becomes a likely candidate for being the templated entity, a...
70,088,953
70,088,983
C++ what does the error of "Initial value of reference to a non-const must be an lvalue" mean in this case?
I am a complete beginner to C++ and was assigned to write a function that returns the factors of a number. Below, I have included the function I also created called print_vector that will print all of the elements of a vector to the Console. In my assignment, in order to check if the factorize function is working, we h...
The error is from this line: void print_vector(std::vector<int>& v) { Since you didn't include the const keyword in the argument-type, you are (implicitly) indicating that print_vector has the right to modify the contents of v. However, you are calling print_vector() with a temporary object (the vector returned by fac...
70,090,424
70,090,488
make prototype of overloading function c++
I want to make a overloading function with a prototype in C++. #include <iostream> using namespace std; int rectangle(int p, int l); int main() { cout << rectangle(3); return 0; } int rectangle(int p) { return p*p; } int rectangle(int p, int l) { return p*l; } I got error at int rectangle(int p, ...
You've to declare the function before you use/call it. You did declare the 2 argument version of rectangle function but you seem to forget to declare the 1 argument taking version. As shown below if you add the declaration for the 1 argument version then your program works(compiles). #include <iostream> using namespace...
70,090,484
70,090,553
OpenGL: Batch Renderer: Should Transformations Take place on the CPU or GPU?
I am developing a 2D game engine that will support 3D in the future. In this current phase of development, I am working on the batch renderer. As some of you may know, when batching graphics together, uniform support for color (RGBA), texture coordinates, texture ID (texture index), and model transformation matrix go o...
Should Transformations Take place on the CPU or GPU? It really depends on the situation at hand. If you resubmit your vertices every frame, it's best to benchmark what's best for your case. If you want to animate without resubmitting all your vertices, you don't have a choice but to apply it on the GPU. Whatever the ...
70,090,540
70,090,865
Sharing global variable from C++ library to C main program
I have gstdsexample.so, a C++ library. Inside, it has two global variables that I'd like to share between the library and the main C program. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *ptr; Test two scenarios. Scenario 1 sharedata.h #ifndef __SHARE_DATA_H__ #define __SHARE_DATA_H__ #include <stdio.h> #in...
in a header file... gstdsexamle.h // disable name mangling in C++ #ifdef __cplusplus extern "C" { #endif // declare your two vars in the header file as extern. extern pthread_mutex_t mutex; extern int *ptr; #ifdef __cplusplus } #endif in gstdsexamle.c #include "gstdsexamle.h" /* only initialise here */ pthread_mu...
70,090,770
70,091,183
Passing float to a function in C++ appears to change precision
This is a very noob question, but I am curious to know the reason behind this: -If I debug the following C++ code: void floatreturn(float i){ //nothing } int main(){ float a = 23.976; floatreturn(a); return 0; } Monitoring the passed value of a, it appears to be 23.9759998 when entering floatreturn....
The issue happened before floatreturn(a);. It happened at float a = 23.976; floatreturn(a); is irrelevant. There are about 2^32 different values that float can encode exactly. 23.976 is not one of them. The nearest encodable float is about 23.9759998... To avoid, use values that can exactly encode as a float or toler...
70,090,929
70,091,811
Can variables be used in function call in ellipsis functions in C++
For this function that takes variable number of arguments, void func(int count, ...) // ellipsis function { // function definition } Can a function call be made like follows : int a{}; double b{}; string c{}; func(3,a,b,c); // using actual variables instead of fixed values in function call My question is when an el...
Note that passing classes like std::string, with non-trivial copy constructor or nontrivial move constructor or non-trivial destructor, may not be supported and has "implementation-defined" semantics. You have to check your compiler documentation on how such classes are passed or check if they are supported at all. Ca...
70,091,028
70,091,115
segmentation fault with char* buffer in getline() function
I get segmentation file in the below code. The reason is in the line 10 I guess where I'm using char* buffer. I want to know why is this. Is it because the memory in the buffer is not still allocated? Here is the code: 1 #include <iostream> 2 #include <fstream> 3 4 int main() 5 { 6 const char* filename ...
Is it because the memory in the buffer is not still allocated? Yes. In fact, you don't even have a buffer. The pointer buffer is NULL, meaning it points to a memory location that you have no business accessing. You then went ahead and told getline() it can write up to 100 bytes starting from that address. It worke...
70,091,096
70,102,583
How to return intersecting linestrings in boost::geometry::intersection(ring1, ring2, vector_of_linestring)?
I have 2 rings A and B, and I want to use boost::geometry::intersection() to return linestrings (the orange arrow ones): But my code only returns the intersecting points P1 and P2. Which part should I modify? #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geome...
I've tried to get a handle on this problem using just the DE-9IM that Boost Geometry implements: https://godbolt.org/z/KWzvzExr7 which outputs https://pastebin.ubuntu.com/p/9ck6gcPK5P/ ---- void do_test(Input, Input) [with Input = boost::geometry::model::ring<boost::geometry::model::point<int, 2, boost::geometry::cs::c...
70,092,075
70,092,253
How do you pass user input from main to other classes?
#include <iostream> #include "multiplication.h" #include "subtraction.h" using namespace std; int main() { multiplication out; subtraction out2; int x, y, z; int product; int difference; cout << "Enter two numbers to multiply by: "; cin >> x; cin >> y; product = out.mult(); ...
You should pass them to the function call as arguments difference = out2.sub(x, y); In the .h files you should define them with arguments class subtraction { public: int sub(int x, int y); }; Function overloading
70,092,277
70,093,623
How to replace NDEBUG by C++ means
So I use preprocessor macro NDEBUG to enable some checks for my debug build. But I would like to replace it with C++ constant to use it in noexept clause and in static if. I know I can probably achieve it like so: // in constants.hpp #ifdef NDEBUG constexpr bool ndebug = true; #else constexpr bool ndebug = false; #end...
If you use variable or function, you will probably have ODR violation if you mix file with NDEBUG defined or not with those variable/function. You can though declare a MACRO with a value matching NDEBUG presence. #ifdef NDEBUG # define NDEBUG_VALUE true #else # define NDEBUG_VALUE false #endif to use it in noexept cl...
70,093,274
70,093,437
^ after data type in Visual C++
What does ^ mean near the c++ data type? This seems to only work in visual studio C++ and is clearly not a standard C++ syntax, so what does it do here? I am familiar with pointer * and reference &, but to see ^ after the data type, I have no clue.
In C++/CLI and C++/CX, ^ is the Handle to Object Operator: The handle declarator (^, pronounced "hat"), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible. ... Because native C++ pointers (*) and references (&)...
70,093,511
70,095,761
how to write a C++ debug function in Windows?
I want to write a windows debug function like linux one: #define debug(fmt, ...) printf("[%s:%d]"fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
In order for string concatenation like that to work, you need spaces between the strings. So this part: "[%s:%d]"fmt"\n" changes to "[%s:%d]" fmt "\n" Otherwise, fmt is assumed to be a string literal operator (operator""fmt), which you don't want here. Don't forget to include <cstdio> for printf, and then it should w...
70,093,863
70,110,667
Linux BTF: bpftool: Failed to get EHDR from /sys/kernel/btf/vmlinux
I am trying to start with BPF CO:RE Development. Using Ubuntu 20.04 LTS in a VM, I needed to recompile the kernel and install pahole (from apt install dwarves) so that BTF is enabled (I set CONFIG_DEBUG_FS=y and CONFIG_DEBUG_INFO_BTF=y). So my setup is: Ubuntu 20.04 Kernel 5.4.0-90-generic bpftool --version: /usr/lib/...
You need to update bpftool to support a fallback to reading BTF as raw data if the input file is not an object file. The minimum bpftool version required is v5.5 as that's the Linux release where the patch landed. In general, I would recommend to always use the latest bpftool version as there are no backports.
70,093,991
70,094,081
GCC #pragma or command options
If the compiler has some command-line flags and the code has some pragmas that are incompatible with those flags, which one will be used? To be clearer: I am compiling with g++ -g -O2 -std=gnu++17 -static {files} – GCC version g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0. If I write in my code #pragma GCC optimize("Ofast"), will...
That depends on if it's above or below the pragma. void this_will_be_compiled_with_O2() { stuff(); } #pragma GCC optimize("Ofast") void this_will_be_compiled_with_Ofast() { stuff(); }
70,094,288
70,096,468
Why Queue Give me 0 in last display function
#include <iostream> #define size 100 using namespace std; class Q { private: int item[size]; int front, rear; public: Q() { front = -1; rear = -1; } bool is_empty(); bool is_full(); void enque(int num); void deque(); void display(); }; bool Q::is_full() { ret...
We should check whether the Q contains elements or not and then start printing. void Queue::display() { if (is_empty()) { cout << "Q is Empty You Can't Deque From it" << endl; return; } cout << "Elements in queue : "; for (int i = front; i <= rear; i++) { cout << items[i]...
70,095,010
70,100,359
Detect if C++ class has a template method
I know how to detect presence of a variable or a regular method in a C++ class. But how to do it, when the method is a template? Consider the code: struct SomeClass { template<typename Sender, typename T> auto& send(T& object) const { Sender::send(object); return object; }; }; How to wr...
Ok, I acutally managed to solve it, if anyone is interested: I needed to create a dummy class class DummySender { public: template<typename T> static void send(const T&) {} }; And then I can check for the presence of the send method, by defining type traits: template<typename T, typename = ...
70,095,337
71,733,584
How can I get specific std::map value with indexing while using gdb for debuggin c++ code?
I use Ubuntu 20.04-LTS with WSL(Windows Subsystem Linux), GDB version is 9.2, and I builded my c++ code with c++11. I tried to access std::map's value with index in GDB, however GDB showed error message "Invalid cast". My code is same for below #include <iostream> #include <map> #include <string> using std::cout; usi...
You first write the below code in the ".gdbinit" file. define newstr set ($arg0)=(std::string*)malloc(sizeof(std::string)) call ($arg0)->basic_string() # 'assign' returns *this; casting return to void avoids printing of the struct. call (void)( ($arg0)->assign($arg1) ) end define delstr call ($arg0)->~basic_string(0)...
70,095,549
70,095,784
How do I stop segmentation error with array in C++?
I am creating a simple command line, tic-tac-toe game in C++. Whenever I reun the code I get no compiler errors but then VSCode tells me once I have given input that there is a Segmentation Fault. I will paste my code below: #include <iostream> #include <cmath> using namespace std; void print_board(string board[3][3])...
void print_board(string board[3][3]) why are you using a string[3][3] ? you basically just need a 3x3 character array board[(int)floor(position / 3)][(position % 3) - 1] = "X"; make sure you keep yourself in range 0..2, -1 is outside and will cause undefined behavior return board[3][3]; No that is wrong in more wa...
70,095,987
70,102,829
boost program_options: Read required parameter from config file
I want to use boost_program_options as follows: get name of an optional config file as a program option read mandatory options either from command line or the config file The problem is: The variable containing the config file name is not populated until po::notify() is called, and that function also throws exception...
I'd simply not use the notifying value-semantic to put the value in config_file. Instead, use it directly from the map: auto config_file = variable_map.at("config").as<std::string>(); Now you can do the notify at the end, as intended: Live On Coliru #include <boost/program_options.hpp> #include <fstream> #include <iom...
70,097,152
70,097,267
Is there an easier way of finding cpp executable in visual studio?
I've started programming in c++ and I recently switched from a text editor to visual studio's ide, and I found out how to compile a single hello world. But it takes a bit to actually find the executable which is in a mess of folders full of a bunch of different files. Is there just an easier way to find the file? Or ch...
In visual Studio (not code), go to the Project menu, then to <Project_name> properties. In the popup window go to Configuration properties/General, you will find the output directory. Plan B: when building your solution, the full path of the exe is displayed in the console output.
70,097,673
70,097,800
How to continue to next item in iterator using recursive_directory_iterator
I am currently iterating through a filesystem. I want to capture any errors that occur and then just continue iterating. The current behavior if an error occurs it will set the current iterator to the end and then the for loop exits. I would like for this to skip that path and continue. try { for (const aut...
You can't recover from errors in recursive_directory_iterator. If the recursive_directory_iterator reports an error or is advanced past the last directory entry of the top-level directory, it becomes equal to the default-constructed iterator, also known as the end iterator. From cppreference
70,098,010
70,100,138
Can I move construct (or assign) to a map a different type values using conversion?
I have a simple container for data (simplified more for the purpose of this question) that I use as a value in a map. I want to know if there is some way I can move construct a map with this container as a value type from a map using the underlying data type. Here is such a class: class D { public: D() :m_value(0.0...
Something along these lines, perhaps (requires C++17): std::map<Key, long> new_m; while (!m.empty()) { auto node = m.extract(m.begin()); new_m.emplace(std::move(node.key()), std::move(node.mapped())); } Demo. I made a user-defined class the key of the map rather than std::string, so that I could instrument it ...
70,098,210
70,098,738
Can I throw exceptions through functions compiled w/o exceptions
Let we have two libraries: libA.a and libB.a. They are organised s.t. libA.a calls libB.a functions and provides a callback to itself. In other words, the following call stack is possible: #0 liba_callback() #1 libb_function() #2 liba_function() libA.a is compiled with -fexceptions and libB.a is compiled with -fno-exc...
As @Pete Becker noted, exceptions are part of the language, so the compiler is responsible for documenting such C++ dialect. The GCC documentation says: Before detailing the library support for -fno-exceptions, first a passing note on the things lost when this flag is used: it will break exceptions trying to pass thro...
70,098,331
70,098,459
Conventions for using std::feclearexcept
Is there any convention for using std::feclearexcept? In the examples you usually see, this is called before an operation is executed that might trigger a floating point exception. This seems a safe thing to do. But should you also call std::feclearexcept after you have detected and handled an error, so that the error ...
Simlar in reasoning to (re-)setting errno only before you do a specific operation and intend to check errno afterwards. There might be conditions under which errno, or the floating point exception flags, are set that you are not aware of. You don't know where exactly they happened or what they mean semantically. You ar...
70,098,533
70,098,864
C++ How to read input N and then read a series of numbers N long?
I'm working on an assignment where I need to create a program that reads a non-empty sequence of integer numbers, and tells how many of them are equal to the last one. It should read the amount of integers the sequence has and then read the sequence itself and return the amount of times the last number repeats itself e...
Just don't judge harshly, please. I suggest another way to solve this problem. #include <iostream> #include <vector> using namespace std; int special, count; void dfs(int current, int previous, vector<int>& visited, vector<int>& input) { if(visited[current]==1) { return; } visited[current]=1; ...
70,098,843
70,098,953
Adding a member to std::vector<std::vector<int>> class in C++
I have to modify a code so that I can add a member to 2D vectors. The code started with a typedef vector<vector<int>> Matrix which I replaced with a Matrix class. I tried to inherit from vector<vector<int>> using : class Matrix: public vector<vector<int>> { public: int myMember; }; This way I practically don't hav...
Constructors are not inherited by default, but can use them in your derived class for that you have to do something like this: #include <vector> #include <iostream> class Matrix : public std::vector<std::vector<int>>{ public: using vector::vector; int myMember; }; int main(){ Matrix data(1); ...
70,099,368
70,109,565
std::chrono gdb pretty printer
I am mildly surprised that gdb doesn't come with pretty printers out of the box for the std::chrono duration types since they are part of the standard library. With gdb 10.2 (through most recent Clion IDE although that should not be Clion specific - it's plain gdb under the hood) I see the unhelpful : system_clock::m_t...
I ended up adding a .gdbinit file in my home directory with a few lines of python which achieves the single-line value display I was after. python # way to tell .gdbinit we enter a python section import gdb class ChronoPrinter: def __init__(self, val): self.val = val def to_string(self): integ...
70,099,903
70,100,358
c++ how to sum all rows from one specific column from a csv delimited
I have a question in C++ For example, i have a csv file delimited by ; with this data name;age;country maria;19;portugal joao;20;espanha carlos;18;portugal antonio;30;alemanha How can i get the sum of column 2 (age) -> =87 How can i get the country that shows more times (portugal) With this code i get a complete lin...
You should use struct to hold information together in this case, as shown below. You can use the below given program as a reference(starting point) for your future purposes/programs. #include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> #include <map> #include <functional> #inclu...
70,100,820
70,102,036
For print a pattern by using loop
*this is my output 1234 234 34 4 code //variable declaration #include<iostream> using namespace std; int main(){ int i,j,space,star,n; cin>>n; i=1; //for printing spaces while(i<=n){ space=i-1; while(space){ cout<<" "; space--; } // for counting variables j=1; star=n...
Well, when printing spaces, you do this: cout<<" "; You can do this: cout<<" "; That is, print two spaces instead of one. That's half your answer. Later you do this: cout<<num; You can do this: cout << num << " "; That is -- print the digit plus a space. Done. However, if you do that, then you get ...
70,100,958
70,101,000
Skip 2 Index In the body of For Loop VS While Loop ( Python VS C++)
In the first code below (Using for loop) When I want to skip 2 index by increasing the index within the body of for loop, it ignores i = i+2 and updates the index only with for i in range (len(c)) phrase, while in the c++ we could do this in th e body of for loop by for (int i = 0 ; i <sizeof(c) ;i++){i += 2;}. Is ther...
You can use continue to skip. You'll just need a condition that will be True. def jumpingOnClouds(c): skipCondition = False count_jumps = 0 for i in range (len(c)): if skipCondition: skipCondition = False continue if (i+2 <len(c) and c[i] == 0 and c[i+2] ...
70,101,355
70,102,095
How to get all dictionary words from a list of letters?
I have an input string, like "fairy", and I need to get the English words that can be formed from it. Here's an example: 5: Fairy 4: Fray, Airy, Fair, Fiar 3: Fay, fry, arf, ary, far, etc. I have an std::unordered_set<std::string> of dictionary words so I can easily iterate over it. I've created permutations before...
You can keep an auxiliary data structure and add a special symbol to mark an end-of-line: #include <algorithm> #include <string> #include <set> #include <list> #include <iostream> int main() { std::list<int> l = {-1, 0 ,1, 2, 3, 4}; std::string s = "fairy"; std::set<std::string> words; do { st...
70,101,356
70,101,410
How to use a char buffer array as the case in switch-case C++?
I have a snip of the following code which should read the first 4 objects in a .wav file in order to eventually parse the header of the file. I know I'm doing something wrong here because the buffer always passes "RIFF" without printing out Riff is found How should I use the Switch-case in order to find the correct ar...
In contrast to languages such as C#, you cannot use strings in a switch expression. You will have to use if...else statements in conjunction with std::memcmp instead: if ( std::memcmp( Buffer, "RIFF", 4 ) == 0 ) std::cout << "Riff is found.\n"; else if ( std::memcmp( Buffer, "crif", 4 ) == 0 ) std::cout <<...
70,101,890
70,102,033
Meaning of "ill-formed declaration" in L(n)
A code snippet from cppreference.com is like this: struct M { }; struct L { L(M&); }; M n; void f() { M(m); // declaration, equivalent to M m; L(n); // ill-formed declaration L(l)(m); // still a declaration } L(n); is commented with "ill-formed declaration". But nearly all compilers issue message like th...
I think that the example demonstrates that declarator may be enclosed in parentheses. So this declaration M(m); is equivalent to M m; that is there is declared an object m of the type M. However this record L(n); can be considered as an expression statement with calling the constructor L( M & ) with the argument n o...
70,102,205
70,103,381
Why wrapping call to function returning by value in hana::always circumvent requirements of ranges::views::join? Or maybe it doesn't?
This function, fed with any int, returns a std::vector<int> by value: auto make = [](int){ return std::vector<int>{1,2,3}; }; Therefore, such a thing can't work std::vector<int> v{1,2,3}; auto z = v | std::ranges::views::transform(make) | std::ranges::views::join; // fails to compile because, I underst...
There are two separate issues. join_view's restriction on joining ranges of prvalue ranges is a defect in C++20 that has been corrected by P2328R1. transform(make) | join should Just Work on a standard library implementing the defect resolution (such as libstdc++ trunk). hana::always returns different things dependin...
70,102,937
70,103,124
How should an input string be read into a shunting yard algorithm calculator?
I have implemented the basic structure of the shunting yard algorithm, but I'm not sure how to read in values that are either multidigit or functions. Here's what I have currently for reading in values: string input; getline(cin, input); input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end()); //pass...
In order to run shunting-yard, you're going to want to tokenize your string first. That is, turn 12+4into {'12','+','4'}. Then you can just use the tokens to run shunting yard. A naive infix lexing algorithm might like this: lex(string) { buffer = "" output = {} for character in string { if characte...
70,103,116
70,103,161
Get access to a variable in a class without copying it
I would like to get access to fields from a class without copying it. I have a class that stores two variables (simplified version here). In the get_cutting_types method I check where the user inputs true or false and pass the object back by reference. But here I have to use =, meaning the data is copied. Is there a di...
There's a lot to unpack here, but: I don't think you're going to be able to avoid using an "=" sign somwhere along the way. And I don't see any reason that's a problem. If all you want is to return a boolean value: then maybe just add a new public method to your class, e.g. public: bool isMale() { return <<some te...
70,103,300
70,103,325
Accessing non-const data members from constexpr member function
Both GCC and MSVC seem to allow defining constexpr accessor functions for non-const data members: #include <random> #include <iostream> class Foo { int val; public: Foo(int v) : val(v) {} constexpr int get_val() { return val; } // OK }; int main() { std::random_device rd; Foo foo((int)rd()); ...
Of course this is allowed! constexpr don't mean const. You can even mutate values in a constexpr function: class Foo { int val; public: constexpr Foo(int v) : val(v) {} // OK constexpr int get_val() { return val; } // OK constexpr void set_val(int v) { val = v; } // OK }; With this you can write cons...
70,103,393
70,103,474
Is there a portable way in standard C++ to retrieve hostname?
I'm working on a C++ program that needs to use the hostname of the computer it is running on. My current method of retrieving this is by mangling a C API like this: char *host = new char[1024]; gethostname(host,1024); auto hostname = std::string(host); delete host; Is there a portable modern C++ method for doing this,...
No, there is no standard C++ support for this. You'll either have to make your own function, or get a library that has this functionality.
70,104,117
70,123,774
How to set expectation on a mocked method which is called inside another mocked method C++
I am a beginner with google testing framework and have looked up for the solution to this question on SO, but could not find any solutions with respect to C++. Anyway here is what i am trying to do. I have a state machine(service) which is called inside a client code. //IStateMachine.h class IStateMachine {...
You don't need to set this expectation. I'd go even further: you should not even depend on the implementation of Run in IStateMachine: you should only care about what input it is provided with (parameters, checked with matchers) and what output it can return (so basically only the contract between these two classes) an...
70,104,318
70,104,345
c++ 2 overloads have similar conversions depending on whether the operator is a member function or a global one
Consider a simple vector class realization: #include <algorithm> class Vector { public: Vector(int _elementsCount) : elementsCount(_elementsCount) , elements(new float[_elementsCount]) {} ~Vector() { delete[] elements; } Vector(const Vector& rhs) { elementsCount = rh...
You need to make your constructor explicit: explicit Vector(int _elementsCount) { ... } The reason for the ambiguity is that the compiler can't decide whether it should implicitly convert a int value to a Vector and invoke Vector::operator*, or implicitly convert a int value to a float and use operator*(const Vector&,...
70,104,717
70,104,722
Why is move-constructor not called?
I have the following piece of code: #include <iostream> struct T { int a; T() = default; T(T& other) { std::cout << "copy &\n"; } T(T&& other) { std::cout << "move &&\n"; } }; void foo(T&& x) { T y(x); // why is copy ctor called?????? } int main() { T x; foo(std...
x is an lvalue itself, even its type is rvalue-reference. Value category and type are two independent properties. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression; You need to use std::move to convert it to rvalue, just same as using std::move on x in main...
70,104,749
70,104,785
Can't kill all child processes using SIGTERM
My program has the following parent child layout: int main() { std::vector<pid_t> kids; pid_t forkid = fork(); if (forkid == 0) { //child process pid_t fork2 = fork() if (fork2 == 0) { // child process }else { //parent kids.push_back(fork2); } }else { // code here kids.push_...
std::vector<pid_t> kids; pid_t forkid = fork(); fork() creates a complete duplicate image of the parent process as its child process. Emphasis on: duplicate. This means that, for example, the child process has its very own kids vector, that has nothing to do, whatsoever, with the parent process's original kids vector....
70,104,875
70,130,364
How did a Renderer pass to the rest of the classes?
I have a Game class that through its constructor initializes the window and the SDL renderer. I understand from what I read so far (not much) that there should only be one renderer for each window. Then I have a Player class where through the constructor I want to load a texture with an image, for which I need the rend...
The only thing I can think of is not to create the texture through the constructor, but through a function, but it wouldn't be the right thing to do, right? that's what the constructor is for Right. However, SDL is a C library so it doesn't use C++ RAII, which is responsible for construction/destruction. First, we ca...
70,104,984
70,105,036
C++ Keeping track of start iterator while adding items
I am trying to do a double loop across a std::vector to explore all combinations of items in the vector. If the result is good, I add it to the vector for another pass. This is being used for an association rule problem but I made a smaller demonstration for this question. It seems as though when I push_back it will so...
nums.push_back(sum); push_back invalidates all existing iterators to the vector if push_back ends up reallocating the vector. That's just how the vector works. Initially some additional space gets reserved for the vector's growth. Vector's internal buffer that holds its contents has some extra room to spare, but when ...
70,105,002
70,105,136
Using a concept in another concept's 'requires' clause
I have a fairly simple example that I'm struggling with. I'd like to use an already-defined concept in another concept's requires clause - something like this, except actually working: template<typename T> concept Any = true; template<typename T> concept UsesAnyA = requires(T t, Any auto a) { t(a); }; I've also tri...
Probably need to do something like this: template <typename T> concept Any = true; template <typename T, typename A> concept UsesAny = Any<A> and requires (T t, A a) { t(a); }; A concept needs each of the complete types involved in order to test its constraint, but at the point you evaluate it, you should already h...
70,105,697
70,105,771
Why does automatic type deduction not work for constexpr member referencing?
In the example code, compiled in C++17: template <typename T = int> struct A { static constexpr double b = 0.5; }; int main() { A a; // compiles double c = A<>::b; // compiles double d = A::b; // fails to compile // ... return 0; } Live example A::b fails to compile because: main.cpp:13:16: e...
Each instantiated class instance has own A<T>::b member. #include <iostream> template <typename T = int> struct A { static constexpr double b = 0.5; }; int main() { std::cout << &A<int>::b << "\n"; std::cout << &A<char>::b << "\n"; return 0; } Compiled with clang++13 with the option -std=c++17. Out...
70,105,768
70,105,787
what is the difference between while and do-while loop in c?
I am new to programming language. Anyone please help me with this. It helps to improve my skills. what is the difference between while and do-while loop in c Thank You,
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. do-while loop: do while loop is similar to while loop with the only difference that it checks for the condition after executin...
70,105,905
71,513,590
How do I remove a special constructor from overload resolution?
I'm creating an implementation of C++17's std::optional<class T> in C++14. The specification states that the move constructor should be excluded from overload resolution if T is not move-constructible, and made trivial if T is trivially move-constructible. I'm stuck on getting the former. Here's a code sample of what I...
A move constructor has one T&& argument, and possibly additional arguments provided those have default values. That means you can add std::enable_if_t<Condition, int> = 0 as an additional argument to your move constructor. The compiler won't create a one-argument optional::optional(T&&) move constructor when you have t...
70,105,969
70,105,992
C++ Loop through first K elements of unordered_map
I have an unordered_map that stores counts of integers. I want to loop through the map, but instead of fetching all the entries, I only wish to get the first K.It is guaranteed that map has more than K entries. I'm running into issues when I do the following: unordered_map<int, int> u_map; // Logic to populate the ...
I only wish to get the first K Note from std::unordered_map documentation an unordered_map object makes no guarantees on which specific element is considered its first element. This essentially means that there is no guarantee that you will iterate over the elements in the inserted order. For iterating over the ele...
70,106,194
70,135,562
Combine multiple animations for PathView delegate
Qt 6.2.0, Ubuntu 20.04. Here the code of my PathView: PathView { id: view property int item_gap: 60 anchors.fill: parent pathItemCount: 3 preferredHighlightBegin: 0.5 preferredHighlightEnd: 0.5 highlightRangeMode: PathView.StrictlyEnforceRange highlightMoveDuration: 1000 snapMode: P...
The problem is that view.delegate is a Component, which is like a class definition, not a class instance. Your PathView may create many instances of that delegate. So you can't use view.delegate as a target for an animation because it needs to know which instance you're referring to. Since it's the current item you're ...
70,106,777
70,107,046
C++ compilation vs translation unit
I am preparing a short presentation on templates for work and am using isocpp.org as a starting point for the content. However, I have come across an interesting paragraph: A note to the experts: I have obviously made several simplifications above. This was intentional so please don’t complain too loudly. If you know ...
First, translation and compilation units are the same thing. The word/phrase Translation unit is used more often than compilation unit. Which basically means your source file including all of its header files. Second we(and by we i mean good C++ books) use the term function template or class template rather than using ...
70,107,117
70,143,198
I need assistance with pinpointing a std run time error
So the question above pretty much explains my problem, I have a program that prints the code size of my fragment shader and vertex shader, it is part of my Game engine project I have been working on for the past few days as a learning experience to get more knowledge of low-level c++ programming, but the problem is whe...
In researching, I found that adding the absolute path to my shader file actually outputs the size as expected, the program didn't like the short path I was inputting for some reason
70,107,183
70,107,238
Virtual list (Problems with parameter/pointer)
I am trying to convert my CListCtrl into a virtual list, but i dont know which parameter i have to use // --- Virtual List --- void CSpielebibliothekGUIDlg::OnGetdispinfoList(NMHDR* pNMHDR, LRESULT* pResult) // --- nullptr muss weg --- { LPNMITEMACTIVATE pNMIA = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); ...
You don't need to call message handlers, they will be called by system after you: Set proper window styles (LVS_OWNERDATA) Set item count Add your OnGetdispinfoList to the message map
70,107,218
70,107,290
QWebEngineView will not load a local file, but will load perfectly a remote webpage
An MWE demoing the problem is this: #include <QMainWindow> #include <QApplication> #include <QWidget> #include <QWebEngineView> #include <QGridLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); QMainWindow w; auto w1 = new QWidget(); w1->setLayout(new GridLayout()); auto view ...
If you want to create a QUrl using a file path then use QUrl::fromLocalFile(): view->load(QUrl::fromLocalFile("C:\\Users\\FruitfulApproach\\Desktop\\AbstractSpacecraft\\MathEnglishApp\\KaTeX_template.html"));
70,107,366
70,107,425
atcoder educational dp problem a runtime error problem
I am getting a runtime error in some test cases when I try to submit my code. Problem Link: https://atcoder.jp/contests/dp/tasks/dp_a My code: #include<bits/stdc++.h> using namespace std; #define int long long int minCost(int n, vector<int> h, vector<int> dp) { if (dp[n] != -1) { return dp[n]; } ...
I'm not sure this is the only problem, in minCost() but you're passing dp by value, not reference. That means the compiler will make a copy of dp, not the actual dp. Change your code to: int minCost(int n, vector<int> h, vector<int>& dp)
70,107,582
70,107,759
cmake add_custom_command pre_build
I am writing cmake example for the first time. Here is a part of CMakeFiles.txt: add_custom_command( OUTPUT ${CODEGEN_SRC} PRE_BUILD COMMAND ${CODEGEN_CMD} ${SERVICE_XML} --generate-cpp- code=/home/hello/include/gen/testGenCode COMMENT "Generate gdbus code" ) add_custom_target(${CODEGEN_TARGET} DEPENDS...
add_custom_command will run the command during build phase (when running make). Since it generate the files required by the next target, it will fail if the file have never been generated. You can configure the file when running cmake too, using execute_process() in addition of add_custom_command(). You can also use co...
70,108,420
70,108,699
how to poll a com port in c++
This is all the code for polling the com port, according to the modbus-RTU protocol, the device does not respond. I can't figure out how to get the device to respond to me. The device address and the function code are enough to answer. These are the first two characters (0x15, 0x03 ...) I do not know what I am doing wr...
Did you check your request string with a terminal program f.e. hterm? As far as I know only two tx characters will not make an answer from the device, there is also a crc at end of a frame https://www.der-hammer.info/pages/terminal.html
70,108,453
70,109,438
How to structure "future inside future"
I am building a system where a top layer communicates with a driver layer, who in turn communicate with a I2C layer. I have put my I2C driver behind a message queue, in order to make it thread safe and serialize access to the I2C bus. In order to return the reply to the driver, the I2C layer returns a std::future with ...
You are looking for an operation called then, which as commenters note is sadly missing even in C++20. However, it's not hard to write a then yourself. template<typename Fun, typename... Ins> std::invoke_result_t<Fun, Ins...> invoke_future(Fun fun, std::future<Ins>... futs) { return fun(futs.get()...); } template<...
70,108,588
70,108,747
What is "a>b" as a parameter which requires a function pointer or lambda expression?
Below is the very simple use of boost::log::set_filter, #include <boost/log/trivial.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> namespace logging = boost::log; void test() { logging::add_file_log("sample.log")->set...
The result of a user-defined >= can be any type, it does not have to be bool. In this case, the library author defined a >= that returns a function object. As a sketch, it's something like this struct severity_t {} severity; enum severity_level { info, ... }; struct greater_equal_filter { severity_level l...
70,108,635
70,108,733
C++: Variable that is passed by const referance changes value
for an assignment I was provided with a framework of different classes that use parameters passed by const reference. When I initialize one instance of this same class and then a second one later, the values of the members that were passed by const reference within the first one change. I am not allowed to change a_cam...
Your code is rather complicated. Though much less is needed to see that the assumption: "A const reference does not change its value." is based on a misunderstanding. #include <iostream> struct foo { const int& x; }; int main() { int a = 42; foo f{a}; a = 0; std::cout << f.x; } The output of ...
70,108,639
70,109,089
output map object where the value can be any data type
Trying to output a map object where the value can be any data type. Tried the following: #include <iostream> #include <unordered_map> #include <any> std::unordered_map<std::string, std::any> example = { {"first", 'A'}, {"second", 2}, {"third", 'C'} }; std::ostream &operator<<(std::ostream &os, ...
There isn't a good way of printing the contents of an arbitrary std::unordered_map<std::string, std::any>. It might have contents that aren't printable, and you've discarded the information about what type the contents actually are. You need to keep that information somewhere. #include <string> #include <iostream> #inc...
70,108,692
70,109,103
Calling function that was declared virtual in interface (and implemented in derived class) inside base abstract class
I have the following inheritance model: interface abstract class concrete derived class _________________________________________________________ IPriorityQueue -> APriorityQueue -> UnsortedPriorityQueue My member function was declared purely virtual in the interface. In the abstract class, I want to use siz...
Just replace bool empty(void) const { return (!size()); } with bool empty(void) const { return (!this->size()); }//note i have added this-> and that will solve your problem. Here's the rule the compiler does not look in dependent base classes when looking up nondependent names . Here's a good article for read...
70,108,763
70,112,613
Estimate the camera pose in the reference system using one marker with ARUCO
I am currently working on a camera pose estimation project using only one marker with ARUCO. I used Aruco's Marker Detector to detect markers and get the marker's Rvec and Tvec. I understand these two vectors represent the transform from the marker to the camera, which is the marker's pose w.r.t camera. I form a 4 by 4...
The one equation you gave looks right, so the issue is probably somewhere that you didn't show/describe. A fix in your notation will help clarify. Write the pose/source frame on the right (input), the reference/destination frame on the left (output). Then your matrices "match up" like dominos. rvec and tvec yield a mat...
70,108,775
70,108,776
gdb exits immediately `Process finished with exit code 1` or lldb `'A packet returned error 8'` on docker
This took me full days to find, so I am posting this for future reference. I am developing C++ on a docker image. I am using clion. My code is compiled in debug mode, and runs fine in run mode, but when trying to debug, the process exits immediately with the very informative Process finished with exit code 1 When swit...
Eventually, I found this comment which led me to this blog post, in which I learned C++ debugging is disallowed on docker by default. The arguments --cap-add=SYS_PTRACE and --security-opt seccomp=unconfined are required for C++ memory profiling and debugging in Docker. I added --cap-add=SYS_PTRACE --security-opt secc...
70,109,239
70,109,562
RSA Algorithm is not working for certain numbers
I have a homework that includes handling user login and register. For that the teacher told us to use the RSA Algorithm to encrypt the passwords of the users. My problem is with the RSA. I am trying to write it to encrypt only 1 integer and after that I will write a new method that encrypts a string. So at this moment,...
Even with small numbers like that it's easy to exceed the limits of int with exponentiation. If you make your own pow, it should apply the modulo after every step: // computes x**y % n int custom_pow(int x, int y, int n) { int res = 1; for(;y;y--) { res = (res*x) % n; } return res; }
70,109,363
70,109,462
Why do I need Boost.SmartPtr for the C++ compiler that supports C++11 and later?
The boost C++ library is a famous sandbox for the language and Standard Library features that absorbed with each new version of the Standard C++. However boost components that eventually became a part of the Standard are still present in boost. One of the classic examples of said above are smart pointers. So why do I n...
Why do I need Boost.SmartPtr for the C++ compiler that supports C++11 and later? Because: You may need your program to compile with another compiler that doesn't support C++11 or later. You may not want to bother implementing make_unique yourself. Sure it's easy, but why do it when you can use an existing implementa...
70,109,372
70,109,482
Global namespace variables without translation unit issues?
I'm trying to abstract away some GLFW input code by using a global variable state to keep track of key presses. I thought using namespaces would be nice, so I thought doing something like: namespace InputState { namespace KeyPressed { static bool left = false; static bool right = false; ...
Is there some way I can get this working where I truly have a global variable within a namespace or is this just not possible/not intended behavior for namespaces? If you want to use these variables in other source file then you can do so using extern as follows: myheader.h #ifndef MYHEADER_H #define MYHEADER_H names...
70,109,628
70,109,841
How should I define my destructor for the Node class in C++?
I am supposed to implement a class of Nodes for the tree that consists of static nodes (for educational purposes). The classes headers look like this: class CNodeStatic { private: int i_val; CNodeStatic *pc_parent_node; vector<CNodeStatic> v_children; public: CNodeStatic() {i_val =0; pc_parent_node = NU...
I know that we need to define destructors when there is a dynamically allocated memory or pointer in class Right. If a class manages a resource, it must manage the resource and cleaning up is part of that. In this case it's pc_parent_node that points to the parent of the node. Pointers != managing a resource. In pa...
70,109,726
70,109,941
Segmentation fault caused by repeating pop_back() and push_back()
When I run the following code in Clion(an IDE) with c++11. I ran into a segmentation fault. But if I delete the if statement, add else before pop_back, remove push_back, or remove pop_back(do them separately). There would be no error. So why there would be a segmentation fault and why doing any of the above would elimi...
You are popping from the vector when it is empty. Using pop_back() from an empty vector results in undefined behaviour which means: your program could crash your program could print some nonesens your program could continue normally your program could continue normally, but have some other strange seemingly unrelated ...
70,109,997
70,110,333
How to format an 2d array of different type sized strings (e.g. x, xxx ,xx ,xxx) to look more square like when printed
This is my code Does any one know how I can format it so it looks more like a square rather due to the different character sizes in each element. 1 int main() { string a[4][4]= {{"\xC9","\xCD","\xCD","\xBB"}, {"\xBA","p1","p2","\xBA"}, {"\xBA","100","p3","\xBA"}, ...
There's not really a shortcut here: you'll have to all bring them to the same length. Which length to choose: hard. You might first have to make all rows, then find the longest one, the format all rows to have the same length, then make the top and bottom bar. You can do that with iostreams / stringstream in standard C...
70,110,055
70,110,141
C++: Variables change values after initialization of different class
I have the following problem. PerspectiveCamera pcam2(Point(0, 0, 0), Vector(0.5f, 0.5f, 0.3f), Vector(0, 0, 1), pi * 0.9f, pi * 0.9f); Renderer r12(&pcam2,0); In the above code, pcam2 is initialized and then after that, &pcam2 is passed on to r12. pcam2 has members const Point& center, const Vector& forward, const Ve...
Point(0, 0, 0) is a temporary object which lives only until the nearest ;. If you store a reference to it inside pcam2, this reference becomes dangling right after the line with pcam2 initialization is complete. Any access to the dangling reference afterwards is undefined behavior. You typically don't need to store any...
70,110,371
70,111,033
Why is object member value changing between 2 getter calls
I am getting unexpected value in second getter call which looks wrong to me, any specific reason for this happening? #include<iostream> using namespace std; class Test { public: int &t; Test (int x):t(x) { } int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout << t1.getT() <...
The problem here is that your code results in undefined behavior. The constructor of Test does not take a reference to an int but a copy, and due to int x only being a temporary copy which is not guaranteed to live until your second function call you will end up with undefined behavior. You would have to change your co...
70,111,021
70,111,067
Strange behaviour of if in C++
At my work I tried to use this construction: if (repl && (repl = replaced.count(*l))) { // repl isn't used here ... } and in my mind it should work the same way as bool newRepl = replaced.count(*l); if (repl && newRepl) { // repl isn't used here ... } repl = newRepl; because expressions in && evalua...
&& is short-circuiting. Your original code is equivalent to this: if (repl) { repl = replaced.count(*l)) if (repl) { // repl isn't used here ... } }
70,111,290
70,111,691
Correct way to numerically calculate a sum
I am trying to numerically calculate a sum: I fully understand that it is an easy sum, however, my mind keeps tingling me for a few days consequently, if I am doing it correctly. Here is an outline of a C++ code that I have written to calculate it: struct vecs{ float x; float y; float z; float a; }; s...
Yes, your code is correct. If you want to make it "more obviously" correct, I would move it closer to the mathematical definitions by defining some helper functions. Concretely: const vecs& R(int upper, int lower) { return VEC[upper].VAL[lower]; } const float a(int upper, int lower) { return VEC[upper].VAL[lower].a; } ...
70,111,914
70,114,545
How to use Boost::log not to rewrite the log file?
Below is the simple example of using boost::log to write log, #include <boost/log/trivial.hpp> namespace logging = boost::log; logging::add_file_log("sample.log")->set_filter( logging::trivial::severity >= logging::trivial::info ); BOOST_LOG_TRIVIAL(info) << "log content"; Every time run logging::add_file_log("...
You can pass an openmode to the setup function: Live On Coliru #include <boost/log/trivial.hpp> #include <boost/log/utility/setup.hpp> #include <random> namespace logging = boost::log; namespace logkw = logging::keywords; int main() { logging::add_file_log("sample.log", logkw::open_mode = std::ios::app) -...
70,112,122
70,112,213
What is a better data structure to replace a map o sets?
recently I wrote a post in which I asked for help in a problem I had in a C++ code. However, some people focused on a definition I put in one of my codes, which is: std::map <std::string, std::pair<std::string, std::string>> map_example; saying that this is considered a bad definition and that I should replace it. I w...
A common concern against std::pair is poor naming of its members. Your code will be sprinkled with first and second when you probably could use better names. Compare struct customer_name_and_company { std::string customer_name; std::string company; }; std::map<std::string, customer_name_and_company> m; for (...
70,112,202
70,112,287
multithread segment fault destructors
i have a segment fault when it calls the function unit_thread_data,Actually it is caused by ~Data(). thread1 is all right, but thread2 cause the segment fault, the whole code is as fallows:(forgive the poor code style), error info is double free or corruption. Other info: gcc5.4.0, centos7. any help? thank you very muc...
delete[] pthread_data[i].d->A_; This deletes the A_ member of your Data class, an int *. Immediately afterwards, this happens: delete pthread_data[i].d; And this deletes the Data itself. Data's destructor then does the following: if(A_) { delete A_; } This then proceeds to attempt delete the same poi...
70,112,492
70,112,672
Same class as a member inside a class in C++?
Sorry I ill formed the question earlier. The piece of code is something like: class Bar { public: // some stuff private: struct Foo { std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo; // some other basic variables here }; Foo foo; }; ...
There are more misunderstandings about nested class definitions than there are actual benefits. In your code it really does not matter much and we can change it to: struct Foo { std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo; // some other basic variables here }; class Bar { Foo foo; }; ...
70,113,095
70,214,141
How to cross-compile Qt6 on Linux for Windows?
I'm trying to cross-compile Qt 6.2.1. Target - Windows, my machine OS - Linux (Mint 20.2) (both 64bit). Unfortunately I can't compile it on Windows, so I have to do this cross-compilation. My configure cmd: ./../qt-everywhere-src-6.2.1/configure -prefix $PWD/. -platform linux-gcc-64 -xplatform win32-g++ -device-option ...
For those coming here from google with same problem. In Qt6 you need to specify Cmake toolchain for cross-compilation (I get something similar to toolchain shared here), as 'alone' device-option CROSS_COMPILE (as in cmd from my question) is depreciated/outdated (or smth like that). In my case I needed to use CMake tool...
70,113,292
70,113,655
Why doesn't std::string have a constructor that directly takes std::string_view?
To allow std::string construction from std::string_viewthere is a template constructor template<class T> explicit basic_string(const T& t, const Allocator& alloc = Allocator()); which is enabled only if const T& is convertible to std::basic_string_view<CharT, Traits> (link). In the meantime there is a special deductio...
The ambiguity is that std::string and std::string_view are both constructible from const char *. That makes things like std::string{}.assign("ABCDE", 0, 1) ambiguous if the first parameter can be either a string or a string_view. There are several defect reports trying to sort this out, starting here. https://cplusplu...
70,113,466
70,113,582
How do I calculate the sum of all the array numbers after the first negative?
Can you help me with this problem? All I could do was count all the negative numbers. Here is my code: using namespace std; int main() { const int SIZE = 10; int arr[SIZE]{}; int number=0; srand(time(NULL)); cout << "Your array is: " << endl; for (int i=0; i<SIZE; i++) { int newVal...
One way is to have a flag that is zero to start with that is switched on after the first negative: int flag = 0; int sum = 0; for (std::size_t i = 0; i < SIZE; ++i){ sum += flag * arr[i]; flag |= arr[i] < 0; } This approach carries the advantage that you don't need an array at all: substituting the next number...
70,113,566
70,113,657
runtime error: left shift of negative value -1
In fact I am trying this question: 5.4 in 《Cracking the coding interview:189 programming questions and solutions,fifth edition》 the question is: Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. There is an exact same ques...
why the func can passed in msvc, clang, and gcc ,but just cannot pass the UndefinedBehaviorSanitizer? Because the compiler didn't know at compile time, what value the operand would be at runtime. If compilers were able to detect all UB at compile time, then UB sanitisers wouldn't exist since they would be unnecessary...
70,113,831
70,114,739
How to put projects in one folder in a Visual Studio solution
I did some problem-solving in C++, and the current file structure looks like this. solution_folder/ ├── question_1/ │ ├── Main.cpp │ ├── question_1.vcxproj │ └── question_1.vcxproj.filters ├── question_2/... ├── (more project folders) └── solution.sln I want to put all projects in one folder and still be able to...
As @drescherjm and @heapunderrun commented, Put all project folders in one folder in File Explorer, Remove all projects from the solution in Solution Explorer, Right-click on the solution and Add → Existing Project all projects. Update: Shortcuts Remove: Delete Add existing project: Alt F D E
70,114,043
70,128,838
Add ros cmake to an already existing cmake
I have a really big code with this cmake that works: cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project(MYPROJECT) set (CMAKE_CXX_STANDARD 11) find_package(PCL 1.7 REQUIRED) if(DEFINED PCL_LIBRARIES) list(REMOVE_ITEM PCL_LIBRARIES "vtkproj4") endif() FIND_PACKAGE(Boost COMPONENTS program_options REQUIRED) ...
Make sure you also link agains the catkin specified libraries (${catkin_LIBRARIES}), because there the ROS libs are listed in: target_link_libraries (main ${PCL_LIBRARIES}) ${catkin_LIBRARIES} )
70,114,257
70,115,148
Customizable way to instantiate objects in 1 expression in C++
In Rust, there is this crate which utilize Rust procedural macro to automatically implement builder pattern for any arbitrary struct defined. As there is no flexible way to instantiate Rust struct with some default and some provided values, this helps a lot in reducing boilerplate. Is there any similar thing to generat...
In c++ 20 you can do this: struct S { std::string str = "Hello"; float y = 1.0f; int x = 10; }; auto a = S{ .str = "Hi", .x = 8 };
70,114,706
70,115,679
How to get the base class offset of an inherited struct without creating an instance
Consider this code: struct A { int64 member; int32 member2; virtual void f(); }; struct B { int16 member3; virtual void b(); }; struct C : A, B { virtual void b() override; }; I'm interested in finding the offset of B in C. Previously with other structs with no virtual inheritance and only ...
I tried the following, and it worked: (char*)(B*)(C*)0x100 - (char*)(C*)0x100 It casts C* to B*; this is supposed to do the work. All the rest is support. I used an arbitrary number 0x100; it seems to work with all numbers except 0. Why it doesn't work for 0: it sees a null-pointer of type C*; to convert it to a null-...
70,114,894
70,115,949
What is the c++ approach for upgrading these c style casts for HtmlHelp API?
What is the c++ approach for upgrading these c style casts for HtmlHelp API? void CMeetingScheduleAssistantApp::DisplayHelpTopic(CString strTopic) { CString strURL = _T("https://help-msa.publictalksoftware.co.uk/") + strTopic; if (theApp.UseDownloadedHelpDocumentation()) { // CHM files use 3 letter...
reinterpret_cast will always trigger a code analysys warning In that case, you could invent your own pointer cast function. A smart compiler will most probably optimize this away: #include <cstring> template<class D, class T> D ptr_cast(T* x) { D rv; static_assert(sizeof rv == sizeof x); std::memcpy(&rv,...
70,114,988
70,119,548
SDL 2.0 BMP Blit screen / Update won't show picture
I ran into an issue with getting my picture to display. I couldn't get the picture to show up in the window. I accidentally ran the program twice (two windows) and the second window had the image in it. I can close the first and the image holds in the second window. It looks sketchy if I moved the window around. Said ...
You can't just throw something to be drawn once and expect it to stay on screen. What you've described in question is exactly how window manager operates - if some part of your window is not shown, there is no need to update it. But once it is visible again, window manager sends you a message that you need to redraw, a...
70,115,209
70,115,308
Reversing number in c++ with arrays
I am trying to find the reverse of the number entered by the user : This is my main.cpp code int number=0; cout<< " enter a number"; cin>>number; reverse( number); this is my function .cpp code int reverse( int number){ int last=0; int i=0; int array1[10]={0} ; int check=number; while ...
check=number/10 will be check=check/10 and j<=i will be j<i
70,115,227
70,116,558
C++ Reference - SomeType* &val vs. SomeType* val
I'm solving LeetCode 783. Minimum Distance Between BST Nodes and I've noticed that the difference between a correct solution and an incorrect solution is a reference (&) at my function call, as follows: Correct Solution: class Solution { public: void traverse(TreeNode* root, TreeNode* &curr, int &sol){ if (...
If you do this void foo(int * inner_ptr) { ptr++; } int main() { int arr[5] = {1, 2, 3, 4, 5}; int outer_ptr = &arr[1]; foo(outer_ptr); } the outer_ptr will still be equal to &arr[1]. You only changed the inner_ptr, the copy of the outer_ptr. You can change the thing it points to. void foo(int * inner_ptr...
70,115,272
70,115,431
Is it possible that `shared_ptr::use_count() == 0` and `shared_ptr::get() != nullptr`?
From the cppref: Notes An empty shared_ptr (where use_count() == 0) may store a non-null pointer accessible by get(), e.g. if it were created using the aliasing constructor. Is it possible that shared_ptr::use_count() == 0 and shared_ptr::get() != nullptr? Any example to illustrate that is true?
As stated in the notes, the aliasing constructor causes this to happen. For example: #include <memory> #include <iostream> int main() { std::shared_ptr<int> a = nullptr; std::shared_ptr<float> b(a, new float(0.0)); std::cout << b.use_count() << "\n"; std::cout << (b.get() == nullptr) << "\n"; } prints...
70,115,492
70,118,394
Implement a type trait for a class template that is true for the actual class template and classes that inherit it
I have a tuple-like class template like this template <class... T> struct Foo {} Now I need to implement something like this template <class T> void bar (const T& t) { if constexpr (IsFoo<T>::value) // treat it as Foo else // a generic solution } IsFoo can be implemented straightforward like t...
C++20 concepts make things much easier: template <class... Ts> struct Foo {}; template<class T> concept IsFoo = requires(T& t){ []<class... Ts>(Foo<Ts...>&){}(t); }; Demo.
70,115,892
70,116,429
Arrays (driver’s exam scorer)
I am working on this assignment and I am pretty new to c++, we are working with arrays, and I am having trouble reading inputs from a file. What I need to do is create a program that will read inputs from a file which is a driver's exam score, and the program should tell if the person pass or fail, how many answers wer...
See where you actually read the file. You even commented the place. And then go up the scope and see where you actually do it. You commented that too. I think you made a typo.
70,116,856
70,118,402
Swap nodes (with pointers) on doubly circular linked list
I am trying to write a doubly circular linked list, but I got somewhat stuck in swapping nodes. It's working fine for any node except the head node. I tried adding a check if node1 is the head without a luck. Where am I doing wrong ? Well, I stated earlier but for any other node except head the swap is working just fin...
Some of the problems include: With head->prev = node1 the node reference node1 is made to refer to itself, as at that moment head and node1 reference the same node. head should be changed also in other cases: it should change when it is equal to either node1 or node2 without any other condition. And then it should ju...
70,117,470
70,117,566
How do I get an error from `pop_back()` if `size()` is 0?
I was explaining to a coworker why we have small test with sanitizers on them. He asked about popping a vector too many times and if it was an exception, assert, UB and which sanitizer catches it It appears NONE catches them. Address and memory will if you call back() after popping too many times but if you pop and do ...
Both libstdc++ and libc++ have a "debug mode" with assertions, that can be enabled using: -D_GLIBCXX_DEBUG for libstdc++ -D_LIBCPP_DEBUG for libc++ Also -fsanitize=undefined appears to catch it, but the error message is much more cryptic.