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
68,461,857
68,462,066
Why is redeclaring a template member function allowed in C++?
class test{ public: int call(); }; int test::call(); int main(){return 0;} The above will not compile, with this error: error: declaration of 'int test::call()' outside of class is not definition However, the same code is allowed if templates are used as such: class test{ public: template<class T> int call();...
This is not a declaration, but a definition. This is called an explicit template instantiation of a function template. This forces the compiler to instantiate the int version in your case. You could also add explicit instantiation for many types: class test{ public: template<class T> int call() { return 0; } }; tem...
68,462,112
68,462,452
Is there a reason to differentiate between static and non-static data members in terms of prohibition of the usage of abstract types?
In class.abstract we can see in the Note 3 that: An abstract class can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it ([basic.def], [class.mem]). This rules out the usage of abstract classes as subobjects and it makes se...
Whether or not a class is abstract is not known until the class is defined. It has always been allowed to declare a static data member with an incomplete class type, as long as the type is complete by the time the static data member is defined. Since the type of a static data member may be incomplete on its declaration...
68,462,274
68,462,351
Is it possible to recover an allocated OVERLAPPED structure used in a pending I/O operation?
Let's say you're doing an asynchronous operation (like ReadDirectoryChangesW) using I/O completion ports. And for each call to the function, you allocate an OVERLAPPED structure (perhaps with some additional data) for use within the I/O completion callback. And then within the callback, after the OVERLAPPED structure ...
Is there a function you can call to retrieve a pointer to the OVERLAPPED structure used in any currently pending I/O operation No, there is not. It is your responsibility to keep track of your allocated OVERLAPPEDs. However, when you cancel an asynchronous I/O operation, you will still receive a completion notificat...
68,462,461
68,462,483
Returning the value of a class member pointer variable using 'this' pointer
My scenario is , I want to return the value of class member variable m_ptr using this pointer. What I have tried is , #include <iostream> using namespace std; class Test{ int *m_ptr; public: Test():m_ptr(nullptr){ cout<<"Def constr"<<endl; } Test(int *a):...
The indirection operator is in the wrong place. this->m_ptr would be correct to access the member, and to indirect through that pointer, you put the indirection operator on the left side: return *this->m_ptr;
68,463,323
68,463,336
Typechecking value before adding it to a vector
At one point in my code I have to add values to a helper vector. The following is a simplification of what is going on. #include <vector> #include <string> template<typename A, typename B> void add_value(std::vector<A> vec, B val) { if (std::is_same<A, B>::value) { vec.push_back(val); } } int main() ...
Use constexpr if (since C++17). If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded. template<typename A, typename B> void add_value(std::vector<A>& vec, B val) { if constexpr (std::is_same<A, B>::value) { vec.push_back(val); } } BTW: vec shoul...
68,463,370
68,463,728
The & should follow type or in front of the parameter when using reference as function parameter?
from what I know, if we use pointer or reference as a function parameter, it could written like this: for reference: void myfunction(int& x); for pointer: void myfunction(int *x); but I recently see people written like this: void myfunction(int &x); I think it is still a reference, but if in general &x means getting...
but if in general &x means getting the address of x, right? Outside a declaration, the & operator is the "address-of" operator. However, when declaring a variable, & is not an operator, but has a completely different meaning. It means that the declared variable is a reference. The compiler doesn't care whether you wr...
68,463,379
68,463,655
Getting an "Type alt_up_character_lcd_dev could not be resolved" error
I've been working on try to display anything on the LCD screen using the Nios processor and the DE10-Lite board for weeks. I finally found a code that may help, but the I've been unable to shake off this error message, the code I found is #include <string.h> #include <system.h> #include <altera_up_avalon_character_lcd....
In the header, the typedef uses the same name (alt_up_character_lcd_dev) for both the struct tag and the typedef alias. My assumption is that your compiler is confused by this. (but gcc doesn't have this issue) To fix it, struct alt_up_character_lcd_dev* char_lcd_dev; might help.
68,463,868
68,464,881
How to read char by char in c++ until new line
is there any way of reading 3 (or any quantity) strings char by char (in a loop where i can access the exact char that is being read)? For this input: banana apple orange I tried to do a loop like this: for (int i = 0; i < 3; i++) { while(cin.peek() != '\n') { char aux; cin >> aux; } } But it occurs that ...
In your case, the problem is that cin.peek looks at the next char but does not read it, at the same time when trying to go to the next loop iteration cin.peek was pouring on the same character as last time, respectively, it will look at '\n'. To avoid this, just add a single character reading after the end of the inter...
68,464,225
68,471,084
What is the best way to make a nested list in C++?
For those who know Python, the best way to explain what I want is by analogy: [1, [2, 3], 4, [5, [6]], 7] Obviously, I can implement my own class (template) to do this, but if the standard library has already invented this wheel, I want to avoid re-inventing it (or at least, avoid putting my half-baked re-invented ver...
So your value will have a type that either holds an int or a vector of values of the same type. This can be achieved with std::variant with a struct to allow for the recursive nature of the type (and with one more constructor to allow initializing it with your desired syntax) template<typename T> struct nested_list : s...
68,464,826
68,465,041
Make int overload a preferable one
Consider following code snippet: class Foo { public: void bar(std::size_t){} void bar(const char* ){} }; int main() { auto foo = Foo{}; foo.bar(0); } It produces ambiguous calls errors (check here). But I think from programmer's perspective it is pretty obvious that I want to call overload with std::s...
can be done like this in C++ 20 #include <cstdint> #include <iostream> #include <type_traits> class Foo { public: template <typename T> requires std::is_integral_v<T> void bar(T){ std::cout<<"hello size_T"; } void bar(const char* ){ std::cout<<"hello"; } }; int main() ...
68,465,823
68,466,322
How to allocate memory for a struct variable whose members are of type string
My struct: struct Company { string name; string profit_tax; string address; }; I allocated by using line: Company* a = (Company*)calloc(m, sizeof(Company)); with long long m =pow(10,9)+9 but pointer a is a null pointer after allocating. I don't know why this happened?. Please tell me solution, thanks!
You're allocating way too much memory for your computer (unless you have a huge amount of memory). See this godbolt example, the computation shows that on their hardware you would be trying to allocate 96GB of memory! If this is an exercise, maybe you have a typo somewhere on the size you have to allocate? If not, you ...
68,465,830
68,466,125
Template with fold expression creates unwanted parameter copy
The following prototype is intended to make synchronized print: #include <iostream> #include <string> #include <sstream> #include <mutex> #include <Windows.h> // for OutputDebugString std::mutex sync_mutex; template<typename T> void sync_print_impl(std::ostringstream& str, const T& t) { str << t << " "; } tem...
You do not need extra template function sync_print_impl. Following should be enough, as you can make use of c++17 's fold expression. In addition, use perfect forwarding to avoid coping the object. template<typename... Args> void sync_print_impl(std::ostringstream& str, Args&&... args) // ...
68,465,844
68,977,831
Headers for Clang from VS build tools and LLVM
I was experimenting with different compilers, build managers and IDEs for my new project in C++. I am using VSCode(v1.52) on a windows 10 machine. I installed VS build tools 2019 and also included C++ Clang Compiler for Windows and C++ Clang-cl for v142 build tools (x64/x86). The project uses CMake as build manager and...
VSCode build tools (C++ Clang tools for Windows) will link the Clang compiler with Microsoft implementation of the Standard Library Also, VSCode build tools has a component called: "C++ Clang-cl for v142" that gives you the freedom of using your own Compiler/Settings Regarding header files, on Windows you should use cl...
68,466,054
68,466,829
Is it possible to unfold a variadic (lambda) template and the pass those functions return value to another variadic function?
So I wonder given a variadic template function like following: template<typename...Fs> parse(int x, Fs...funcs); Where we ensure (through C++20 concept) that is convertible to std::function<double(int)>. Could we use unfold it into another functions argument, like passing to following one: template<typename...Ts> test...
Syntax would be: template <typename... Fs> auto parse(int x, Fs... func) { return test(funcs(x)...); }
68,466,107
68,467,039
Is there a way to enable/disable window resizing at runtime in qt c++
I have an application that has a settings window, and in that window I have a QCheckBox named "Resizable window", as you can probably tell it is responsible for enabling/disabling the ability to resize the mainwindow. I know you can write something like this in a constructor: this->setFixedSize(x,y); //if the checkbox ...
Calling setFixedSize() is essentially calling both setMaximumSize() and setMinimumSize(). Therefore, to undo the effect, you can set the minimum size to 0, and maximum size to QWIDGETSIZE_MAX (2^24 - 1, or 16777215). #include "mainwindow.h" #include <QCheckBox> MainWindow::MainWindow(QWidget *parent) : QMainWindo...
68,466,815
68,466,877
"Call of overloaded function is ambiguous" even with different argument order
I have a function fun() I wish to overload in the same scope. As per the rules of overloading, different order of arguments should allow for the overloading of the function as mentioned here. The Code: #include "iostream" using namespace std; void fun(int i, float j) { cout << "int,float"; } void fun(float i, ...
You give two integers, so the compiler have to convert one into a float, but which function shall be taken? int main() { fun(20.0,20); fun( 20, 20.0); } these calls makes the compiler happy, since you tell which function shall be taken.
68,467,000
68,468,937
How to linking OR-Tools to my CMake project?
Below is a small working example of how to link OR-Tools to a CMake project. Thanks to mizux and kamilcuk for your help. Also, mizux it might be good to update the documentation to specify that "USE_SCIP=OFF" might be required to solve error arising when building using FetchContent. Solution: CMakeLists.txt: cmake_mini...
Few points (OR-Tools dev here): You can find 3 integration samples here: https://github.com/or-tools/cmake_or-tools using local install / find_package() using FetchContent() using ExternalProject() Basically we provide an alias library ortools::ortools, you should depend on it. src: https://github.com/google/or-to...
68,467,781
68,467,888
What is the mean of '(void) (_p)'
our code has a line like: #define UNREFERENCED_PARAMETER(_p) (void) (_p) STATUS RequestHandler(Request *request) { UNREFERENCED_PARAMETER(request); ... return 0; } I don't know what is the mean of UNREFERENCED_PARAMETER, why translate the 'request' to '(void) (request)' Thanks!:)
When you try to compile this code int main() { int x = 0; } with gcc -Werror -Wall you get an error: <source>: In function 'int main()': <source>:3:9: error: unused variable 'x' [-Werror=unused-variable] 3 | int x = 0; | ^ cc1plus: all warnings being treated as errors ASM generation compiler ...
68,468,833
68,470,397
Convert time_point to string using std::format with format that includes date, time and subseconds
Let's assume we have a simple function that takes a std::chrono::time_point and returns a string using a given formatting string. Like so: std::string DateTimeToString(std::chrono::sys_time, const char * szFormat /*= "%Y/%m/%d %H:%M:%S"*/) According to the cppreference documentation of std::formatter we should be able...
You need: std::format("{:%Y/%m/%d %H:%M:%S}",tSysTime); Or you can simplify it to: std::format("{:%Y/%m/%d %T}",tSysTime); If your system_clock::time_point::duration isn't microseconds, you can force it to microseconds precision with: std::format("{:%Y/%m/%d %T}",floor<microseconds>(tSysTime)); The reason std::forma...
68,468,910
68,468,965
Undefined behaviour of Designated initializers in C++
The following C++20 program is accepted without any warning in all compiles I have tried: struct A { const int & x = z; int y = x; int z; }; int main() { return A{.z=3}.y; } https://gcc.godbolt.org/z/nqb95zb7c But every program returns some arbitrary value. Is it right to assume that this is undefined behavior?
Members are initialized in the order they appear in the class definition, hence the designated initializer is not that relevant, and also this struct A { const int & x = z; int y = x; // <- read of indeterminate value ! int z = 42; // <- doesn't really matter because y is initialized be...
68,469,602
68,469,630
C++ Debug Assertion Failed While Using Opencv
I am trying to compare two image and check whether they belongs to same person. This code giving Debug assertion failed Like here. I have checked, it can access to photos. Then what is the problem. People say that you are trying to access the something which is not actually exist. However, I could not find anything abo...
You are trying to access elements of vectors that have no elements. You have to allocate elements before accessing. You can use the constructor with specifying the number of elements to allocate to allocate elements, for example. To do this, change the lines vector<Mat> img; vector<int> label; to vector<Mat> img(1); v...
68,470,100
68,470,334
Why does a user-provided constructor allow for instantiation of a const class instance?
Here is an example from cpp reference. struct T1 { int mem; }; struct T2 { int mem; T2() { } // "mem" is not in the initializer list }; int main() { // const T1 t1; // error: const class with implicit default ctor T1 t1; // class, calls implicit default ctor const T2 t2; // const...
Why does a user-provided constructor allow for instantiation of a const class instance? Because the default constructor is responsible for initialisation of the object. Sure, in this case the constructor fails to initialise the member in this case, but the compiler cannot generally know that whether it does that. Bec...
68,470,276
68,499,684
How to use an LQR controller with collision geometry
I am using the examples/atlas/atlas_run_dynamics.cc, and I want to add an LQR controller to make the robot stand. I add my code int num_act,num_states; num_act = plant.num_actuators(); num_states = plant.num_multibody_states(); std::cout<<"num_actuators: "<<num_act<<std::endl; std::cout<<"num_multibody_state...
I actually have a PR open to better document exactly the error that you are seeing: https://github.com/RobotLocomotion/drake/pull/15437 . It's true that the LinearQuadraticRegulator does not have assume_non_continuous_states_are_fixed yet. That would be easy to add. What really needs to happen is that i take a full s...
68,470,294
68,471,812
Create and dynamically allocate multiple versions of a class
Due to different hardware versions of a project I am working on, there are two versions of a c++ class which control the hardware. The version of the class that should be used should be determined during runtime and therefore the instantiation needs to occur dynamically. The function names and return types of the two c...
You need a base class: class HWVerBase { private: std::string _msg; public: HWVerBase(std::string x): _msg(x) {} virtual void do_something() = 0; }; The virtual void do_something() = 0; means that both HWVer1 and HWVer2 must implement this method. You can now cr...
68,470,625
68,470,711
Inheriting constructors in C++20 (Visual Studio 2019)
I am using Visual Studio 2019 (v16.10.3) with /std:c++latest and this compiles: class Base { public: Base(int x) {} }; class Derived : public Base { // no constructors declared in Derived }; int main() { Derived d(5); } For the previous versions of the standard I have to declare inherited constructors with the...
Is this something new that was put in C++20 or is it some Microsoft specific thing? Not with relation to inherited constructors. What changed is that aggregate initialization may use parenthesis under certain conditions. Derived is considered an aggregate on account of having no private parts, so we initialize its ba...
68,470,939
68,471,199
C++ 'using' keyword in class hierarchy with function call operator and private inheritance
I have stumbled upon something that I don't quite understand. I have a class hierarchy that uses private inheritance where each of the structs defines a different function call operator. Oddly enough, the function call operator from the topmost struct is available in the most derived struct, despite the fact that a usi...
As pointed out by others in comments, it turns out I just had an error in my thinking. The using pulls in all the operators available in the respective base class, including the ones that were imported by the base class itself, and therefore all the operators will be available in the bottommost object. foo, on the othe...
68,471,039
68,471,441
passing reference argument to function taking universal reference of unique_ptr
I have two functions whose signatures I can't change. The first one takes a reference to an object, while the second takes a universal reference to a unique pointer of the same object. I'm not sure how to pass the first argument to the second. I've tried by passing a new unique ptr with the address of the reference, bu...
Your compiler complains because make_unique calls new on the type you are trying to instantiate, effectively copying the existing object. Of course, it can't do that, as the class is abstract. Unless you have a way to guarantee that the reference passed to MyUserClass is to a dynamic ("heap") variable (and its pointer ...
68,471,419
68,472,651
Is it possible to generate C++ template functions that are not inline these days?
It used to be that templated functions were not always inlined. There were tremendous problems in having template functions defined in a .cpp file, since it was unaware of what a different module had passed in as the template argument. So templates were almost always pure header file, everything included. However, code...
The issue is orthogonal to whether or not the operator is inline, the definition (body) of the template must be available at the point of instantiation. You've explicitly instantiated the Matrix class, but the issue is your operator * is a free operator, and so it is independent of Matrix and needs to be instantiated s...
68,471,860
68,481,380
Button style on the form
Please tell me how to correctly specify the arguments for the fact that all the buttons on the form had a style when you hover the mouse over these buttons? In addition to the style for the button, there is also a style for the form itself. I specify it in the constructor: { ui->setupUi(this); this->setStyleShe...
I think you are looking for this this->setStyleSheet("QWidget { background: rgb(49, 54, 59); color: rgb(220, 221, 218); selection-color: lightyellow; selection-background-color: darkcyan; }" " QPushButton::hover {color: darkcyan; border: 2px solid grey; border-radius: 1px};"); If your main form...
68,471,921
68,472,091
C++20: Why can't range adaptors and ranges be combined in one expression?
I am looking at the following snippet: std::vector<int> elements{ 1,2,3 }; // this won't compile: elements | std::views::filter([](auto i) { return i % 2 == 0; }) | std::ranges::for_each([](auto e) {std::cout << e << std::endl; }); // but this compiles: auto view = elements | std::views::filter([](auto i)...
Why can't range adaptors and ranges be combined in one expression? They can be. You just did combine them. You used elements as a range, and combined it with the range adaptor std::views::filter. std::ranges::for_each however is neither a range, nor is it a range adaptor. It is a function (template) that accepts rang...
68,472,240
68,472,329
Is there a more efficient way to code this part?
int reserveSeating(char seatingPlan[][COLS]) { char ticketClass, choice, letter; int column = 0, row = 0, rowStart, rowEnd; bool isValidInput = true; while (isValidInput) { cout << "\nPlease choose class (first class (F/f), business class (B/b), or economy class (E/e)): "; cin >> ticket...
Well, this portion: switch (letter) { case 'A': column = 0; break; case 'B': column = 1; break; case 'C': column = 2; break; ...
68,472,308
68,472,386
C++ question: what is "class UserDefinedType* MemberName;" when declared as a property of a class?
I would expect the declaration of a user-defined type member variable (a pointer to be specific) to look something like: ... public: UserDefinedType* MemberName; ... But I've seen this in a few examples: ... public: class UserDefinedType* MemberName; ... Apologies for what I'm sure is an obvious question to answe...
That's a forward declaration class UserDefinedType { }; class A { public: UserDefinedType * member1; // this is ::UserDefinedType class UserToBeDefinedType; // forward declaration UserToBeDefinedType * member2; // this is A::UserDefinedType }; class A::UserToBeDefinedType { // define the class ...
68,472,428
68,473,061
Check if enum class contains a specific identfier
I searched a bit here on SO and was surprise that I didn't find any similar question. Happy for any hints in case this has already been answered. I have a codebase with a lot of enum classes defined. Some of them specify a totalNum constant like enum class Foo : int { a, b, c, totalNum } Others don't ...
Found the answer myself in the meantime, using an approach like @jfh mentioned in the comments. First of all this is a way to check if an enum class contains an identifier with a certain name template <class EnumToTest> class EnumConstantDefined_totalNum { private: using Yes = int8_t; using No = int16_t; t...
68,472,555
68,603,512
Why can some libraries built by older compilers link against modern code, and others cannot?
We have a lot of prebuilt libraries (via CMake mostly), built using Visual Studio 2017 v141. When we try to use these against a project using Visual STudio 2019 v142 we see errors like: Error C1047 The object or library file ‘boost_chrono-vc141-mt-gd-x32-1_68.lib’ was created by a different version of the compiler tha...
I will try to answer some integral parts, but be aware this answer could be incomplete. With more information from peers we will maybe be able to construct a full answer! The simples kind of linking is linking towards a C library. Since there is no concept of classes and overloading function names, the compiler creator...
68,472,720
68,475,665
std::to_chars() minimal floating point buffer size
Given a generic integer type IntType, it is easy to determine the necessary buffer type for a std::to_chars operation for base-10 numbers: std::array<char, std::numeric_limits<IntType>::digits10 + 1 + std::is_signed<IntType>::value> buf; Since std::to_chars doesn't NUL-terminate, and only adds the digits (and a possib...
Note that the minimal buffer required is different depending on the floating point format desired. Using max_digits10 and max_exponent10 is always enough to determine the minimum number of characters necessary for base-10 output, assuming one doesn't want to output more precision than the floating point type contains. ...
68,472,846
68,478,565
How to write nested list in boost property tree and dump it as json?
I want to use a nested list in boost json. What I want is like {"matrix": [[0.0, 0.0], [0.0, 0.0]]} I couldn't find the nested list case in the official document
The document is not very detailed about create list value, I have tried to accomplish it, we need to call put with empty path, and push_back with empty path int main() { pt::ptree child_inner1; pt::ptree child_inner2; child_inner1.put("", 0.0); child_inner2.put("", 0.0); pt::ptree child; child.push_back(st...
68,473,480
68,473,619
How to retrieve the QPainter object in QML Canvas object
I have a QML Canvas, on which I'm drawing in C++ by overriding the paint(QPainter *painter) method and using a bunch of statements that use that painter object. Stuff like... void myGraphDisplay::paint (QPainter* painter) { QPainterPath path; path.MoveTo(0, 0); path.LineTo(100, 100); painter->strokePat...
The rules state that the process of painting a QQuickItem occurs in the paint method, not in another method. The generic solution is: Save the painting information in some attribute of the class. Invoke the paint method Implement the logic in the paint method. *.h private: QPainterPath m_path; *.cpp myGraphDispl...
68,473,518
68,473,586
C++ too many initializer values on GENERIC_READ when creating a file mapping object
I'm trying to create a file mapping object but I'm experiencing a few compiler errors. (I'm using MinGW GCC-8.2.0-3) I'm getting the following error from VS-code: too many initializer values on the GENERIC_READ line. HANDLE CreateFile( L"filename.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXIST...
Thanks to @Jarod42 for the answer. I had to assign the file handle to a variable: HANDLE fileHandle = CreateFile( _T("combatlog.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
68,473,598
68,547,698
Accessing Max Input Delay with C++ on Windows
I am having trouble obtaining certain data from Windows Performance Counters with C++. I will preface my question by stating that I am new to both C++ and to developing for Windows, but I have spent some time on this issue already so I feel familiar with the concepts I am discussing here. Question: How do I use Windows...
I asked this same question on Microsoft Q&A and received the answer: The Performance Counters in question require administrator privileges to access. All I had to do was run this program in administrator command prompt, and that solved my issue.
68,473,670
68,473,933
"Potential memory leak" with std::function
Consider this example: #include <vector> #include <string> #include <functional> #include <iostream> using closure_type = std::function<void(void)>; using closure_vec = std::vector<closure_type>; class callbacks { static closure_type common(std::string name, uint32_t number) { return [number, name]() { st...
Try closure_vec retval; retval.reserve(sizeof...(calls)+1); retval.push_back(callbacks::foo(number)); ( retval.push_back(std::forward<calls_t>(calls)), ... ); return retval; this avoids the const initializer_list contained copies of std function your code created, so should be more efficient as well. Live example. I t...
68,473,725
68,473,919
How do I get a destructor on an object in a vector not to throw a failed assertion?
I'm programming a Breakout game in C++. I'm having a HUGE problem that's preventing me from giving the game multi-ball functionality. I think it has something to do with the destructor. Have a look: for loop for the balls (Driver.cpp): for (Ball& b : balls) { // Loops over all balls (...) // Collision for when ...
You cannot modify a container while you are iterating through it with a range-for loop. You don't have access to the iterator that the loop uses internally, and erase() will invalidate that iterator. You can use the container's iterators manually, paying attention to the new iterator that erase() returns, eg: for(auto...
68,473,791
68,473,928
how to remove the last comma between 2 prime number
#include <iostream> using namespace std; int main(){ int a=0 , b=0; cin>>a>>b; for(int i = a+1;i < b;i++){ int counter = 0; for(int j = 2;j <= i / 2;j++){ if(i % j == 0){ counter++; break; } } if(counter == 0 && i!= 1){ ...
Instead of always printing the number followed by a comma, you can change your logic to the following: If it is the first time you are printing a number, only print the number. Otherwise, print a comma before printing the number. That way, the last number will never have a comma printed behind it. I suggest that you ad...
68,473,846
68,474,179
Wrong Answer on Leetcode for Leaf Similar Trees Problem done by BFS
I am trying to solve the given problem using Breadth-first Search (I know Depth-first search will be best suited for this scenario but I just want to try out things) My code seems to be working in case of other test-cases but fails in case of first test case. Please suggest some improvements in my code. Problem Link - ...
I tried dry running your code on example 1. Content of v1 : 6,9,8,7,4 where as content of v2: 6,7,4,9,8 since you are doing BFS traversal, leaf node at lower depth will be pushed first into the result vector than the leaf node at the higher depth. so it would not maintain the order from left to right. To maintain the o...
68,474,189
68,476,147
What is the currently handled exception after co_await?
GCC permits one to resume C++20 coroutines from catch sections and in the coroutine to call co_await again from its catch sections. What is considered then the current handled exception in such cases? Please consider an example: #include <coroutine> #include <iostream> struct ReturnObject { struct promise_type { ...
co_await can only appear outside of a catch block, as specified by the standard: An await-expression shall appear only in a potentially-evaluated expression within the compound-statement of a function-body outside of a handler. co_yield is defined as a variation of co_await, so it has the same limitations: A yield-e...
68,474,262
68,475,799
How can I make this as fast as possible? - Iterating through an image mat
The question is quite straightforward. I'll also explain what I do in case there is a faster way to do this without optimizing this specific way. I go through an image and its rgb values. I have bins of size 256 for each color. So for every pixel I calculate the 3 bins of its rgb values. The bins essentially give me th...
First of all vector<vector<T>> is not efficiently stored in memory as it is not contiguous. This as often a big impact on performance and should be avoided as mush as possible (especially when the inner arrays are of the same size). Instead of this, you can use std::array for fixed-size arrays or a flatten std::vector ...
68,474,298
68,474,387
Can't pass private member directly from main to function in C++
This my C++ code: #include <iostream> class Node { public: int data; Node* prev; Node* next; }; class Doublyll { private: Node* head; Node* tail; public: Doublyll(); Doublyll(int A[], int num); ~Doublyll(); friend std::ostream& operator<<(std::ostream& os, const Doublyll& src); ...
Make int Doublyll::Length(Node *p) a private member function and add a public int Doublyll::Length() that takes no arguments and does: int Doublyll::Length() { return Length(head); } (also you should probably make both of them const - int Doublyll::Length() const since they shouldn't modify anything) Then just cal...
68,475,182
68,475,455
c++ function polymorphism/template
My goal is to provide three ways calling the function listen(). Is there a better way to do this? (Like using template or default value parameters so I can implement only one listen() function) My current approach void listen(const int &port, const std::function<void(std::string err)> &f) { http_s...
IMO your approach is close to optimal. If I was writing this, I'd make only minor changes: void listen(int port, std::function<void(const std::string &err)> f) { http_server_.listen(port, std::move(f)); } void listen(int port, std::function<void()> f) { http_server_.listen(port, [f = std::move(f)](const std::st...
68,475,185
68,475,975
How to draw multi-color segmented circle using OpenCV?
What is the best way to draw multi-color segmented circle using OpenCV like below? What I found, it can be: Using cv.fillPoly Many points are required for an arcs accurate drawing, the number of segments is several hundred; Using cv.line by rotating the line in a circle; Using cv.line by rotating whole image like in t...
Using cv.ellipse you can draw segments pretty easily: from matplotlib import pyplot as plt import cv2 import numpy as np import random ANGLE_DELTA = 360 // 8 img = np.zeros((700, 700, 3), np.uint8) img[::] = 255 for size in range(300, 0, -100): for angle in range(0, 360, ANGLE_DELTA): r = random.randint(...
68,475,458
68,484,328
What is a nice way to cycle through an enum?
Background For a UI in an embedded project, I'm looking for a nice generic way to store a "state" and cycle through it with a button press, e.g. a list of menu items. Normally, I like to use enums for this purpose, for example: enum class MenuItem { main, config, foo, bar, }; Then, in my UI code, I can...
Rather then using _count, set the last "sentinel" value to the last actual value. enum Value { main, config, foo, bar, last = bar }; Then you avoid the problem of having an enum value that is not a valid menu option. in your increment for example instead of : v = static_cast<Value>( (static_cast<i...
68,476,065
68,485,724
How to overload operator<< with a reference pointer on the RHS?
I am trying to understand how to correctly overload the operator << with a pointer variable on the RHS, using a reference parameter. Here is an example code: #include <iostream> using namespace std; class A { public: void print(ostream& out) const { out << "Hello World!"; } }; ostream& operator<<(ostream& out, c...
I am guessing that -- in the spirit of similar overloaded functions -- you were trying to make your parameter a const reference. That is, a reference to a const object. Your parameter: const A*& handle Is not a const reference. It's a (reference &) to a (mutable pointer *) to a (const A). Change your parameter to t...
68,477,230
68,478,357
How does the std::is_union implementation work?
I'm currently going through the C++ standard library in some more detail, and I was wondering how the implementation of std::is_union works. In libcxx (LLVM), apart from directly using a possibly built-in __is_union, it is defined as template <class _Tp> struct __libcpp_union : public false_type {}; template <class _Tp...
Not all of the std library can be implemented in C++. You skipped the tests for various intrinsics. There is no way to implment is_union without intrinsics, essentially. The std library is not a library that ships with C++, it is part of the language. #include <vector> permits certain code to work; no vector header ne...
68,477,485
68,477,509
Sieve of Eratosthenes for first n prime numbers
I am trying to get my Sieve of Eratosthenes program to output only the first n prime numbers that the user requests. The Sieve works just fine on its own- it correctly outputs the first 100 prime numbers (as in my array below), but the counter variable in the last loop isn't working correctly and I can't figure out why...
You should count only prime numbers, not all numbers. Also the range of i for looping should be corrected. The first prime number is 2 and the element arr[100] is not available. for (int i = 2, count = 0; i < 100 && count != n; i++) // don't increment count here { if (arr[i] == 0) { cout << i << '\n'; ...
68,477,646
68,489,487
Efficient bitwise reverse of the successor
The most efficient way I've found to bitwise-reverse an integral type is this: template <class NT = std::size_t> NT reverseBits(NT num) { NT count = sizeof(num) * 8 - 1; NT reverse_num = num; num >>= 1; while(num) { reverse_num <<= 1; reverse_num |= num & 1; num >>= 1; count--; } reverse...
Think about it this way: How would I implement I+1 if I had to implement it manually? How can I "mirror" above implementation to compute r(I+1) from rI? Incrementing a number by 1 can be done as follows: Look for the rightmost (nearest to the LSB) 0. Change that 0 to 1. Set everything to the right to 0. Now lets mi...
68,477,749
68,478,015
What happened with this static method?
I have a static method called getSingleton() in a class called Renderer, which I use as a macro like this: Renderer.h #define g_Renderer Renderer::getSingleton() class Renderer { private: Renderer(); static Renderer renderer; public: Renderer getSingleton(); }; Renderer.cpp #include "Renderer.h" Renderer...
Your getRenderer() method is setup all wrong for what you are trying to do. For one thing, it is not static. For another, the static variable is only being declared, not defined anywhere, which is why the linker is complaining. You would need to add this line to Renderer.cpp to actually instantiate the variable: Rende...
68,477,805
68,477,921
XOR encryption program not encrypting the whole sentence
This is an updated question with the proper code and a couple of examples so that you guys can see what is going on. I'm having a really hard time trying to make work an encryption program. I can only use chars and no strings in any sense. I'm trying to encrypt any message that the user inputs in the program using the ...
The code IS "encrypting" the whole user input. You are just not taking into account that some of the characters that your ^ xor operation is producing are unprintable control characters, like 0x06, 0x1B, even 0x00, etc. Online Demo Also, you probably should not be XOR'ing the input against the key's null terminator. ...
68,478,345
68,478,479
Chicken Egg Class Interface in C++
I need some help understanding the syntax used in this problem for an assessment I took a while ago. Add the missing code to Chicken and Egg so the following actions are complete: Chicken implements the Bird Class. A Chicken lays an egg that will hatch into a new Chicken. Eggs from other types of birds should hatch in...
std::function<Bird* ()> is a wrapper for a lambda expression. You can implement a private variable std::function<Bird* ()> hatch_egg; like: class Egg { int hatchCount = 0; public: Egg(std::function<Bird *()> createBird) : hatch_egg(createBird) { throw std::logic_error("Waiting to be implemented"); ...
68,478,725
68,478,929
i can't display the first row of the file
i have a coding that read from a file. My problem right now is the output didn't display the first row of the file. i also cannot find the smallest value. but i already got the highest value . This is my coding : #include <iostream> #include <fstream> #include <iomanip> using namespace std; void total (ifstream & the...
The first row is swallowed by the first theFile >> year >> classA >> classB >> classC;, so remove this line we will get the first row. The clear and setg are not needed here, since the file stream is newly created. The duplicated definition values can be removed to make the code clear. For max and min value check, we n...
68,479,202
68,479,276
finding the minimum of 2 numbers in an array in C++
#include <iostream> using namespace std; int main() { int a[42] = {-16748, 1861305, -1677019, 2959868, 8279642, -5614317, -6959809, -8869681, 5841371, 684147, 9078506, -9854715, 5442553, -8007477, 5455657, 400271, -8326571, -589876, -2139466, 7869921, 9462518, 8289564, -1158751, -1908990, 3315049, 5073796, -2511851...
There are multiple statements which you need to correct. Firstly for (int i=0; i<=42; i+=2) Your array size is 42, so the indices to loop are from 0 to 41(inclusive). However, your loop also reaches 42, which will cause undefined behaviour(which is generally bad), so the correct way would be for (int i=0; i < ...
68,479,618
68,479,769
Create new data type in C++
Is there a way to create a new data type in C++. I have some variables whose values are never going to be >100. So, I want to create a new datatype to store values only between 0 and 100 which would also take up less memory. I could use unsigned short smth = 100; but unsigned short also takes up 16 bits and there will ...
If you want to "extract all the juice of performance from your application", you should not use other datatypes than types that are the size of a register (which may be int in your implementation). If you don't care about portability, I recommend using uint_fast8_t. It is atleast 8 bits, but the implementation uses the...
68,479,958
68,480,356
Bitfield using 1 byte instead of 1 bit
I am working on a networking application where I will receive 2 bytes and certain bits have specific significance. I am trying to implement that packet as a structure. The intent is to do a binary copy to object address and the fields of the packet are ready to be accessed. Here is a simple example representing my prob...
The source code of Microsoft Visual Studio' STL is open-sourced recently, you can check the implementation of bitset here, we can confirm that the data structure is an array, the sketch: template <size_t _Bits> class bitset { // store fixed-length sequence of Boolean elements public: using _Ty = conditional_t<_Bits...
68,479,959
68,481,377
Cannot open a file through fopen()
Im working on making a simulator with c++, for which I need to read files. my directory looks something like this proj ------>bin #stores the executable ------>include #stroes the external library includefiles ------>lib #stores the lib files of the libraries ------>obj #stores the .o files ----...
Your main is calling romReader.FreeRom(); I think m_Rom is not NULL. So the memory get freed, so the memory exception getting fired?!? Set it to NULL in a constructor of your class: class RomReader { ... public : RomReader() { m_Rom = NULL; }; ~RomReader() { if ( m_Rom != NULL ) delete [] m_Rom; }; ... }
68,479,971
68,480,106
Call variadic templated function with arguments from a std::vector
I need to convert elements of a std::vector to types based on a template parameter and call a function with these parameters. In pseudocode: template <typename T...> void foo(std::vector<std::string> v) { if (v.size() != sizeof...(T)) throw std::runtime_error("Bad"); bar(convert<T0>(v[0]), convert<T1>(...
If you know that the number of elements in a vector is equal to the parameter pack size, you can solve this problem by adding one level of indirection: template<typename... T, std::size_t... is> void foo_impl(const std::vector<std::string>& v, std::index_sequence<is...>) { bar(convert<T>(v[is])...); } template<ty...
68,480,093
68,480,203
QT : QTranslate is not working with QObject subclass
QTranslate is working fine with tr and QObject::tr but when I try to create a subclass of QObject its generating the correct ts file but unable to read it back. class Reporting : public QObject { }; Reporting::tr("I Am Reporting."); please help Thanks in advance
That's not a correct QObject. A designating macro and vtable are required, also you might want to provide ownership mechanism. class Reporting : public QObject { Q_OBJECT Reporting (/*whatever*/ QObject* parent = 0 ) : QObject (parent) /*whatever*/ { /*whatever*/ } ~Reporting () }...
68,480,684
68,480,794
Why I am getting different output on HackerRank than the output of my IDE?
I am trying to solve a problem named "Jumping on the Clouds" on HackerRank. I have written a code primarily and it gives the right output as my expectations. But when I am submitting the code on HackerRank it gives different output with the same input. How it is possible! I tried to compile in different IDE and text ed...
Your code has undefined behavior because arr is accessed out of bounds. The loop constraint is i < n, but you access arr[i + 2] and arr[i + 1].
68,480,817
68,481,270
Why does concatenation of a string an char in C++ return an empty string?
Why does concatenation of a string and char in C++ return an empty string? #include <iostream> #include <string> #include <assert.h> int main() { std::string s = "hello" + '4'; assert(s == ""); // why does s equal "" here? }
The problem is in std::string s = "hello" + '4'; which doesn't do anything remotely similar to appending a '4' to a string. The actual behaviour is completely different from your expectations. The string literal "hello" is represented as an array of six const char, with values 'h', 'e', 'l', 'l', 'o', and '\0'. (th...
68,480,964
68,481,637
Benefits of std algorithms about readability
In some code snippet, here on stackoverflow mostly, I often found myself reading code like this: std::array<std::string_view, 3> appleNames{"Fuji", "Golden", "Gala"}; std::copy (appleNames.begin (), appleNames.end (), std::ostream_iterator<std::string_view> (std::cout, "\n")); // print all the names It's just me or th...
To understand the motto "algorithms are more readable" you need to consider a bit of history. Suppose bare index based loops are out, then in C++98 the comparison is between this (no string_view, no std::array): #include <vector> #include <string> #include <iostream> #include <iterator> int main() { std::vector<st...
68,482,379
68,482,529
How to find the highest and smallest value
I want to find highest and smallest value in one function. I have tried it, however I only get the smallest value. This is because the code wasn't read from the first row and the first row contains highest value. This is my code: void price (ifstream & infile) { infile.clear(); infile.seekg(0); int year, mal...
Because the initial value for low_expenses is zero, you will never find any year with lower expenses, unless the expenses are negative. You should initialize your low_expenses to the greatest possible integer like this: low_expenses{ std::numeric_limits<int>::max() }; If the expenses can be negative, initializing high...
68,482,509
68,483,608
Rotate Array LeetCode (189)
The question is as follows: Given an array, rotate the array to the right by k steps, where k is non-negative. Here is my code: class Solution { public: void rotate(vector<int>& nums, int k) { int r =nums.size()-k; vector<int>::iterator it; it = nums.begin(); for(int i=0;i<r;i++){...
The code crashed because that the it would be invalidated after calling push_back, to fix it we may directly call begin. class Solution { public: void rotate(vector<int>& nums, int k) { int r =nums.size()- (k % nums.size()); for(int i=0;i<r;i++){ nums.push_back(nums[0]); nums...
68,483,570
68,513,697
How is charT checked for/enforced in template code?
I am very new to c++ and am trying to understand how "generic" types are "enforced" in templates, specifically with something like charT. After reading this question I understand that charT can be any char-like object, but I am wondering what the appropriate way is to check that the user actually supplied a valid charT...
Generally, this is can be done in C++ using type traits, std::enable_if and SFINAE (Substitution Failure Is Not An Error), assuming that you're using pre-C++20 code. The basic principle is to check if a type has a certain property and if it doesn't, to disable a function overload or class specialization. For example, i...
68,483,798
68,483,966
How to get pid of some process started inside child process with help if exec family in C/C++ in linux?
I want to get the pid of some process(let's call it Somebinary) which is started with the help of exec family inside child process and assume Somebinary never stops once started. I want to print the pid of this process from the parent process. I can't wait in the parent process as the child process will start Somebinar...
Note that exec does not "create a process" or change the PID, fork does. As @kaylum said, childpid is the PID of the exec'd process already. You can just print it: int start(std::string Somebinary){ pid_t childpid = fork(); if(childpid == 0){ freopen(logfile.c_str(), "a+", stdout); dup2(1, 2); ...
68,483,814
68,494,868
C++ Conditional compilation directives: multiple files
I have 2 files,main.cpp and head.h //main.cpp #define DEBUG2019 1 #include 'head.h' int main{ A A1; return 0; } //head.h class A{ #ifdef DEBUG2019 int p; #endif int q; }; Look, I have defined DEBUG2019 in main.cpp. But in my visual studio 2019, the int p is still greyed out in head.h. Why is that? Why head.h does no...
As far as I'm concerned, you should use #include "head.h" instead of #include 'head.h' Here is the code of main.cpp: #include <iostream> #define DEBUG2019 1 #include "head.h" int main() { A A1; return 0; }
68,483,888
68,484,643
How to display a timer simultaneously with the rest of the program?
So I've been making a terminal-based quiz as my first-year project, I decided to display a timer along with the code, but the timer doesn't let the program proceed cause of the infinite loop used in the timer. How do I proceed through this problem? void timer() { while (true) { clock_display();//Functio...
This problem is more difficult as it might seem. You want the same program to do 2 things at the same time. While this is a common scenario these days and most programs run just this way, this is not the level expected from first-year students. What you need is concurrent programming, supposed to be a hard stuff. So he...
68,484,180
68,484,565
Is it safe to use omp_get_thread_num to index a global vector?
I have a code like this: thread_local CustomAllocator* ts_alloc = nullptr; struct AllocatorSetup { AllocatorSetup( int threadNum ) { static std::vector<CustomAllocator> vec( (size_t)omp_get_max_threads() ); ts_alloc = &vec.at( threadNum ); } ~AllocatorSetup() { ts_alloc->res...
The documentation spells this out. The omp_get_thread_num routine returns the thread number, within the current team, of the calling thread. The binding thread set for an omp_get_thread_num region is the current team. The binding region for an omp_get_thread_num region is the innermost enclosing parallel region. T...
68,484,290
68,484,603
Is the memory address for string literals in different translation units the same?
Suppose we have the following cpp file. #include <iostream> int main(){ const char* p1="hello"; const char* p2="hello"; std::cout<<p1==p2; } Output 1 As we know, p1 and p2 are pointing to the same memory address (correct me if I am wrong). Now, suppose we have pointers defined in different translation un...
As mentioned in the comments, the C++ Standard does not enforce whether or not multiply-defined, identical string literals should be merged: 5.13.5 String literals        [lex.string] … 16    Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given charact...
68,484,314
68,484,406
C++Mutex and conditional Variable Unlocking/Synchronisation
I'm wanting to have several threads all waiting on a conditional variable (CV) and when the main thread updates a variable they all execute. However, I need the main thread to wait until all these have completed before moving on. The other threads don't end and simply go back around and wait again, so I can't use threa...
You have cv.wait(lck, [] {return finished[0] == true; }); in main thread, but it is not being notified. You'd need to notify it, and you'd better use another condition_variable for it, not the same as for worker thead notifiecation.
68,484,741
68,495,358
Convert QGraphicsItem::pos() to scene coordinates
I have a custom QGraphicsItem which overrides QGraphicsItem::itemChange() like so QVariant CustomItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { if (change == QGraphicsItem::ItemPositionChange) { QPointF newPos = value.toPointF(); QRectF rect = mapRectToScene(boun...
Ok so I think that I have solved my problem. The thing that I forgot to mention is that my item was initialized this way: auto item = new CustomItem(QPolygonF(QRectF(70, 70, 100, 100))); What I did to fix my problem is first initialize the item at (0, 0) and then use QGraphicsItem::moveBy() instead of giving positions...
68,484,818
68,486,035
Function-like macros with C++20 __VA_OPT__ error in manual code
I am building the code from the great manual of Recursive Macros and C++20 __VA_OPT__: https://www.scs.stanford.edu/~dm/blog/va-opt.html The code is #include <iostream> #define PARENS () // Rescan macro tokens 256 times #define EXPAND(arg) EXPAND1(EXPAND1(EXPAND1(EXPAND1(arg)))) #define EXPAND1(arg) EXPAND2(EXPAND2(E...
If you look here, I added a __VA_OPT__ support detector. #define PP_THIRD_ARG(a,b,c,...) c #define VA_OPT_SUPPORTED_I(...) PP_THIRD_ARG(__VA_OPT__(,),true,false,) #define VA_OPT_SUPPORTED VA_OPT_SUPPORTED_I(?) static_assert(VA_OPT_SUPPORTED); gcc and clang pass it; the MSVC version does not. I then looked at clang's ...
68,484,824
68,485,953
How can I update a scene in Qt?
I'm trying to learn c++ and for that, I would like to implement a board game (the game of life) in which we have several cells. If the cell is alive, we paint it white, if the cell is dead we paint it black. What I am trying to do at the moment is simply: make one cell alive show it on screen wait for half a second ma...
I changed a little your code, I use Mainwindow class instead of using the main function directly and used QTimer class and QRandomGenerator the result is this : In mainwindow.h : #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <vector> #include <iostream> #include <QApplication> #include <QP...
68,485,187
68,486,311
cannot declare variable ‘pdu’ to be of abstract type ‘Tins::PDU’
I'm using libtins to capture packets and moodycamel Concurrent Queue to queue captured packets. I note that the dequeue operation fails because PDU is an abstract type. Hence it fails to compile, error: cannot declare variable ‘pdu’ to be of abstract type ‘Tins::PDU’ I am not sure what to do at this stage to fix this...
moodycamel::ConcurrentQueue<PDU> PacketQueue; ... bool callback(PDU &pdu) { PacketQueue.enqueue(pdu); This cannot work correctly. You received a reference to the base class of some concrete object. Enqueueing this by value causes object slicing - you're just copying the base-class subobject and discarding all the ...
68,486,328
68,486,439
recursive function cannot return value as expected
I want to use recursive to achieve beziercurve, in recursive_bezier function it recursives all input points until there is only one point left and return that point, then in bezier function get that value by execute recursive_bezier. But in bezier function I can only get the value of the first input point, have no idea...
Ignoring the details, your code is this: cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t) { int control_size = control_points.size(); std::vector<cv::Point2f> temp_points; if (control_size != 1) { recursive_bezier(temp_points, t); } return...
68,486,391
68,486,675
C++why do constrained algorithms (e.g. std::ranges::merge) also return the end of the input ranges?
std::ranges::merge (for example) returns a bundle of iterators containing the end of the merged range, obviously, but also the end of the two input ranges. Cppreference says (https://en.cppreference.com/w/cpp/algorithm/ranges) Additionally, the return types of most algorithms have been changed to return all potentiall...
I'd like to quote Alexander Stepanov: When writing code, it’s often the case that you end up computing a value that the calling function doesn’t currently need. Later, however, this value may be important when the code is called in a different situation. In this situation, you should obey the law of useful return: A p...
68,486,663
68,487,410
Undefined behaviour on std::prev for transform-view
Consider the following code (click here for godbolt): #include <algorithm> #include <ranges> #include <vector> int main() { auto v = std::vector<short>{1, 2}; auto view = v | std::views::transform([] (auto i) { return static_cast<int>(i); }); auto it = view.begin() + 1; auto prev_it = std::ranges::prev...
This means there’s a compiler bug or the code calling std::prev invokes undefined behaviour – which one is it? The latter, although libstdc++ should be able to detect this failure and diagnose it better as it does if you ask it to. The issue here is that given: auto view = v | std::views::transform([] (auto i) { retu...
68,486,843
68,508,178
How can I use compressed DDS format textures with mip mapping?
Until now, I was setting my D3D11_TEXTURE2D_DESC::MipLevels to 1, but in order to improve performance and quality of terrain textures, I've tried to swap it to textures with mipmaps. So this is the code I'm using to create a texture with mipmaps: D3D11_TEXTURE2D_DESC t2d; ZeroMemory(&t2d, sizeof(D3D11_TEXTURE2D_DESC))...
Automatic generation of mipmaps does not support Block Compressed formats. You can confirm this using CheckFormatSupport. bool autogen = false; UINT fmtSupport = 0; hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { // 10level9 feature le...
68,487,191
73,549,048
Embed sqlite database into c++ executable
I think my question is related to this one, but that one is talking about a png and I'm not sure how to translate that to my case. I have a database created with sqlite in a file ending with .db. Now I have a program that only reads from this database. Is there a way to include the databse file into the executable? Now...
There exists an age-old trick to append something (such as a virus, but in this case a database) to the end of the executable. The executable will usually work just fine, but you can read (and perhaps even write) to the database as well. The already-mentioned custom VFS can help you accomplish this task. The other solu...
68,487,413
68,487,581
Is there an equivalent of "typename" for template types?
We have a template member function of the form: template <template <class> class TT> TT<some_type> foo() const; Now, in an invocation context where TT is explicitly specified from a dependent name: template <class T_other> void bar() { instance.foo<T_other::template_type>(); } Visual Studio is able to compile the...
Use template instead of typename. And, note that while typename would go before the ::, template goes after. template<class T_other> void bar() { instance.foo<T_other::template template_type>(); } Complete example.
68,487,558
68,488,214
C++ VS Code on OSX forrange loop
I'm stuck with forrange loop in VS Code. It gives me error: expected a ';' expected an expression VS Code C++ error mp[0] = 10; mp[1] = 200; mp[2] = 3000; mp[3] = 40000; for (int id : mp) // error for ":" and ")" { std::cout << id << std::endl; }
Thank you for answer, Cory but problem still there: explicit type is missing ('int' assumed) [13,21] reference variable "item" requires an initializer [13,27] expected an expression [13,31] { std::map<int, int> mp; mp[0] = 10; mp[1] = 200; mp[2] = 3000; mp[3] = 40000; for (auto const &ite...
68,487,710
68,487,940
How do you correctly use /GUARD:CF MSVC flag?
I am trying to use the /GUARD:CD MSVC flag. From the documentation, it says The /GUARD:CF option must be specified to both the compiler and linker The documentation also says that /GUARD:CF requires the /DYNAMICBASE option to also be set. However, when I try to compile, I see warnings for unrecognized options: cl -c...
The page you linked is a part of the manual to MSVC linker options. Linker options are case-insensitive. That page has a link to the manual to MSVC compiler options: When source code is compiled by using the /guard:cf option. Compiler options are case-sensitive. The proper cl invocation cl -c /W3 /O2 /EHsc /MP /Zi /n...
68,487,931
68,488,140
Assignment to temporary, GCC 9.3 bug or ill formed code/UB?
This question is very short and I apologize for the lack of detail I'm running short on time. I ran into what seems like a bug to me. You can find the code here: https://godbolt.org/z/eWMbb7qrK . This code compiles on clang since at least version 8. On gcc however, it does not compile before 10.1 (I only tested compile...
The defaulted constexpr assignment operator looks faulty on gcc-9.4 and prior. Define it yourself. #include <iostream> struct A { constexpr A() : i_{} {} constexpr A(const A&) = default; template <int i> constexpr A(const char (&the_data)[i]) : i_{i} {} constexpr A& operator=(A const& other) { i_ = other.i...
68,488,773
68,496,949
getting a error message with Python/C API
I was looking for a way to get error message from executing python code in C++. I tried some answers from How to get Python exception text, but any of them worked for me. Can someone explain me what I'm doing wrong? #include <iostream> #include <Python.h> int main() { Py_Initialize(); if (PyRun_SimpleString("s...
According to documentation (https://docs.python.org/3/c-api/veryhigh.html#c.PyRun_SimpleStringFlags), when using PyRun_SimpleStringFlags() (or just PyRun_SimpleString()): If there was an error, there is no way to get the exception information. So code must be runned the other way. Eventually, you can run in interpret...
68,489,697
68,493,360
adding elements to vector of pair
there is a question in which I need to manipulate vector of pairs but it seems to show some errors Code #include "bits/stdc++.h" using namespace std; bool compare(vector<int> arr1[3], vector<int> arr2[3]) { return arr1[1] < arr2[1]; } int max_trains(vector<vector<int>> arr[][3], int n, int m) { vector<pair<int, i...
You have mixed array and vector, generally, we don't need to use c styles arrays when we have a vector, I have fixed your code to be compilable: #include "bits/stdc++.h" using namespace std; bool compare(vector<int> arr1, vector<int> arr2) { return arr1[1] < arr2[1]; } int max_trains(vector<vector<int>> arr, int n, int...
68,489,890
68,490,054
C++ destructor for class object within another class
I am trying to implementing a SegmentTree class to be used in another Solution class. In class SegmentTree, the destructor is implemented as follows: ~SegmentTree() { destruct(root); }; void destruct(Node* root) { if (!root) return; destruct(root->left); destruct(root->right); delete root; ...
There must be exactly one delete for every new or there will be a memory leak. You can write a destructor like this: class Solution { private: SegmentTree* tree; public: Solution(vector<int>& nums) { tree = new SegmentTree(nums); } ~Solution() { delete tree; } }; However, you need...
68,490,348
68,490,497
Array index incrementing limit
Consider the code given below. let i = 0 and size of array be 3 and for all three index it satisfy the while loop condition.so will i be keep on increasing after it has reached value of 2?? while (A[i] <= 0) { i++; }
and for all three index it satisfy the while loop condition.so will i be keep on increasing after it has reached value of 2?? Yes, it will. Given that A[0], A[1], A[2] all are less than zero, then i will be increased to the value 3 and your code will try to access A[3]. That is illegal - out of array bounds - and the...
68,490,611
68,491,256
Why is my program printing the last record of a file twice?
I created a simple bank application program to ask a user whether they want to add a bank record to a file or show all the records available. Both these functions are facilitated by write_rec() and read_rec() respectively. But when the function read_rec() is applied, while it does print all the records available in the...
As already pointed out in the comments section, the problem is that the line while(outfile.good()) will only check whether the stream extraction has already failed. It will not tell you whether the next stream extraction operation will fail or not. It is unable to provide this information. Therefore, you must check the...
68,491,266
68,491,631
How to create a list of class types, in order to repeatedly call a template function by iterating through it?
I am working with protobufs in C++. Currently, I have a function that receives the protobuf name and the serialized protobuf data. Based on the name, it calls a decode function template to convert the data to json. Sample code: template <typename T> static bool DecodeToJson( const std::string& protostring ) { T pro...
Since template arguments have to be known at compile time, a for loop like this is of course not possible, but template metaprogramming can achieve something similar with recursive templates. #include <string> #include <typeinfo> template<typename T> bool decodeImpl(const std::string& theData); template<typename Firs...
68,491,463
68,491,901
node-addon-api how to pass int pointer back and forth between JS and C/C++
I have the following backend functions: // foo.c void cStart(pid_t* pid) { *pid = getpid(); // event-loop keep running until receive SIGINT signal } void cStop(pid_t* pid) { kill(*pid, SIGINT); } // addon.cpp #include "addon.h" #include "foo.h" Napi::Number addon::run_pipeline_wrapped(const Napi::CallbackIn...
You don't have to pass pointer to JS. You can use a global state instead: // foo.c pid_t* my_pid; void cStart(void) { my_pid = getpid(); // save the pid // event-loop keep running until receive SIGINT signal } void cStop(void) { // kill the process from earlier kill(*my_pid, SIGINT); } Note, however this ...
68,491,675
68,491,726
Check if std::vector<const char *> contains character sequence given as const char *
When I declare std::vector<std::string> v, i can easily check if it contains given char sequence if ( std::find( v.begin(), v.end(), "abc" ) != v.end() ) { // some logic if contains } but if i use std::vector<const char*> v and try to apply the same logic to find given char sequence my code does not work properly....
std::find calls operator==, which for const char * is defined to compare pointer values, not contents. (After all, who says that the pointed-to thing is a string? It could be a single char or even a one-past-the-end pointer to an array.) You'll have to use strcmp with std::find_if or iterate over the vector manually.
68,492,183
68,492,263
What is the equivalent of string temp = ""; in C?
I have a string in C++ called temp and currently curious how that string could be represented in C. Unsure if it would constitute being a pointer or using an array. string temp = ""; //c++ code char * temp; //c code
C doesn't have a native modifiable string class, so there's no simple parallel. If you want a modifiable buffer, you'll need char temp[n] = ""; (fixed size, automatic storage) or char *temp = malloc(n); temp[0] = 0; (resizable, in heap). If you have no intention of changing the string, you can use const char *temp = ""...
68,492,205
68,492,394
Private Static Constexpr Member Variable is Inaccessible in Main?
In my Environment class I have a private static member variable: class Environment { public: Environment(double air_density, Color background_color); void create_new(const Part &object); double get_air_density() const noexcept; void set_air_density() noexcept; Color get_background_color() const n...
Your data member is declared private (and NOT static, BTW), so it is simply not accessible to any code outside of the class. If you want main() to access the member, either: declare the member as public (and static): class Environment { public: Environment(double air_density, Color background_color); ... ...
68,492,673
68,492,679
Makefile for linking an extern global
I'm trying to use the g_struct variable that's defined in struct.cpp and declared in struct.hpp inside the test.cpp, but the linking fails. Why is that? // test.cpp #include "struct.hpp" int main(void) { g_struct.a = 1; return 0; } // struct.cpp #include "struct.hpp" Struct g_struct; // struct.hpp #prag...
You have to link struct.o, which has Struct g_struct;. test: test.cpp $(CC) -o test test.cpp struct.o
68,493,706
68,493,736
In C++ is it valid to pop_front() on a std::deque in a loop?
If I have this code: #include <deque> int main() { std::deque<int> d; d.push_back(1); d.push_back(2); d.push_back(3); d.push_back(4); d.push_back(5); for (std::deque<int>::iterator it = d.begin(); it != d.end(); it++) { d.pop_front(); } return 0; } I'm wondering whe...
It is invalid, since it no longer points to a valid iterator once pop_front() is executed, thus it++ will produce undefined behavior.