question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
63,089,319
63,102,312
c++ array of interfaces that contains class instances
How is an array that stores multiple IClass objects, into which we add instances of Class objects that implements IClass gets stored in memory? I am trying to confirm if my assumption is right (in case of 32 bit app) we have an array of 32 bit pointers to the IClass objects that have a 32 bit pointer to the actual inst...
how does the runtime store sizeof(Class) into something that have sizeof(IClass) allocated for it? It does not. By assigning a Class instance to an element of the IClass array you are effectively invoking the IClass copy-constructor and copying just the parent part of the object. This is called "slicing", as explaine...
63,089,641
63,089,861
How to make two different programs wrote in different languages to link?
I and my friend are working on the same project which is a pretty big so we split the project. Everything is ok till now but the real problem is that my friend has written the code in C++ but I have written the code in python now some of the functions that I have written will depend on those that he wrote. Like if I wr...
There are different possible solutions to this problem, depending on how complex your requirements are. If it is possible to make a C wrapper for the C++ functions you want to call from the Python side, ctypes may be an option. If the Python program needs access to a more complex C++ API, have look at swig, Boost.Pyth...
63,089,995
63,090,047
What is the time complexity of the following search algorithm?
/* * V is sorted * V.size() = N * The function is initially called as searchNumOccurrence(V, k, 0, N-1) */ int searchNumOccurrence(vector<int> &V, int k, int start, int end) { if (start > end) return 0; int mid = (start + end) / 2; if (V[mid] < k) return searchNumOccurrence(V, k, mid + 1, end); i...
It's O(N) because if you always take this "branch" (the array contains N elements with value k) return searchNumOccurrence(V, k, start, mid - 1) + 1 + searchNumOccurrence(V, k, mid + 1, end); you have to do 2 calls, and you can image it like a complete tree traversal, which is O(N)
63,090,184
63,090,566
Query regarding the default return type of a function in c++
A book says: If return type is not mentioned, it defaults to int. Just to check this I wrote the following code. #include <iostream> print() { return 3.3; } int main(void) { double d = print(); std::cout << d; return 0; } As expected I got output 3. There's no problem. I tried the following code w...
[In Visual Studio C++ since VS2005] You have to specify the return type otherwise you will get a compilation "error C4430: missing type specifier - int assumed. Note: C++ does not support default-int" ...Other systems generate just a warning. But, you ignored 1st issue intentionally. So let's assume print() returns int...
63,090,625
63,091,090
Synchronization requirements for DMA
Let me tell you a story: I have two buffers setup, to do what is called ping ponging. I have a DMA system pointing to each of the buffers. The system is setup such that the DMA is writing data to one buffer, while an interrupt processes the data in the other buffer. That would look something like this: #include <atomi...
I don't have any hard answers on hand, but from a glance, I would assume that because ping_pong is global, it has external linkage and therefore the compiler cannot optimize it out in that translation unit. The compiler doesn't know where it'll be written from in that TU, but, when finally linking all TU's together (fo...
63,090,885
63,095,848
DirectX: Get InfoQueue before Device
Is there a way to get the InfoQueue or set the break parameters before the Device is created? Right now i am creating the Device and then getting the InfoQueue, but any messages that are emitted before that point are going to be ignored and buried in the output window. ID3D11Device* pDevice; //...Create Device... ID3D1...
What you want to do is enable DXGI debugging which will provide debug information for the device & swapchain creation. #include <dxgidebug.h> #if defined(_DEBUG) Microsoft::WRL::ComPtr<IDXGIInfoQueue> dxgiInfoQueue; typedef HRESULT (WINAPI * LPDXGIGETDEBUGINTERFACE)(REFIID, void ** ); HMODULE dxgidebug ...
63,091,165
63,093,048
while loop in class won't execute c++
I have a while loop as part of a class. #include <iostream> #include <iomanip> #include <fstream> struct familyFinance{ //add 3rd member familyFinance; int acctNos; float Balance; struct familyFinance *nextNodePointer; struct familyFinance *dynMemory; }; using namespace std; class myFinanceClass { pr...
If the while loop is in the method and defined in that class, that won't execute, cause it's not allowed by the language. Methods defined within the class are not allowed to have any loops. There are a few more restrictions that apply for methods defined within the class. Such a case can be solved by declaring the meth...
63,091,296
63,091,607
Error with using keyword with curiously recurring template pattern
Does anyone know why the following code compilation cannot find N::balance_type? I'm using this example from Stroustrup C++ 4th Ed Page 771. It is the curiously recurring template pattern. class Bal {}; template<typename N> struct Node_base : N::balance_type { }; template<typename Val, typename Balance> struct Searc...
g++ says SearchNode is an incomplete type when you derive from Node_base<Search_node<Val,Balance>> test.cpp: In instantiation of ‘struct Node_base<Search_node<int, Bal> >’: test.cpp:8:8: required from ‘struct Search_node<int, Bal>’ test.cpp:14:25: required from here test.cpp:4:8: error: invalid use of incomplete ty...
63,091,884
63,091,936
Disambiguate pointer to overloaded const member functions and member operator
I have a small class with the following member functions: class Point3 { Point3 operator - (Point3 const & p) const {...} Point3 operator - () const {...} const float &x() const {...} float& x() {...} } I need to pass these member functions as arguments to other functions, and of course using just &P...
The compiler was nice enough to tell you what exactly is wrong. You forgot const: (Point3 (Point3::*)(Point3 const &) const) &Point3::operator- // ^~~~~ And for x (I assume you want the const overload): (const float &(Point3::*)() const) &Point3::x
63,092,169
63,092,510
Writing linked list to file truncates existing contents
I am trying to read some data from a file and then put it into linked lists then add some data to it and put the data in the file again but every time I run the code it deletes the only row on the file and write new data over it. struct Node { string name; string number; Node* next; }; this is the functio...
Your problem lies in the add_number() method. You are just using ofstream() which by default opens the file in write mode, i.e with the ios::out flag, which truncates the file by default. ofstream file("D:\\contact.txt"); Replace it with the one below to write. ofstream file("D:\\contact.dat", ios::out | ios::app | io...
63,092,183
63,092,365
c++: templates for Comparators throws an error
is there anything wrong with this function prototype? I am trying to pass less as the default comparator function. template<class iter, typename T, class compare> void bubble_sort(iter first, iter last, compare cmp = less<T>) the compiler throws an error saying: expected primary-expression before ‘)’ token void bubbl...
less<T> is a type, but you need to give an object of that type as the default argument. template<class iter, typename T, class compare> void bubble_sort(iter first, iter last, compare cmp = less<T>{}) If you want to be able to specify T explicitly, the best way is to swap the order of your template arguments, putting ...
63,092,215
63,092,834
C++: default constructor with initialized lists
So, I'm asking this question about constructors, but it applies to all member methods that a compiler provides to a class. I'm a little confused about the default keyword. What are the restrictions, what are the limitations (only Ctor with no parameters? Only one default?) and more specifically: Is the only way to use...
Only one default? Yes. Try making two default constructors: A() = delete; A(int val = 10) : x(val) {} And it will immediately result in an error: error: call of overloaded ‘A()’ is ambiguous Is the only way to use it (for class A) is: A() = default; The definition from cppreference: A default constru...
63,092,240
63,092,330
Is the reference returned from the function rvalue?
int a = 20; int& fun(){ return a; } int main(){ fun(); return 0; } Is the reference returned by func rvalue by itself?
No. If a function returns an lvalue reference, then calling it gives you an lvalue. If it returns an rvalue reference, you get an xvalue, and if it returns by value, you get a prvalue. Also, strictly saying the result of calling the function is not a reference. It's an lvalue expression of type int. In general, you ca...
63,092,552
63,092,614
C++: how to return object's set state when used as logical value
I have some class that can be set or not: Class obj; I want its value, when used in logic, to return whether or not it's set: if ( obj ) obj.Clear(); if ( !obj ) obj.Set( "foo" ); I thought of adding in an implicit conversion to bool, but I wonder if int would be necessary or whether there's a better way to ...
You can define a bool operator, as follows #include <iostream> struct Object{ bool state; explicit operator bool()const{ return state; } }; int main(){ Object o1; Object o2; o1.state = false; o2.state = true; std::cout << "\no1 state is " << (o1? "true": "false"); std::cou...
63,092,579
63,106,215
Adding Eigen library to c++ project using cmake
Unfortunately, i have some problems adding the headers only Eigen 3.3.7 Library to my Makefile with Cmake on my Ubuntu 18.04.4 LTS system. I can compile my code using the library by just copying the library folder in the include directory and using include_directories(./include/eigen3) in the CMakeLists.txt file. Howev...
The problems you are running into are caused by downloading the Eigen source code but not actually building the project. You may think since its a header only library that there is no build step. Well there is; it builds the package config .pc and Eigen3Config.cmake files. One of which you are trying to use. From my ...
63,092,701
63,092,805
C++ while loop reading ifstream, wont stop at eof
I'm trying to read a file with ifstream: std::ifstream is("sample_freeway.h264", std::ifstream::binary); std::cout << "reading" << std::endl; if (is) { while (!is.eof() || !is.fail() || !is.bad()) { auto buffer = std::make_shared<SimpleEncodedPacket>(); is.read(reinterpret_cast<char *>(buffer->...
Change while (!is.eof() || !is.fail() || !is.bad()) to while (!is.eof() && !is.fail() && !is.bad()) as said Adrian Mole. Or even better, use is.good() (thanks BitTickler)
63,092,955
63,093,291
Auto return value inference and c++ static typing
In this very interesting use case of auto return value inference(taken from: https://www.geeksforgeeks.org/type-inference-in-c-auto-and-decltype/ ): // A generic function which finds minimum of two values // return type is type of variable which is minimum template <class A, class B> auto findMin(A a, B b) -> decltyp...
You'll get one function that returns a value of common type of A and B. C++ is a statically typed language, so the type of cond ? a : b should be known at compile time. There are special rules to determine that common type. Informally speaking, it is a type that A and B can be implicitly converted to. If no such type e...
63,092,958
63,093,390
C++ server with recv/send commands & request/response design
I'm trying to create a server with blocking sockets (one new thread for each new client). This thread should be able to receive commands from the client (and send back the result) and periodically send commands to the client (and request back the result). What I've thought is creating two threads for each client, one f...
One approach is only create a background thread for reading from that socket. Write on whatever random thread your unsolicited events are raised. You’ll need following stuff. A critical section or mutex per socket to serialize writes, like when background thread is sending response to client-initiated message, and oth...
63,092,976
63,098,237
Calling any function from dll throws error
I'm making game engine in c++ which is compiled into dll. For last 2 weeks i was doing very boring cleaning of code to make it easier to use, unfortunantely didnt make any backup. Now when i put call to any function from that dll inside executable code it shows error window, when executable starts, which tells error c...
if not delay-load, when you load the process, the dll will also be brought to memory. so this error happens. How to tackle? I suggest you to make a fresh plain executable with just basic code and insert this dll. try it. if successful, insert a function call on a non-functional code (should not be called on startup) an...
63,093,618
63,093,754
C++ function that can take integer or float or double or any other castable to float
I am trying to implement a Vector3 struct in C++. I am overloading the "*" operator for handling multiplication with the scalar values. So it will work like this: v1 = Vector3(1.0f, 1.0f, 1.0f); v2 = 2*v1; v3 = 2.4f*v1; v4 = 2.4*v1; All 3 operations will return a Vector3 instance. However, I don't want to implement 3 ...
Since you are casting all of the types to float again, you don't need that. If you defined your function to accept a float, then passed an int or any convertible type, it would be cast to float automatically. The following code shows that #include <typeinfo> #include <iostream> struct Vector3 { Vector3(float x, fl...
63,093,683
63,093,927
Rotate a matrix (2d-std::vector) by 90°
I'm programming an IQ puzzle game for a project at college in C++, and I have the forms of the pieces stored in vector matrices. I need to be able to rotate them clockwise and counterclockwise but so far I haven't found any information on how to do this. As an example I have a purple piece stored like this: vector<vect...
Rotating clockwise: vector<vector<int>> rotateClockwise90(const vector<vector<int>>& x) { vector<vector<int>> result; for (unsigned i = 0; i < x[0].size(); i++) { vector<int> row; for (int j = x.size() - 1; j >= 0; j--) { row.push_back(x[j][i]); } result.push_back(ro...
63,093,750
63,101,493
Copying OpenCV mat to a known address with memcpy
I'm very new at C++ and I'm trying to create a DLL which uses OpenCV library. My DLL gets a raw image from other application and creates a MAT from the application's memory buffer. I send the buffer's address, which has a raw image, to the DLL and get raw image to OpenCV. This part works. But after processing image wit...
Ok. I solved this issue ; Mat img = Mat(height, width, CV_8UC4, address); cv::imshow("Image from GM", img); // same image copy to buffer back; memcpy(&address[0], &img.data[0], width*height*4.);
63,093,781
63,094,072
How and when to make use of the cmake 3.18 option Boost_NO_BOOST_CMAKE?
Current situation The Cmake 3.18 official documentation states: If Boost was built using the boost-cmake project or from Boost 1.70.0 on it provides a package configuration file for use with find_package’s config mode. This module looks for the package configuration file called BoostConfig.cmake or boost-config.cmake ...
When Boost wasn't supporting CMake officially, the latter had its own FindBoost.cmake module. With every Boost release, the CMake team ought to fix it for the latest Boost version and some other things, so the updated module get available only w/ next CMake release. The shipped module used in Module Mode of the find_pa...
63,093,814
63,093,872
Linker errors thrown when defining a function inside of a namespace?
Why am I unable to define a function inside a namespace in a .cpp file (not main.cpp)? For example, say I want to split my code up into 2 different files, main.cpp, and then lib.cpp (with an associated lib.h file). The following setup throws a linker error: lib.h: #ifndef LIB_H_ #define LIB_H_ namespace a{ void foo(); ...
using namespace a; is not a way to define a function inside a namespace. The syntax is the same as with the declaration: namespace a { ... } #include "lib.h" namespace a { void foo(){ std::cout<<"Hello World!"<<std::endl; } } For more details refer to: Namespaces.
63,093,950
63,094,606
How differ a pointer to first element of a vector vs back_inserter() of that vector?
I know back_inserter is a container "adapter", but what does it mean? If I take the example of function std::copy(), which takes as the third argument output iterator/pointer of vector TO copy, then I should give back_inserter instead of last iterator of that vector: #include <vector> #include <algorithm> #include <std...
The STL is designed with 3 major concepts: containers hold element(s) know about/create iterators don't know about generic algorithms. iterator refers to an element (or end), and can modify the elements don't know about algorithms don't know about the container their elements are in* (and thus cannot modify the co...
63,094,183
63,094,286
static_cast<int> of std::initializer_list::size_type spits out "invalid conversion" error
I'm working through "A Tour of C++" by BS, and am recreating the Vector class that he uses throughout, at least the first four chapters. I hit a snag building the second version of the Vector constructor with a std::initializer_list. A static_cast<int> is used to convert the size_type to an int so sz of my Vector can b...
Here elem{lst.size()} you are initializing a double* using a size_t. And why do you do static_cast<int>( lst.size() )? Your size should be of the same type as the size of the list, which is size_t, to avoid negative sizes. Here is your code after some editing: #include <initializer_list> #include <algorithm> #include <...
63,094,294
63,094,406
Order an std::map by the absolute value of key
I want to order an std::map by the absolute value of key with following code as the usual customized order vector<int> A = {-4,4,-2,2}; auto cmp = [](int a, int b) { return abs(a) < abs(b); }; map<int, int, decltype(cmp)> m(cmp); for (int x : A) m[x]++; But the result is m = {{-4,2},{-2,2}}. I don't know, why the key...
To order the int keys as 0, 1, -1, 2, -2, 3, -3, ... change the comparator to this (live): auto cmp = [](int a, int b) { return abs(a) != abs(b) ? abs(a) < abs(b) : a > b; }; This comparator uses lexicographical comparison with two sort keys: The absolute value of the number. The sign of the number.
63,094,311
63,094,318
Why is the variable name an expression?
int n=0; n; Why is "n;" an expression? It doesn't call any operators etc.
Because the language designers have decided as such when creating the grammar. As a more practical reason, grammars are often defined recursively. You can disallow a naked variable to be not allowed as an expression, but it's much easier to define that a variable is an expression as well. Because then you can define ...
63,094,371
63,094,666
How to register a mouse click in SFML 2.5.1
So, I have this code inside my game loop, which executes every frame: if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left) == true) { switch (j) {...} } With the way this code is setup, the switch case inside the condition will end up executing every frame as long as the left mou...
If this does not hurt your code too much, use sf::Event::MouseButtonReleased where you poll events. This way your mouse event code will run only once. Another solution might be to disable key repetition of the window which is something like window.setKeyRepeatEnabled(false). I am not 100% sure how would you handle this...
63,094,408
63,094,449
Can I get reference of an object with address of member variable in C++?
Is it possible to get a reference to an object if I have only the address of a member variable of that object? class example{ public: int var; }; int main(){ example exampleObject; int* point=&exampleObject.var; example* objPointer; // can i get objPointer to point to exampleObj...
Alert: don't do it regularly since it's very easy to mess thing out #include <iostream> class example{ public: int var; }; int main(){ example exampleObject{15}; int* point=&exampleObject.var; example* objPointer = reinterpret_cast<example*>(point); std::cout << objPointer->var; return 0; ...
63,094,587
63,094,632
Why is a class with an explicitly declared move constructor failing `std::is_move_constructible_v`?
A library I'm using requires that classes used with its templates are move constructible and assignable, for various internal reasons. I've written a class, and given it an explicit move constructor. #pragma once #include <entt.hpp> namespace ECS { //! Abstract base class for all components. class Component { ...
is_move_constructible is based on the behavior of is_constructibe; it's just is_constructible<T, T&&>. And is_constructible<T, ...> requires that you can do this: T t(...); Of course, for an abstract class, this is something you cannot do. Therefore, no abstract class can be "move constructible" as far as is_move_cons...
63,094,589
63,123,677
OpenGL: How to change the color of each vertex?
I am trying to change the color of the vertices of each triangle that I have created using the following code: This is the Point structure; this structure stores the position data and color data of each vertex: struct Point{ float x; float y; float z; float r; float g; float b; }; Here is creat...
When you want to change the color of your vertices over time, you probably want to modify it frame by frame as in the example at the following link: https://godbolt.org/z/Y1brGx I have set up a simple way of making those structures change their values during the rendering loop; you can get [more] creative with that onc...
63,094,844
63,094,999
Using enable_if to prevent declaration?
Stroustrup C++ 4th Ed Page 796 states that "If Enable_if’s condition evaluates to false, the whole function declaration of which it is part is completely ignored." and "...we don’t declare anything.". Does anyone know why the first f0() is being declared? Am I using enable_if correctly? My goal is to disable one of the...
You mustn't use this way because your object will be created in any case since the class doesn't have a condition to be created or not. And then here Enable_if<false, T> f0(int x) {};, the condition is false then there is no type. note that template class is instantiated on passing your parameter in the beginning and a...
63,094,845
63,095,153
Base class throws exception. How to propagate?
class base { public: base() : value(int()) { throw true; } private: int value; }; class derived : public base { public: derived() : base() { // base class constructor called, `value` to be initialized // I want this to propagate (rethrow) base class exception... how do I do it? }...
The code you have in your question already does exactly what you want (see demo here). Exceptions rewind the call stack to the nearest catch block that handles the exception type. Since the derived::derived() constructor does not catch the exception, it automatically propagates to the caller.
63,095,358
63,096,491
segfault due to finite recursion
I'm receiving a segfault which I believe to be caused by a large number of recursive calls. This has been noted here. My confusion is that the recursion is not infinite; there is a definite breaking point once a given event occurs and that event will always occur, eventually. I suspect the issue is that the number of r...
Each level of recursion takes up a certain amount of memory on the stack. On all platforms I'm aware of stacks have a fixed (but configurable) relatively small size. Ultimately the number of recursions is limited to (stack size) / (stack used per call) so to increase the number of recursions you need to either increase...
63,095,515
63,095,569
How to make classes inherit each other?
I have two classes ClassOne, ClassTwo each one in a separated file .h and .cpp as follow: // ClassOne.h file #include <ClassTwo.h> class ClassOne : public ClassTwo { protected: type m_string; // Required for "ClassTwo" } // ClassTwo.h file #include <ClassOne.h> class ClassTwo : public ClassOne { public: method...
Maybe the CRTP would solve your problem. First, create the class ClassOne as a template that uses a type ClassTwo as a parameter. This type shall be the class that inherits from ClassOne: template<typename ClassTwo> class ClassOne { public: void methodOne() { if (you need to use methods of ClassTwo) ...
63,095,688
63,095,769
Repeated Function call in the following program in C++
I have to write a programs that takes an input of string which has some '$' and digits. The output of the program is set of all possible strings where the '$ in the string is replaced by all the other digits. I have written the following code for it. #include<bits/stdc++.h> using namespace std; int numberOf(string in...
Assuming that this is homework: Start over. Your code is way too complex for this problem. I would treat everything as type char Loop/iterate over said string, using std::string::replace() to replace each instance of $ with each digit. -- If your teacher doesn't want you using std libraries, then add another loop and ...
63,096,291
63,096,430
Are bitwise operators faster?, if yes then why?
How much will it affect the performance if I use: n>>1 instead of n/2 n&1 instead of n%2!=0 n<<3 instead of n*8 n++ instead of n+=1 and so on... and if it does increase the performance then please explain why.
Any half decent compiler will optimize the two versions into the same thing. For example, GCC compiles this: unsigned int half1(unsigned int n) { return n / 2; } unsigned int half2(unsigned int n) { return n >> 1; } bool parity1(int n) { return n % 2; } bool parity2(int n) { return n & 1; } int mult1(int n) { return n ...
63,096,846
63,097,058
How to call the function of singleton pattern?
https://stackoverflow.com/a/26266280/462608 That link shows the following ways of calling are not allowed: int main() { // Utilizes the copy constructor Foo x = Foo::getInstance(); Foo y = Foo::getInstance(); // Utilizes the operator= x = Foo::getInstance(); } Then what is the way to call the func...
What the examples are showing is that it is an error to copy the singleton instance refered to by the return from Foo::getInstance(). You can avoid that either by capturing the returned reference Foo& x = Foo::getInstance(); or by directly calling the method you are interested in Foo::getInstance().some_method();
63,097,224
63,097,444
Cycle in Directed graph Can't understand why it does not work
Here is my code:- I use a map to keep track of nodes visited in current call to explore function. If some node is already visited and present in map, then i return a cycle. Also to every new call to explore from dfs function i clear map as well. It seems my code classifies come acyclic graphs as cyclic. But those input...
Consider this graph 1 / | / | v | 2 | \ | V V 3 It's an acyclic graph, but your implementation will classify it as cyclic. The reason is that when you start traversing, let's say from node 1, the visited and occurred ...
63,097,498
63,098,042
How to read numbers in a file and process them as integer in Qt
I have a file which consists of free space size of the drives and devices like the following: 32591253504, 33591253504, and so on. I wanted to save these numbers in integer form and then convert them to gigabytes. How can I do that in Qt? I have written the following program which stores numbers as a QString and then r...
Since it's not possible to divide strings by numeric value, a conversion into integer must be preceded. You can convert QString to integer by toULongLong() method, and QString::number() static method would help you converting integers to QString. QFile text_file_freespace("C:/.....space.txt"); text_file_freespace.open(...
63,097,610
63,097,638
How to write a factorial calculator that extends to negative numbers?
I'm trying to write a program for a factorial which tries to calculate as such. If n is the natural number, then the answer is n*(n-1)(n-2)....1(-1)(-2))(-3)...*(-10) Here is C++ code which just doesn't go beyond printing n. It works without the if else statement. #include <iostream> using namespace std; int main() { ...
if (val=1) should be if (val==1) = for assignment and == for comparison. I would expect your compiler to warn you about this very common error. If it didn't you should find out why, if it did you should pay attention. Compiler warnings will save you loads of time in the long run.
63,097,700
63,097,864
"pointer name" does not name a type error
Im new to C++. I get error on the statements marked //this shows error but its alternative (marked as but this works ). Can someone explain this please? #include <bits/stdc++.h> using namespace std; class Node { public: Node *next; int data; }; class Que { public: //this shows error /* Node *fro...
These: front = NULL; rear = NULL; are assignment statements. And this: Node *front = NULL, *rear = NULL; is a declaration (definition, initialization) statement using in-class initializers. Assignment statements are not allowed to appear in the class declaration body, whereas the initialization statements are.
63,097,703
63,097,762
Can I use strings as comments in c++?
In Python, there are two types of comments. The first using # (One-line comments) # This is a comment This_is_not() The other using """/''' (Multi-line comments) """ This is a comment """ ''' Yet another comment ''' NOT_a_comment() In C++, there are two types of comments. The first using // (One-line comments) // ...
Comments are skipped by the compilers during compilation whereas values and their assignments aren't. It'll be better to avoid using unused string values because nevertheless they're unused, they're at least included in compilation. OTOH, comments are ignored.
63,097,799
63,097,876
Corrupted data in vertex shader attribute location
My model looks stretched because of corrupted data in vertex shader attribute location Here's the vertex shader code: #version 330 core layout (location = 0) in vec3 vertPos; layout (location = 1) in vec3 vertNormal; layout (location = 2) in vec2 texCoord; layout (location = 3) in vec4 boneWeigths; layout (location = ...
boneIDs is a vertex shader input with an integral data type: layout (location = 4) in ivec4 boneIDs; If you want to specify the generic vertex attribute data for an integral attribute, then you have to use glVertexAttribIPointer (focus on I) rather than glVertexAttribPointer (see glVertexAttribPointer). Note, the ty...
63,098,070
69,696,852
Is it possible to pass a concept as a template parameter?
Is it possible to pass a concept as a template parameter? For example: I want to do something like this: template <typename t, typename u> concept range_of = range<t> && requires (t a) { {*a.begin()} -> std::same_as<u &>; }; But instead of giving the exact type u I want to give it a concept: templa...
It's possible to cheat a bit since we can pass lambda functions as template arguments ; a concept is just a meta-function from the domain of types to the boolean domain after all. Here is an example: template<auto F, typename T> using check = std::conditional_t< F.template operator()<T>() , std::true_type ...
63,098,409
63,098,517
How does function getline know newline character there
I am curious about principle behind getline function defined in header string, if cin >> operator will never set second operand have any newline character, how does getline work, how does it know it's a new line there?
getline uses istream::get() to read one character at a time in a loop. It's then easy for getline to check if the character just read is a newline and break out of the loop. getline doesn't use operator>>.
63,098,492
63,214,676
XCB: xcb_wait_for_event does not catch event generated by application
I have a small xcb based library for GUI programming. One of its methods forces redrawing of specified rectangle in window area. It creates Expose event and sends it to a window: void GWindow::redrawRectangle(const I2Rectangle& r) { xcb_rectangle_t rect; rect.x = (short) r.left(); rect.y = (short) r.top(); ...
The trouble was in examining event type. To extract type, one should use event->response_type & ~0x80, not just event->response_type
63,098,530
63,098,608
std::vector reallocations in transactional way: copy and move constructors
In this question I want to clarify some details about std::vector reallocations in C++11 and further. I have a class Data with all defined contructors and I'm putting objects of this class to std::vector: #include <iostream> #include <vector> struct Data { Data() { std::cout << "[Data]\n"; } ex...
When copy constructor is not available, std::vector has no other option than to use move constructor, even if it may throw. In such a case, there is only basic exception safety guaranteed (suppose destructor cannot throw). Note that a vector won't be in an invalid state, it will be in a valid state, but its contents ma...
63,098,625
63,098,641
Saving map<string,int> to text file
I have a string int map and I want to save it to a txt. I have not used c++ in a while and I'm hazy with pointers and such. int WriteFile(string fname, map<string, int>* m) { int count = 0; if (m->empty()) return 0; FILE* fp = fopen(fname.c_str(), "w"); if (!fp) return -errno; for ...
%s is for printing strings and you invoked undefined behavior by passing data having wrong type to fprintf(). You should use format %d to print int. fprintf(fp, "%s=%d\n", it->first.c_str(), it->second);
63,098,687
63,098,711
Why the `using` keyword cannot be used for static class member?
using makes an identifier to be visible in the global scope, but why cannot be used for static class member? For example using std::string::size_type; is wrong. Why?
Why cannot be used for static class member? You have misunderstood the use of using-declaration Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce a base class members into derived class definitions. The std::string::size_type; is an member type def...
63,098,988
63,106,446
Getting linking errors when using header CPP
I made a class that helps read .csv files in visual studio 2019 (The class is called CsvReader). #pragma once #include <string> #include <vector> #include <unordered_map> #include <fstream> namespace csv { class CsvReader { private: std::string fileName; std::vector<std::vector<std::string...
From what I can tell, there are at least two projects involved: a DLL called CsvReader and an executable (I'm going to call it CsvUser until I'm otherwise corrected). Before attempting to build CsvUser, you should make sure CsvReader is built. Also pay attention to whether the build is set to "Release" or "Debug", and ...
63,099,057
63,099,137
What happened when use vector::reserve or vector::resize
I'm user of C++14. When I coded for sort two dimensional array using std::vector with compare fucntion. But it didn't work as I thought, finally I found something weird things. Let's see code below. using namespace std; int n; vector<vector<int>> v; bool cmp(const vector<int>& l, const vector<int>& r){ return l[1...
Firstly, your cmp function may not be what you want. For example, it will judge {0, 6} as smaller than {3, 5}. Try this instead: bool cmp(const vector<int>& l, const vector<int>& r){ return l[1] < r[1] ? true : (l[1] == r[1] && l[0] < r[0]); } or this: bool cmp(const vector<int>& l, const vector<int>& r){ retu...
63,099,274
63,175,972
How to change text in widget using c++
I have widget dialogBottom with element Text and I need to change it's text in c++. As I understand, if I use meta word, then I can write the name of widget and access it's variables by creating variables with the same name in code. But by some reason variable Name is always null .h UCLASS() class HOME_API AAct_31 : pu...
As far as I know, if you want to change the text of a text block widget within a widget in C++, then you need to make a class of type UUserWidget and parent your widget blueprint with this class. And then in this class, you can call GetWidgetFromName to get specific widgets like so, // assuming that the native construc...
63,099,530
63,101,064
How to change values in a json file?
I have the following JSON-file : { "users":[ {"nom":"123", "name":"John", "family":"ala", "cash":1000 } ,{"nom":"456", "name":"Joe", "family":"ala", "cash":1000 } ,{"nom":"131", "name":"David", "family":"ala", "cash":100...
Cause You get the error, because you are trying to assign a value to the return value of a function (QJsonValue::toInt in this case). Solution Assign the value to QJsonValue, as demonstrated in the JSON Save Game Example: void Character::write(QJsonObject &json) const { json["name"] = mName; json["level"] = mLe...
63,099,565
63,101,369
c++ for loop exception
I am writing a backtracking algorithm, I think my writing is correct, but the output is wrong. I went to debug and found that the execution:When the program executes to this sentence in the for loop, sometimes it directly skips the following statement in the for loop. Question is here: Permutation Sequence I have writt...
My previous thinking was wrong,@Igor Tandetnik remended me . This problem requires a bit of mathematical skills or it will time out. Thanks for your help @john and @Igor Tandetnik. My finally code is here: class Solution { private: vector<int> hash; vector<int> factorial; bool flag = true; void dfs(int ...
63,099,720
63,099,768
What is causing the segmentation fault in here?
It is just a simple code for DFS of an undirected graph which I have tried through recursion.The recursion does terminate here(I'm guessing?).So,what is causing the segmentation fault ? I used the online compilers i.e, jdoodle, and tutorials point.(Okay this is stupid, sorry) #include <bits/stdc++.h> using namespace st...
You have out of bounds array access on g and vis in dfs. The size of both arrays is n but you access g[n] and vis[n]. Maybe you meant to call dfs(g,0,vis);???
63,099,784
63,099,901
In C (also C++), how '&' operator works as both address operator and bitwise operator ? As operator overloading is not supported by C
The operator '&' can be used in both of following way int a; scanf("%d",&a); and printf("%d",1&2). But different behaviour (for first as address operator and second time as bit-wise operator). I know operator overloading is not there in C. Then how it works ?. Also highlight for c++.
In "C" language, operators have different meaning when they are used as prefix to expression, suffix to expression or "infix" (between two expressions). Consider '*', which performs multiplication as 'infix' operator, and pointer indirection when used as a prefix. Similarily, the '-' operator, which performs subtractio...
63,099,900
63,100,294
Error in Dijkstra's shortest path algorithm implementation (using C++ STL)
I have tried to implement Dijkstra's algorithm in C++ using std::priority_queue.The function "dijsktra" will take input as 2 nodes, the source vertex and the destination vertex. However, I am getting incorrect answers every time. Kindly help me out and tell me where I have erred. My code- #include <iostream> #include ...
Mistake: Your code is not working due to vis[u] = 1 which never lets you enter the for loop. Actually there is no need of having a visited array in Dijkstra algorithm (atleast for this case). But using visited array here will decrease the time complexity and when there are negative edges it will be tricky, so be carefu...
63,100,057
63,100,138
Why is a derived constructor forced to call a base constructor in C++?
Why is a derived class constructor forced to call a base class constructor in C++ (either implicitly or explicitly)? For example: #include <iostream> struct B1 { B1() { std::cout << "B1"; } }; struct B2 { B2(int x) { std::cout << "B2"; } }; struct D1: B1 { D1() { std::cout << "D1"; } // implicitly calls...
A derived class is going to inherit the base class, which means that the functions of the base class need to be used in this derived class. Otherwise the inheritance becomes meaningless. If the constructor of the base class is not called, the member functions of the base class may not work.
63,100,524
63,101,027
function to return top 5 indexes of highest values of a vector
is there a function to do this ? I want to extract the top 5 index of the highest values in an index . I can only get the index of the highest value but then I have to delete it and do it again, any other method ? for (unsigned i = 0; i < 5 ; i++){ int index = std::distance(vMetric.begin(),std::max_element(vMetric...
Create an index array and partially sort that: std::vector<size_t> indices(vMetric.size()); std::iota(indices.begin(), indices.end(), 0); std::partial_sort(indices.begin(), indices.begin() + 5, indices.end(), [&](size_t A, size_t B) { return vMetric[A] > vMetric[B]; ...
63,100,550
63,100,719
std::chrono is not working properly in std::vector
I wrote a class, that does some action every second. Here it is: using namespace std::chrono; class TimerTest { public: TimerTest() { m_start = steady_clock::now(); } void update() // is called every iteration of the main loop { if (duration_cast<seconds>(steady_clock::now() - m_star...
The basic problem is that your range based for loop is making a copy of the TimerTest and updating the copy rather than the original. Try... for (auto &i: vec) { i.update(); }
63,100,583
63,101,156
Reference to local variable returned
I am trying to implement a character selection method, for a text based game and i know that it will not work the way i did it, because i am returning a refernce to an object with a lifetime limited to the scope of the method call. I have also tried to implement the method without referencing the Fighter parent class a...
In this: Fighter &fig1 = characterSelection(player,checkForBot,fig1); you are making a reference to a local object copy returned by the function. Returning a parent object has also the issue of object slicing; you should have that in account. If that's not a problem, however, you can add a copy constructor to the clas...
63,100,651
63,102,439
Reading .ini file in QT with multiple tags
1.For example [Tag1] key1=value1 key2=value2 key3=value3 . . [Tag2] key1=value1 key2=value2 key3=value3 . . This is the format of my abc.ini file. I can read the values of tag1 but I am unable to read for tag2 This is my code for Tag1 QSettings settings("abc.ini", QSettings::IniFormat); settings.beginGroup("Tag1...
Use this code QSettings settings("file.ini", QSettings::IniFormat); QHash<QString,QString>values; settings.beginGroup("Tag1"); QStringList childKeys = settings.childKeys(); foreach (const QString &childKey,childKeys) values.insert(childKey, settings.value(childKey).toString()); settings.endGroup(); settings.beginGrou...
63,101,206
63,101,272
The Terminal executes the first loop and neglets the other loop
I have a problem in executing my program via terminal. My program compiles without errors, but executes the for loop while it ignores while loop section. I checked if it executes the while loop section, and yes, it executed successfully without any error(note: to check if it executes the second loop in the program-whil...
Look at this line: for(int i=0;i<5,j<5;i++,j++) You are incrementing j until it equals 5, even though you are not using it in the for loop. When the for loop ends, j == 5 which means it is greater than 3, so the code in while is never executed - the condition of the loop is never met. You probably want to remove any u...
63,101,304
63,101,952
Multiple concept-constrained parameter packs in variadic function in C++20 does not accept arguments in the first parameter pack
The following code uses multiple parameter packs to define a variadic template accumulator function that accepts any numeric type or pointer to numeric type: // Compile with --std=c++20 #include <type_traits> template <typename T> concept number = std::is_arithmetic_v<T> && !std::is_pointer_v<T>; templa...
Deduction for function parameter packs only occurs for the last pack in the argument list. All other packs are considered a non-deduced context: The non-deduced contexts are: ... A function parameter pack that does not occur at the end of the parameter-declaration-list. Concepts doesn't affect this. You can't use con...
63,101,337
63,101,414
How to insert into a protobuf map in c++?
For the following Maps unable to insert into the Map map<string, double> doubleProps = 4; map<string, int32> intProps = 5; map<string,string> stringProps=6; Here are the following which I have tried , but its not working doubleProps["key"]="value" //doesn't work *(doubleProps["key"]).insert("value") //doesn't work dou...
This is the way to insert into a map in protobuf object in c++ (*mutable_stringprops())["key"]=value https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#map-fields
63,101,459
63,102,661
Why thread sanitizer complains about this std::ranges::views::filter code?
When running this code thread sanitizer complains about data race. Why? #include <iostream> #include <ranges> #include <thread> #include <vector> int main(){ std::vector v{11,22,33,44,55,66}; auto view = v | std::ranges::views::filter([](const auto x){ return x>47; }); std::jthread jt1([&]{ ...
[&] in a thread-running lambda should immediately ring an alarm. It is generally not safe to pass random objects by non-const reference to threads. In particular, it is not thread-safe to invoke non-const member functions on standard library objects. begin is not a const member function of std::ranges::filter_view. co...
63,101,814
63,101,983
MISRA 2008: Cannot understand 5-0-13 rule
I cannot understand 5-0-13 rule itself: Rule 5-0-13: The condition of an if-statement and the condition of an iteration-statement shall have type bool. Rationale: If an expression with type other than bool is used in the condition of an if-statement or iteration-statement, then its result will be implicitly converted ...
Rule 5-3-1 also applies outside if, while and for, e.g. extern void set_flag(bool); set_flag( ( a < b ) && ( c < d ) ); // Compliant set_flag( 1 && ( c < d ) ); // Non-compliant set_flag( ( a < b ) && ( c + d ) ); // Non-compliant set_flag( u8_a && ( c + d ) ); // Non-compliant set_flag( !0 ) // Non-compliant – // al...
63,102,126
63,102,540
Will modules in c++20 reduce compile time compared to traditional header-files?
Suppose we have the module interface source file foo.ixx in which the module foo is defined. We use import foo; in many different cpp-files. Will there be compile time reduction compared to the case where a traditional header-file foo.h is included in many different cpp-files? If the compile time is reduced, why is th...
Yes, one of the advantages of modules is that it can reduce compilation times. For comparison, here's how it's done today: // foo.hpp // some code // a.cpp #include "foo.hpp" // b.cpp #include "foo.hpp" Now when the 2 translation units a.cpp and b.cpp are compiled, some code is textually included into these source f...
63,103,096
63,106,454
How to create library that uses some other libraries?
I'm trying to create a graphic library (nothing serious, just to learn stuff). In Visual Studio I have one solution and two projects in it - dll and exe. For window management I use GLFW library. In my own window class I want to have a private memeber of GLFW Window structure. The problem is that my exe project doesn't...
Thanks to @Manuel I figured out how to do it: both - dll and exe projects, have to include libraries' header files. My solution: in dll I use precompiled headers so all libraries' header files are included in that file with a relative path. In dll project settings I put proper paths so any libraries files will know how...
63,103,417
63,103,482
Why does using void in BST insertion program not work
Below is my code for BST insertion. I want to use void return type for insert, instead of the regular way of using 'struct node*' as its return type. I am unable to find an error or logical error in this. Can someone explain in detail as to why isn't my code working? #include<iostream> using namespace std; struct nod...
The problem with your code is, whenever you make changes to the variable nroot (not changes to values nroot is pointing to) in the insert function, the changes will be local to the insert function. So they won't appear on the outside of the insert function. So that's not the correct way. For doing this, you can either...
63,103,499
63,104,071
Understanding operator overloading 'const' syntax for use in STL map
I am trying to understand the syntax of operator overloading for operator < where the second const word needed for the compiler to be happy. bool operator < (const point& rhs) const { // what's the rationale for the second const word here? Take for example this struct struct point { int x; int y; point (...
The outer const on the end of a method declaration tells the compiler that the method's *this object is to be const. std::map stores its keys as const values. So any operators that are applied to the keys need to be marked as const, or else they will fail to compile. std::map uses operator< by default to order its keys...
63,103,535
63,103,625
Why is my out_of_range exception not being caught
I am new to cpp and I am trying out several things. This one I can't seem to figure out on my own. #include <cstdio> #include <stdexcept> template <class E, class V> struct Pair { E first; V second; Pair(E fst, V snd) : first(fst), second(snd) {} E getFirst() { return first; } V getSecond() { re...
Because the throw code is never actually reached. In this line here: std::printf("%d\n", test2.getSecond()->d[2]); getSection() returns a pointer to the vec object. When you then do ->d you are accessing the d array, within the vec object. Thus, when you add the [2] to the end, you are accessing the element at index 2...
63,103,589
63,103,690
C++ OpenCV imread file path format for windows
I've tried to google this to no avail. Please help me understand what is wrong with this file path: Mat lena = imread("C:\Users\dasboomer\Desktop\Building-Computer-Vision-Projects-with-OpenCV4-and-CPlusPlus-master\Chapter03/lena.jpg"); I've tried changing: backslash to double backslash backslash to forward slash back...
\ is used for an escape sequence. Instead, use the below lines of code: Mat lena = imread("C:\\Users\\dasboomer\\Desktop\\Building-Computer-Vision-Projects-with-OpenCV4-and-CPlusPlus-master\\Chapter03\\lena.jpg"); or Mat lena = imread("C:/Users/dasboomer/Desktop/Building-Computer-Vision-Projects-with-OpenCV4-and-CPlus...
63,103,592
63,170,817
C++ listener on event is not getting event using socket io C++ client
I created sample app, for sending/receiving messages between node.js app which is running as socket.io server and C++ client, Below is my code of C++ client side: sio::client io; socket::ptr current_socket; string w = "harshil"; io.set_open_listener([&]() { io.socket()->emit("message", w); // Can able to send messa...
To those of you who stuck as me, then below sample code will be helpful for them. Created different sample code for node.js acts as socket.io server and main.cpp file acts as client, 'use strict'; const express = require('express'); const app = express(); const serverHttp = require('http').Server(app); c...
63,103,826
63,103,894
C++ | How can I break this inter-class dependency issue?
I provide to you a MWE: #include <iostream> class C; class A { public: A(C &cc) : c(cc) { } int functionA() { return 0; } C &c; }; class B { public: B(C &cc) : c(cc) { } int functionB() { return c.a.functionA(); } ...
Work with complete types by moving the constructors and member function implementations out of the class declarations. #include <iostream> class A; class B; class C; class A { public: A(C &cc); int functionA(); C &c; }; class B { public: B(C &cc); int functionB(); C &c; }; class C { publi...
63,104,257
63,104,615
How to initialise and access a const char* const*
I saw a C++ code where a struct is defined as below with weird const char* const* struct TestStruct { const char* const* text; void* data; }; I need to use the above struct and return an object of it from a function. But for that how to initialise the text variable to a constant string? Also, how to access th...
Constants are immutable, so they cannot be assigned to. They can only be initialized. To return such a struct from a function you can use aggregate initialization (curly brace initialization). This struct can be initialized with any char**, but the one accessing it can only read from the char**, but cannot modify it. T...
63,104,268
63,107,745
c++: request for member [function] in [class], which is of non-class type [class]
while trying to compile this: class DateTime { private: Date d8; Time tym; public: DateTime(Date idate=Date(),Time itime=Time()) { d8=idate; tym=itime; } void set(Date idate,Time itime) { d8=idate; tym=itime;...
In assignment operator you should return a reference to the same object: DateTime & operator= (DateTime & dt2) // without () after dt2 { d8 = dt2.get_date(); tym = dt2.get_time(); return *this; }
63,104,270
63,104,585
Can I declare a variable in an “if statement”?
I am writing a "vending machine" program and I need to have 5 items where 3 items cost an integer amount and the other 2 cost a decimal amount. I am only using if statements in this code, but there is an error with my cost variable. What did I do wrong? Code below: #include <iostream> using namespace std; int main() {...
The problem is that you are doing the following: int main() { [...] if (input == 1) { cout << "You added Popcorn to your cart." << endl; float cost = 2; cout << "Your total is $" << cost << endl; } [...] if (money > cost) { [...] } [...] } The scope of the va...
63,104,410
63,105,978
Variadic template argument list with changing return type
I am trying to make a templated variadic with a changing return type. If the number of arguments is 1 then it should return a pointer to the only argument, otherwise it should return a tuple of pointer of the argument: int var = 0; A *ptr_A = foo<A>(var); auto *[ptr_A, ptr_B] = foo<A, B>(var); and this is the code i h...
The straightforward if constexpr (sizeof...(Args) == 1) { return AddComp<Args...>(entityID); } appears to work just fine. Clang demo, MSVC demo Here's a solution that works with C++14: template <typename T> decltype(auto) AddComponent(EntityId entityID) { return AddComp<T>(entityID); } template <typename... Ar...
63,104,550
63,104,586
Does stringstream ignoring whitespaces?
I was reading about stringstream and found this example. stringstream ss; int foo; int bar = 0; ss << 100 << ' ' << 200; ss >> foo; ss >> bar; cout << "foo: " << foo << '\n'; // 100 cout << "bar: " << bar << '\n'; // 200 Why the value of variable 'bar' is 200? Shouldn't a 'bar' read a space from stream and get an AS...
Does stringstream ignoring whitespaces? Technically the operator>>() function ignores leading whitespace. Doing ss.ignore(1) is a way to do it manually, but it's unnecessary. On the other hand, the function std::getline() does not skip whitespace. So if there is leading whitespace you will have to remove it manually....
63,104,551
63,104,777
Why alias a template parameter in C++ standard containers?
Reviewing the code of Microsoft's STL (specifically std::vector), I came across the following lines of code (irrelevant code replaced with /* ... */): // CLASS TEMPLATE vector template <class _Ty, class _Alloc = allocator<_Ty>> class vector // varying size array of values { /* ... */ public: /* ... */ using...
I was wondering why the convention of assigning a type alias to a template type is used here? Because it is the standard way of doing, makes less error-prone code, less typing, more readable, and all the above makes life easy! For instance, let's consider the const_pointer, public template alias of std::vector usin...
63,104,562
63,104,624
how to use default constructor while using composition
Here is the code where i used composition. I removed the non-relevant functions to make it little easier to understand .When i run this code using parametrized constructor, it work fine. But if i use default constructor while initilizing it does not work, the code terminate in between. #include <iostream> using namespa...
You aren't using any constructor because links and page are pointers. Pointers do not have constructors. Maybe you want this? webpage page; website site("website", &page); Now because page is not a pointer the webpage default constructor will be called. Or looking at the rest of your code, probably this is correct. we...
63,104,829
63,104,932
what is the difference between x=10 & x{10}?
I'm new to programming and i saw 2 types of variable initialization. what is the difference between int x=10 && int x{10}? Is int a class and x is an object in this case? #include <iostream> using namespace std; int main() { int x=10; int y{10}; return 0; }
A difference is that the compiler will have checked that the value 10 was in-range for the type of y, rather than a narrowing conversion. For example, if you set them both to 4 billion on a system where int happened to be 32 bits... int x=4'000'000'000; int y{4'000'000'000}; ...then the second line would be required t...
63,104,956
63,105,080
Is it possible to enable/disable a pure virtual function with `requires` clause?
I have an adapter class which handles classes of the same concept. Now, I want that adapter, based on template parameter RO (read only) to disable pack(). But I don't know if that is not supported in pure virtuals or just I write it wrongly. template<bool RO> // means read only functionality class Adapter { struc...
In the C++20 standard, 11.7.2 [class.virtual] paragraph 6 says: A virtual function shall not have a trailing requires-clause (9.3). *[Example: struct A { virtual void f() requires true; // error: virtual function cannot be constrained (13.5.2) }; — end example] It's more verbose, but you could instea...
63,105,081
63,105,099
char 5: error: control may reach end of non-void function
I'm new to programming and I was trying to solve this question on LeetCode where: Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. My Solution: class So...
In this line: addDigits(sum); You're calling the function, but you're not doing anything with its return value. You have to actually return the value: return addDigits(sum);
63,105,087
63,105,285
Finding largest value in array using recursion
I've been studying to ' Data Abstraction and Problem Solving with C++ ' book at recently, however i did stuck at some point. I'm at recursion chapter, and i faced with a problem which is ' Finding largest value in an array'. As you know i have to solve this problem with recursion perspective and actually i already solv...
I would recommend you use a helper function that calls your largestvalue function like so: int largestValue(int arr[], int size){ int middle = (size - 1)/2; int first_max = largestValue(arr, 0, middle); int second_max = largestValue(arr, middle + 1, largest - 1); if(first_max < second_max){ retur...
63,105,216
63,105,862
Incorrect Pivot Selection for Sort Algorithm
I'm trying to implement the multi-GPU sort algorithm outlined in the paper "Comparison Based Sorting for Systems with Multiple GPUs". The algorithm relies on the following key insight (page 5): Given the two sorted arrays A_α and A_β, there exist a pivot point P in A_β and its “mirrored” counterpart P' in A_α that part...
I think this code should do it. We want to find the greatest pivot > 0 such that a[a.size() - pivot] >= b[pivot - 1] (least upper element of a greater than or equal to greatest lower element of b), or 0 if no such pivot exists. Since pivot is the greatest possible, this implies that pivot == b.size() (least element of ...
63,105,833
63,105,935
What is the C++ equivalent of the % or .format operator in Python?
I am quite new to C++ and I am writing a program that needs an operator that does the same thing as the Python % operator. Is there any equivalent in C++?
C++ has several ways to do IO, mostly for historical reasons. Whichever style your project uses should be used consistently. C-style IO: printf, sprintf, etc. #include <cstdio> int main () { const char *name = "world"; // other specifiers for int, float, formatting conventions are avialble printf("Hello, %s\n"...
63,105,858
63,106,101
What happens when std::move is called on a rvalue reference?
Consider the following c++ programs: string construct(string&& s) { // Passing a r-value reference as an argument to the assignment operator string constructed = s; return constructed; } int main() { string original = "Hello"; string temp1 = construct(std::move(original)); printf("%s\n", origi...
string constructed = s; This does not cause a move because s is not an rvalue. It is an rvalue reference, but not an rvalue. If it has a name, it is not an rvalue. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression. string constructed = std::move(s); This ca...
63,106,033
63,106,591
Why doesn't `std::lock` lock mutexes using a global ordering?
std::lock and std::scoped_lock can be used to lock a series of mutexes while avoiding a deadlock. Apparently, they use some algorithm composed of locks, try_locks and unlocks to achieve this. As it should be simpler, couldn't std::lock and std::scoped_lock lock the mutexes using some kind of global ordering (such as th...
That can deadlock with other algorithms. Suppose one lock protects a collection of objects and another lock protects an individual object in that collection. Code that doesn't call std::lock will lock the collection first, then find the object, and then want to acquire the lock that protects that particular object. If ...
63,106,457
63,106,515
Improve numerical accuracy of LineLine intersection method (3D)
I coded the following LineLine intersection method: double LineLineIntersection( const Eigen::Vector3d& origin1, const Eigen::Vector3d& ray1, const Eigen::Vector3d& origin2, const Eigen::Vector3d& ray2) { if(abs((origin1 - origin2).norm() - 1.0) < 0.000001) return 0; auto n1 = (origin2 - origin1...
You're using the type "double", try to change it to "long double" or "__float128" if it exists in your version of G++. Also, you can use "BigDecimal" in Java for better accuracy or maybe some long arithmetics from Python.
63,106,624
63,106,679
Priority Queue Call Simulation C++
I'm working on a call center call queue simulation model. I've created a vector of caller objects and assigned them exponential distributed random inter-arrival times, then assigned calculated arrival times in the call center class. I would like to then copy each caller object into a vector priority queue, however I ke...
random_device rd1; Your class has a std::random_device as a class member. std::random_device's copy constructor is deleted: The copy constructor is deleted: std::random_device is not copyable nor movable. This makes this class, which contains this class member, also have a deleted copy constructor. After all, if a c...
63,106,719
63,106,927
Assign a pointer to a lambda function countaining variables passed by reference
I would like to assign a pointer to a lambda function, in which the lambda function is taking variables passed by reference, not by value. int main() { // what I can do, but not quite what I want auto funcy = [](const double i ) { std:: cout << "this is i: " << i << std::endl; }; void(*lptr)(do...
Answered by @sweenish in the comments. The "function signature" has to match. It's actually "pretty straightforward". void(*lptr2)(const double&); // FIXED lptr2 = funcy2; lptr2(5);
63,107,146
63,124,338
How to execute CMD command with CreateProcess
I wanted to execute cmd command like "wmic logicaldisk get name > file.log". I have written the following function but it doesn't work and my program will crash. bool Information::ExecuteConsoleCommand(QString arg_console_command) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); ...
I see tag Qt and parameter's type QString in your question. So, you can use QProcess and QFile, here is example: #include <QProcess> #include <QDebug> #include <QFile> int main(int /*argc*/, char* /*argv*/[]) { QProcess process; process.start("wmic logicaldisk get name"); process.waitForFinished(); a...
63,107,372
63,113,334
How to catch assert() in WM_PAINT handler?
I have MSVC 2019, vc142 x64, SDK 10.0.18362.0, WINAPI game project, JIT debugging is enabled, _DEBUG is defined. I use assert() from standard lib #include <cassert>. assert(expr) call expands to _wassert. If test code assert(false) is placed wherever excluding WM_PAINT handler, a window with Abort/Retry/Ignore options ...
We have to be careful when handling the WM_PAINT message. Windows manager constantly monitors which parts of the screen need to be redrawn and adds this information to window's update region. When the GetMessage or the PeekMessage is called and there is no message with higher priority, the WM_PAINT message is generated...
63,107,447
63,110,283
Passing a variable from MainWindow to new window
In my MainWindow i have a combobox and a select button. When the select button is clicked a new window is opened. I want to be able to create a QString variable on the MainWindow that contains the text from the combobox, and pass that QString to the new window. The new window is going to perform different tasks, based ...
The simplest way to do this is, as suggested in the comments, to pass the variable as parameter in the constructor of the class Testwindow. Then you can save the value of the string in a private variable in your Testwindow class and do whatever you want with it. testwindow.h class Testwindow : public QMainWindow { ...
63,108,010
63,108,157
How do I know what functions to use in C++?
I have the basics of the program, but I am stuck on how to establish the functions of the program and how to call them. I know that there is probably an easier way of doing this, but this is what i know how to do. the program is supposed to call a file called uptime, read out the amount of time the system has been up...
There is a few things wrong with your code. For starters, your three functions: starttime(), work(), and endtime() do not return a value. There is a few things you can do to at least run your program. starttime() needs to say void starttime() instead of having int. So does endtime(). Then in int work() you need to ret...
63,108,083
63,108,290
Why std::fetch_add returns the old value?
What are the design purposes or technical restrictions that make the return value of std::fetch_add is the one before changed?
It's not a big deal either way, you can emulate one in terms of the other. e.g. val.add_fetch(1) can be implemented with 1 + val.add_fetch(1) if you want it. However, GNU C __atomic builtins provide both. Possible reason for ISO C/C++ only providing fetch_add instead of add_fetch: it makes it cheaper to implement on ...