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
62,177,575
62,177,711
Function call inside lamda of thread C++
class Box { int _value; public: Box(int value_):_value(value_) {} int getValue() const {return _value;} }; void setBox(unsigned value, Box& box_) { box_ = value == 1 ? Box(1): Box(2); } int main() { Box box1(0), box2(0); std::vector<std::thread> threadList; for(unsigned value : {1, 2}) { ...
Your code has potential undefined behavior. The capture list [&] captures value as reference too. value is a local variable in the for loop, and will be destroyed when the iteration ends, after that the captured reference becomes dangled. You can change it to capturing value by value. for(unsigned value : {1, 2}) { ...
62,177,667
62,177,937
C++: using iterator to construct a 2D dynamically allocated array
I'm new to C++, and I am trying to create a class with a constructor that allocates a 2D array dynamically. I tried to use for loop with iterators(like: for(auto itr = arr.begin(); itr! = arr.end(); itr++))and found out that I can't use .begin() with pointers. Following is my code: class Myarray { public: Myarray(s...
I am trying to create a class with a constructor that allocates a 2D array dynamically Thing about dynamic 2D arrays is that only their outermost dimension can be dynamic. It appears that you want two dynamic dimensions. That is not possible for 2D array in C++. It also appears that you are not creating a 2D array, b...
62,177,715
62,222,522
Webassemly memory management and pointers
I am using webassembly in order to do some calculation using a standard library. In webassembly we can pass only 32bit integers and 64 bits integers. That means that we can pass pointers to arrays as well. That's how we are able to return strings as an array of characters i.e. example char* EMSCRIPTEN_KEEPALIVE returnS...
WebAssembly memory can grow, but never shrink. delete allows memory to be overwritten, but it remains reserved for future use by your WebAssembly application. when i try to send the pointer, poiting to the first value of the vector back to java script then i get some random garbage instead of the string. JavaScript ...
62,177,743
62,178,580
Why does cannonical implementation of overloading binary arithmatic operator in C++ pass first arguement by value?
According to this cppreference page, passing the first argument of an overloaded binary operator by value somehow optimizes expressions like a + b + c. The relevant code snippet from the linked page is as follows: class X { public: X& operator+=(const X& rhs) // compound assignment (does not need to be a mem...
I don't know whether this had that example-writer in mind, but have some explanation. Consider what happens in this code: X a, b, c; X d = a + b + c; Here, first, a + b is evaluated basically as operator+(operator+(a, b), c). Note that operator+(a, b) is an rvalue, and therefore, lhs can, in the outer application of o...
62,178,090
62,180,308
Console RPG in DEV C++ / Map
Im trying to make a Dev C++ RPG game. Im stuck at the map, its a twodimesnional array with the dimensions measured with how many chars can fit before "breaking" a line. The map prints out just fine, but i want to make the player move with the arrow keys. Heres what ive got so far (doesnt work): #include <iostream> #inc...
I've modify your code and I made it better. If you have anything to ask, leave a comment below. #include <bits/stdc++.h> #include <windows.h> #include <conio.h> #define XSIZE 80 #define YSIZE 20 using namespace std; int c_x=XSIZE/2,c_y=YSIZE/2; //the player will be in the middle of the map int direction=1;//directi...
62,178,285
62,178,762
What happens if a string in a struct is longer or shorter than the p/Invoked signature used?
Case in point, I want to use DEV_BROADCAST_DEVICEINTERFACE_A from C#. However, I'm not sure how to declare the struct since the size of dbcc_name is dependent on dbcc_size (It's officially declared as char dbcc_name[1]). According to this question it seems like I need to add [MarshalAs(UnmanagedType.ByValTStr, SizeCo...
You can't declare completely the structure, what you can do is something like this: [StructLayout(LayoutKind.Sequential)] private struct _DEV_BROADCAST_DEVICEINTERFACE_A { public int dbcc_size; public uint dbcc_devicetype; public uint dbcc_reserved; public Guid dbcc_classguid; public char dbcc_name;...
62,178,338
62,178,447
nested defines with defined parameters c++
Here's a smaller reproducer of my code: #include <vector> #include <iostream> struct mystruct { int a; int param1; int param2; }; #define mycase 5, 5 #define mytest_1(test) \ mystruct{ 1, test }, \ mystruct{ 2, test } #define mytest_2(test) \ mystruct{ 3, test }, \ mystruct{ 4, test } #...
Here's the solution: #define IDENTITY(...) __VA_ARGS__ #define mytest_all(test) \ mytest_1(IDENTITY(test)), \ mytest_2(IDENTITY(test)) But if you could change mytest_1 and 2, a better option would be to make them use a .../__VA_ARGS__ parameter.
62,178,471
62,179,004
Why won't my C++ code compile, getting undefined reference error
For my class assignment, we had to make a C++ program using a class and then compile it. These are the following. Snake.h #ifndef SNAKE_H #define SNAKE_H #include <iostream> using namespace std; // We need to include string since we need to access it #include <string> using std::string; // Our declaration of our cl...
It compiled regularly after I removed the bodies of constructors in the header file. /* Snake.h */ Snake(); Snake(string color, double length, bool venomous);
62,178,475
62,178,628
No matching function for call to default constructor
The related code is listed below.Why the compiler complains "'B::B()' is implicitly deleted because the default definition would be ill-formed"? This is the first question in my mind.I find a hint soon.The compiler says:"no matching function for call to 'A::A()'". My question is that why there should be a matching fun...
The compiler is not able to generate a default constructor for B because the constructor of B needs to call the constructor of A. The constructor of A expects an int and the compiler does not know what value to pass to it. This means you need to declare a constructor of B yourself that takes care of this. You can eithe...
62,178,510
62,180,187
C++ SFINAE for group of methods and decorators
I have a std::variants containing objects with different interfaces. Goal is to call some of the methods if the object in variant has it. I'm trying to make a couple of template decorators and looking for a way to do it with less boilerplate and without macro. Finally my idea looks like: class Good { public: void ...
Could you explain why my approach doesn't work ? Your current approach with using declarations fails, because the class' (View's) body instantiation happens outside of immediate context, which means it cannot result in a soft error that would result in falling back to the IsFit primary template, hence its specializat...
62,178,540
62,178,790
Can't construct from std::initializer_list when privately inheriting from std::array
I'm trying to make a wrapper of std::array to perform boundary checks as suggested by this answer. This is the code I have: template <typename T, size_t N> class Array : private std::array<T, N> { public: using std::array<T, N>::array; T operator[](size_t i) { return this->at(i); } T operator[...
The std::array struct does not implement a constructor which takes an initializer_list. It actually only has an implicitly defined constructor. std::array, per [array.cons], does meet the conditions for aggregate though, so it can be initialized via {1,2,3} for example. The requirements for aggregates specified (from [...
62,179,042
62,179,686
Count the number of digits in a Binary
For this program, I will input a Binary number and it will convert into a decimal number. At the end I wanted to return the number of digits in the Binary number that I had input. For example, 1001 - 4 Binary digits.The output of the digits of Binary number is always 0. Should I use size_type to do it ? #include<iostr...
It looks like you are on the right track for unsigned integers. Signed integers in a multiply are generally converted to positive with a saved result sign. You can save some time with a bit data solution, as value testing is not cost free plus 'and' has no carry delay. Of course, some CPUs can ++ faster than += 1, bu...
62,179,152
62,179,648
Run Wt Framework in Qt Creator
I'm just trying to run an example from https://www.webtoolkit.eu/wt I have downloaded precompiled binaries from https://github.com/emweb/wt/releases I choose "Wt-4.3.1-msvs2017-Windows-x64-SDK.zip" and extracted into a folder. Kit i use: Qt 5.12.0 MSVC 2017 x64 Then i added into my Qt project .pro file next lines: LIBS...
I think you need to specify which libs you need to link with explicitly. Check out: How to add additional libraries to Visual Studio project?
62,179,269
62,182,449
modify the linked list main function code in which user will input the index and data of the node with proper messages
I have a link list in which user will input the index and data of the node with proper messages.... it is a very simple task i know but i am so confuse how to do it . all i want is that you edit my code so that user can enter which index he/she want to enter data and also he/she is able to enter his/her data.. I'll be ...
Don't worry it a very simple task 1:- firstly you should give values in particulate index 2:- ten just fetch it from the particular index for further information you can contact
62,179,305
62,184,001
Question about adjacency matrix implementation
I am having issues with a graph implementation using an adjacency matrix. As a little background, I have to read from a file each line containing an actor, a movie they played in, and the year it was made. My job is to create a graph from the file. The graph would then consist of vertexes of actors whose edge relation ...
First off, you'd need to simplify the vertex identification process. I'd suggest enumerating them by storing them in an unordered map with the actor names as string keys and their corresponding indices as values. That would yield O(1) expected time to access the index of an actor. Then, you could form sets movies which...
62,179,459
62,180,183
How should I get the absolute path of a configuration file to be published alongside a windows .exe?
I'm making a windows application in C++. There's an API which requires a configuration file, and also the absolute path of that configuration file. ( https://github.com/ValveSoftware/openvr/wiki/Action-manifest ). I would have an easier time reasoning about this if I understood expected practices for publishing an exec...
Here's how you can do it on Windows. #include <Windows.h> #include <iostream> int main(){ /*If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).*/ HMODULE selfmodule = GetModuleHandleA(0); char absolutepath[MAX_PATH] = {0}; uint32_t l...
62,179,658
62,179,718
Reserved Names & User Literals
The C++ Standard reserves names beginning with an underscore followed by a capital letter in all scopes. Does this apply to user literal operators? e.g. int _MyInt; // reserved, violation template < char... > auto operator "" _MyInt ( ); // reserved???
No, it allows the use of an underscore followed by a capital letter (which is otherwise a reserved identifier). Source I've only found an example, not a formal paragraph, in the standard supporting the above: [over.literal] double operator""_Bq(long double); // OK: does not use the reserved identifier _­Bq double op...
62,179,683
62,387,448
Canonical implementation of operator+ involves additional move constructor
Motivated by this question, I compared two different versions of an implementation of a binary operator+ in terms of operator+=. Consider we are inside the definition of class X. Version 1 friend X operator+(X lhs, const X& rhs) { lhs += rhs; return lhs; } Version 2 friend X operator+(const X& lhs, const ...
What hinders the elision of that additional move constructor call in the first case? The defect report DR1148 that was accepted and included in C++11. In short, it says (emphasis mine): It is unclear whether copy elision is permitted when returning a parameter of class type. If not, it should still be possible to mo...
62,179,729
62,182,332
basic_thread_pool is not a member of boost::executors
I am changing the version of boost to 1.71 from boost 1.63 and while running against the projects and solutions i see the following error in multiple places. Below is how I have used it: boost::executors::basic_thread_pool threadPool( workingThreadNum ); The error that I see: C2039 'basic_thread_pool': is not ...
These features are experimental and require compiler defines to enable their conditional compilation: #define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION 1 #define BOOST_THREAD_PROVIDES_EXECUTORS #define BOOST_THREAD_USES_MOVE #include <boost/thread/executors/basic_thread_pool.hpp> Of course it's important for these to...
62,179,912
62,179,966
getting segmentation fault string s=s+"A";
CASE 1 If i use string s=s+"A" i get segmentation fault #include <iostream> #include <string> using namespace std; int main() { string s=s+"A"; return 0; } CASE 2 but if i use string s; s=s+"A" it works fine #include <iostream> #include <string> using namespace std; int main() { string s; s=s+"A";...
string s hasn't been initialized here yet: string s=s+"A"; This is why you are getting a segmentation fault. In the second case: string s; // default value "" s = s+ "A"; // you are getting "" + "A"
62,179,977
62,182,250
Filter OpenCV Contours by inside colors
I have a problem with filtering some contours by colors in it. I want to remove all contours, which has black pixels inside and keep only contours with white pixels (see pictures below). Code to create a contours list. I've used a RETR_TREE contour retrieval mode with CHAIN_APPROX_SIMPLE points selection to avoid a lot...
Hopefully, one thing is clear that the objects in the image should be white and the background black when finding contours that you have done by using THRESH_BINARY_INV. So we are essentially trying to find white lines and not black. I am not providing the code as I work in python but I'll list it out how it can be don...
62,180,535
62,181,088
QML/C++/QObject Struct Copy
my Qt/QML program uses classes declared in C++ to structure information in QML and pass it as a bundle to C++ functions. The structs are derived from QObject as required by QML. Example: class ResultStorageOptionsStruct : public QObject { Q_OBJECT public: explicit ResultStorageOptionsStruct(QObject * parent =...
You can serialize and deserialize to a QIODevice, but this would be for file storage. To me, it sounds more like you want a QObject wrapper around a plain C++ object. I would create a C++ class with the data that you need. Then create a QObject derived class with a (weak) reference to the C++ class that you wrap the or...
62,180,555
62,180,693
OpenGL drawing a triangle instead of a square
I am trying to get a square on the screen. This code should draw a square, however it omits the last vertex and only draws a triangle. Where have I gone wrong? #include <glad/gl.h> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include "linmath.h" #include <stdlib.h> #include <stdio.h> static const struct { flo...
You're telling opengl to render 3 vertices instead of 4 with glDrawArrays(GL_POLYGON, 0, 3); Change it to glDrawArrays(GL_POLYGON, 0, 4);
62,180,616
62,180,958
Error C2676 on custom templated operator<<(T x)
I have logger class which encapsulate 2 std::ofstream: class logger { private: std::ofstream one; std::ofstream two; public: logger(); ~logger(); template<typename T> logger & operator<<(T); }; logger::logger() { // open streams } logger::logger() { // close streams } templat...
std::endl is a function template. It's an IO manipulator.. There is an std::endl<char>, std::endl<wchar_t> and an infinite number of other std::endls, one for each possible character type. The compiler has no idea which one of those you could possibly mean. It works with std::basic_ostream because std::basic_ostream ov...
62,180,635
62,180,835
selection sort for array of objects
Iam trying to make selection sort for array of objects considering i have Data class I want to sort them depending on the id attribute of the object class Data { public: string name; int id; }; } int main() { Data m[3]; m[0].id = 5; m[1].id = 4; m[2].id = 8; selsort(m, 3); cout <<...
Change: if ((mry[min].id < mry[j].id) < 0) to: if ((mry[min].id > mry[j].id) ) You are finding the minimum index, so you have to swap if you find an index with a value that is lesser than the current minimum. A better way to accomplish this is to make your function take in another parameter called a comparator functi...
62,180,673
62,180,960
How can I compare std::function objects?
I have a vector of std::function objects defined like this: std::vector<std::function<void()>> funcs = { myFunc1, myFunc2, myFunc3 }; //The functions are defined like this: //void myFunc1() { ... } I am trying to search through this array for a specific function. My first attempt was using the std::find function, like...
As shown here, template member function target accepts type that is compared with a stored object type. In you case it is a pointer to a function. You have to change *iter->target<void()>() == myFunc2 to *iter->target<void(*)()>() == myFunc2 Note that this will only only you to find a plain C function, not an arbitra...
62,180,712
62,181,244
delay in executing widget program
I have a Main window with push buttons to open other windows, as shown below: Here both in Program window and Logs window , I have a back to main button which can take to the Main window. In the Logs window at present I'm having a real-time display of sensor. Everything seems fine if I start Logs from Main in the fir...
I would suggest that you use QStackedWidget. It is good for navigating through different "pages". You can add 5 pages to the stacked widget. when you click on a button and need to change to the respective page you do stackedWidget->setCurrentIndex(indexOfThePage); for example, the function to go back to main menu can ...
62,180,985
62,181,325
Permutations with output limitation in C++
I am trying to do the permutations of 8 characters, but I am only interested in output which contains maximum of 3 same characters. So any output which contains any character in more than 3 occurrences should be skipped. Character set: a, b, c, d, e, f, g, G Example: Not interested in output e.g. aaaaaaab , aabcdeaa, a...
The solution to your problem is pretty simple. What you want to do is to take your character set: a, b, c, d, e, f, g, G and construct a "fake" sequence with each character triplicated. std::string perm{"GGGaaabbbcccdddeeefffggg"}; The key insight here is that you can compute your permutations as usual, e.g., using s...
62,181,427
62,181,649
Coordinates using idenity matrix won't work
Basically i am supplying the vertex shader with an idenify matrix and for some reason it doesn't work. This is my C++ code: glm::mat4 trans; GLuint transformLoc = glGetUniformLocation(program, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans)); I am doing this after glUseProgram(). This...
As of 0.9.9.0 GLM no longer identity-initializes (or anything-initialize!) default-constructed vectors/matrices by default. You can #define GLM_FORCE_CTOR_INIT before #includeing GLM to restore the old behavior.
62,181,555
62,182,992
Bool Vector realization
Can somebody tell me how this vector actually works? Particularly about its operator= and operator bool of VecProxy class and operator[] of main class. I understand that it is needed for reduce the amount of memory used. Like bool is 1 byte and with this class we can reduce it by 7 bits for every element. I guess VecPr...
From Like bool is 1 byte and with this class we can reduce it by 7 bits for every element. We know that you understand that each bit has distinct meaning, each representing a different boolean value, and that these bits are then packed together into a byte to save space. In order to get the boolean value back out a...
62,181,746
62,181,853
Why would you want to overload operators and how can you use its original functionality?
I am having trouble trying to understand why someone would want to overload an operator. I understand it can help reassign functionality, but it takes away key functionalities as well. In an assignment given to me, I was given a skeleton code that Vector4f overloaded =, and now in Matrix4f.h, I can't use = when creati...
Operator overloading is a way of adding some syntactic sugar to help your types have a full, semantically-coherent API. Take, for example, std::string. In terms of pure assignment operators, it provides a number of ways to help the string behave in a coherent and semantically-sound way. In addition to the copy/move ope...
62,181,852
62,181,969
Implicit auto type specifier
I was wondering why it is not possible to omit the auto keyword in some/all cases entirely, e.g. int main() { [](auto x){}(10); // why this? [](x){}(10); // and not this? auto x = 10; x = 10; } Is there a problem with ambiguity or something similiar? Or was it simple a design choice?
Consider this: struct x {}; [](x){}(10); Is that a lambda with an unnamed argument of type x (as per the current language spec) or is it am argument named x of deduced type (as per your suggestion)? Your suggested syntax is ambiguous with the pre-existing syntax of function parameter declarations. x = 10; This ...
62,182,309
62,183,815
How to read complicated C++ type declarations when there is no identifier?
There's the well known spiral and right-left rules etc. for reading complicated C++ types such as int (*(*foo)(char *,double))[9][20]; Foo is a pointer (change direction, move out of parentheses) to a function taking a pointer to char and a double, and returning (change direction again) a pointer to (parentheses again...
The rules for reading complex types assume that the type has already been parsed (and you know where the "innermost" point is). The rules for parsing work from the outside in, the same as reading complex expressions in math class. When you hit parentheses, give it a name and come back to it (unless it's simple enough t...
62,182,500
62,182,667
Why vectors inside two struct have the same address?
For avoid duplicate code, i want to build this generic structure. I want the numbers24 vector inside the scaledown24 struct to be different from the numbers32 vector inside the scaledown32 struct. So when I make a change, they won't be able to influence each other. But when I run the program, the printAddress function ...
There are several problems with your code. Mainly stemming from the fact that both getVector() methods return their vectors by value, and both printAddress() methods take their arguments by value as well. So you are dealing with copies of vectors all over the place. You are seeing memory getting reused in different ...
62,182,762
62,183,062
C++: Extending static STL container/ map member in subclass?
Currently I have code that looks a lot like #include <map> #include <string> #include <functional> void SomeFunc(); void SomeOtherFunc(); struct Calls { std::string name; std::function<void(void)> a, b; }; struct BaseClass { static const std::map<std::string, Calls> callbacks; const std::map<std::s...
You could write a function like auto concat_maps(std::map<std::string, Calls> first, const std::map<std::string, Calls>& second) { first.insert(second.begin(), second.end()); return first; } Which merges one map into another. This allows you to define your derived class maps as a concatenation of the parent c...
62,182,941
62,183,187
Cmake: find_library doesn't work but find_path does (same path)
I am trying to build a cross platform school project in C++ with CMake. My project requires the use of the Irrlicht library and must compile under Linux and Windows 10. The project source path contains a lib folder, containing the Irrlicht header (in an include subfolder), an Irrlicht.dll, an Irrlicht.lib and a FindIrr...
Well, I found my problem. I feel stupid for not thinking about this sooner... The problem was in the pre/suffixes, with some debugging output I realised that they were set for Linux instead of Windows, hence not founding the library file. The reason for that is that in the CMakeLists.txt, the call to find_package was d...
62,183,286
62,183,447
What is the difference between std::ranges::begin and std::begin?
What is the difference between std::begin and the new std::ranges::begin? (same for end, size, etc.) Both seem to work identically: #include <iostream> #include <vector> #include <array> #include <ranges> template<std::ranges::range R> void printInfo(const R &range) { std::cout << (std::ranges::begin(range) == std...
There are a few differences. First, ranges::begin(x) works on all ranges while std::begin(x) does not. The latter will not do ADL lookup on begin, so ranges specified like: struct R { ... }; auto begin(R const&); auto end(R const&); won't work, which is why you have to write something like: using std::begin, std::...
62,183,356
62,183,740
Unpack C-style array along with parameter pack in C++
My question is somewhat similar to this one: I'm using C++14 and I'm trying to "unpack" a C-style array and call a function with its content. The difference is, I need to do that in a variadic function template and pass each element of the array into something that depends on the type parameter pack. Here is the simpli...
Here's a solution that creates a compile time integer sequence that you can use to index args: template<typename ...T, size_t ...I> void myfunction_impl(void(*f)(T...), char const* args[], std::index_sequence<I...>) { f(Converter<T>::convert(args[I])...); } template<typename ... T, size_t N> void myfunction(void(...
62,183,418
62,191,548
OpenCV ArUco markers, how to get the center of them?
I'm using ArUco markers and I'd like to get the coordinates of the center of a marquer. This method detectMarkers() followed by the drawDetectedMarkers() draws the Id of the marker. It looks like the bottom left pixel of the word "Id" is placed in the center. How can I get the coordinates so I can print them on my fram...
Since you already have the 4 vertices, the center is simply their mean (as you can see also in the OpenCV implementation for drawDetectedMarkers) Point2f cent(0, 0); for(int p = 0; p < 4; p++) cent += currentMarker.ptr< Point2f >(0)[p]; cent = cent / 4.; So your code should look like (see also the tutorial): cv::M...
62,184,125
62,184,193
Calling member function in transform()
So I've been trying to use the transform function to create a vector from 2 existing ones. I succesfully managed to do it without classes but now I want to use classes and I get errors. The code bellow is only a small, relevant part of my project so it might seem silly but the whole thing actually makes sense in the en...
The simplest way to approach this problem would be with the use of lambdas: transform( timeVec.begin(), timeVec.end(), aVec.begin(), ampVec.begin(), [this](double a, double b) { return multiply(a, b); } ); You can't use a pointer-to-member-function here because you need the this pointer upon which to i...
62,184,191
62,184,533
Class's static struct pointer declaration in C++
Given the following snippet: /* trie.h file */ using namespace std; #include <list> typedef struct tn { char ch; list<struct tn*> ptrs; } TrieNode; class Trie { public: static const TrieNode* EMPTY; //... other member functions }; /* trie.cpp file */ #include "trie.h" // decla...
You can't put statements like Trie::EMPTY->ch = '.'; and Trie::EMPTY->ptrs = nullptr; in global scope, they can only be executed inside of functions, constructors, etc. Try something more like this instead: /* trie.h file */ #include <list> struct TrieNode { char ch; std::list<TrieNode*> ptrs; }; class Trie ...
62,184,221
62,184,555
Initialization of std::atomic before and after C++20
Consider the following two lines of code: std::atomic_flag a { }; // Since C++20 std::atomic_flag a = ATOMIC_FLAG_INIT; // Until C++20 In C++20, the first line initializes a to the clear state, but if I use that in C++17, a will be initialized to an unspecified state. The second line is deprecated in C+...
Based on @chris comment, I think the following code will do the job: #if __has_cpp_attribute(__cpp_lib_atomic_value_initialization) std::atomic_flag a { }; #else std::atomic_flag a = ATOMIC_FLAG_INIT; #endif The required macros are defined in either one of <memory>, <atomic>, and <version> header files. I certainly do...
62,184,557
62,184,575
Do i need to free allocated memory from local pointers in c++?
void f() { int *ptr = new int; // is the following line necessary? delete ptr; } int main() { f(); return 0; } Do i have to free the allocated memory in the function f or is it freed automatically because there is no reference to that memory anymore?
Do i need to free allocated memory from local pointers in c++? If you want to avoid memory leaks - and you should want to - then you should dellacate everything that you allocate. There should be one delete for each allocating new. or is it freed automatically Dynamic allocations are not freed automatically. becau...
62,184,841
62,184,852
Search for and replace a value in a vector of structs
I am trying to compare a string to a struct element in a vector of structs and, if the values match, replace value in the struct element with a new value. I am able to populate the vector fine but I'm having issues getting the search and replace to work. struct info { string name; string phone; string addre...
To change the elements in the vector, you need to take a reference in the range-for loop: for (auto &e : data) Otherwise you are making a copy, which doesn't change the original elements. The 4th parameter of replace_if needs to take an info object, not just the new_name value. Instead of replace_if, the appropriate a...
62,185,058
62,185,283
Why isn't "this" known at compile time in a consteval constructor?
I'm writing a class to wrap around part of a C-based library that works with devices, where each device is configured with a callback function poiner for handling data. An instance of MyClass would be made for each device. See below: struct DeviceConfig { void (*callback)(char *data); }; class MyClass { private: ...
Constructors are functions, just like any other. They have very few special privileges compared to other functions, and the constant expression behavior of their parameters is not one of them. this is essentially a parameter to all non-static member functions. Parameters are never constant expressions. Therefore, this ...
62,185,138
62,185,154
Is it needed to put function declarations in header files and their definitions in a source files?
Is it needed to put function declarations in header files and their definitions in a source files? Is there any performance gain, or possibly any advantage to doing this instead of putting the declarations and definitions in the same file? Example: In Person.h class Person() { public: void sayHi(); } and in Person...
If you put the definition in the .cpp file, then you can change the definition without having to recompile all the other .cpp files as well. If it's in the header, then every .cpp file that includes the header will also need to be recompiled to have the new definition. The runtime performance will be exactly the same. ...
62,185,360
62,185,669
Attemptimg to use a predicate function causes the error: 'std::sort' no matching overloaded function found
I'm attempting to use the std::sort() algorithm with a custom predicate, but I'm getting a compiler error. I'm using Visual Studio 2019 with C++17 and the v142 toolset. I'm copying the exact code from the Microsoft Documentation example. The code is below: Predicate Function: bool UDgreater ( int elem1, int elem2 ) { ...
Change UDgreater as below: struct { bool operator()(int a, int b) const { return a > b; } } UDgreater;
62,185,373
62,193,329
In practice, why would different compilers compute different values of int x = ++i + ++i;?
Consider this code: int i = 1; int x = ++i + ++i; We have some guesses for what a compiler might do for this code, assuming it compiles. both ++i return 2, resulting in x=4. one ++i returns 2 and the other returns 3, resulting in x=5. both ++i return 3, resulting in x=6. To me, the second seems most likely. One of t...
The compiler takes your code, splits it into very simple instructions, and then recombines and arranges them in a way that it thinks optimal. The code int i = 1; int x = ++i + ++i; consists of the following instructions: 1. store 1 in i 2. read i as tmp1 3. add 1 to tmp1 4. store tmp1 in i 5. read i as tmp2 6. read i ...
62,185,515
62,185,534
Pre increment vs post increment inside if check C++
int main() { int a = 0; if(a++ == a){ std::cout << "A" << std::endl; } int b = 0; if(++b == b){ std::cout << "B" << std::endl; } } Output: B I was expecting the result to be A since my assumption was that value of a wiil be used before a is incremented since it is post-incremen...
Both your if conditions have undefined behavior, since you are modifying and accessing a variable in the same expression. The program could print A, B, AB, nothing, or the program could crash your computer. Absolutely anything can happen when your program has undefined behavior. Make it a habit to compile programs with...
62,185,958
62,186,215
How to declare a variable for high resolution clock in C++?
In the example here: https://en.cppreference.com/w/cpp/chrono/high_resolution_clock/now They declared the clock time point with auto. auto start = std::chrono::high_resolution_clock::now(); and the doc says it returns 'A time point representing the current time.' But I am not sure how do declare in my code below becau...
std::chrono::high_resolution_clock::time_point orderRecvedTime; In practice, high_resolution_clock is a type alias for either system_clock or steady_clock, so my advice is to choose either one of those instead for a portable experience. system_clock is like a watch. It can tell you what time it is. steady_clock is l...
62,186,051
62,206,528
CTest project directory. No tests were found
Here is my project hierarchy ProjectMain | Project 1 | | | tests | Project 2 | tests CMakeLists of ProjectMain downloads and sets up google test as per https://github.com/google/googletest/blob/master/googletest/README.md ...
I needed to enable_testing() in ProjectMain's CMakeLists.txt
62,186,136
62,218,230
QTabWidget round corners for frame (not tabs)
How can i make QTabWidget's corners rounded? Not Tab's, but frame's (?) I tried: QTabWidget{ border-radius: 7px; } But it isn't working. QSS for tabs: QTabBar::tab { background-color: qlineargradient(x1:0.5, y1:1, x2:0.5, y2:0, stop:0 rgb(253,250,250), stop:0.2 rgb(253,250,250), stop:1 rgb(255,249,234)); border-top-...
Just tested this (black color and thick frame just to see something) and should thus work: QTabWidget::pane {border: 3px solid black; border-radius: 7px;}
62,186,209
62,237,541
Calculate FPS with sfml
This question is NOT related to the main loop in sfml. How do I calculate the actual framerate (for example, I have vsync enabled, but the main loop still runs at a high speed), so that it actually displays how fast the screen is updated (not the speed of the main loop). Measuring main loop speed is not important for m...
SFML did not provide a way to retrieve your current framerate, neither backends like OpenGL does. Therefore, the only way is to monitor the main loop speed, as you suggested. Also, window.setFrameLimit(60) or window.setVerticalSyncEnabled(true) or internal loop sleep on a 60Hz monitor causes the same effect in my SFML ...
62,186,261
62,186,317
Why is std::string s = "123" considered copy-initialisation when no copy is involved?
Why is this way of initialisating a std::string: std::string s = "123"; considered a copy initialisation, when no copy whatsoever actually occurs? In the above case, there is no ambiguity that the compiler will see that there is a std::string constructor that takes a char const *, and consequently what happens here is ...
The term copy-initialization is simply used for an initializing syntax of the form: T object = other; where one of the effects of this initialization is: If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T, or if T is non-class type, but the type of other is a class ty...
62,187,633
62,187,674
Constructor implicitly deleted
The related code is listed below, you could check it on https://godbolt.org/z/3GH8zD. I could solve the complier compile error indeed.But i am not completely clear about the reason lie behind it.I would be grateful to have some help with this question. struct A { int x; A(int x = 1): x(x) {} // user-defined def...
The class member int& ref needs to be bound to an int when an object of type F is created. A compiler-generated default constructor would not know how to bind it, so the compiler merely deletes the default constructor. In the second snippet you explicitly set the member. (You can do that from C++11).
62,188,510
62,189,459
How to get hints from a int c++
How do we do to get a hint from a int , for example : #define A 0x1 #define B 0x2 int hint = A | B; How to check what hint is used ?
First of all, don't define constants as pre-processor #defines. Prefer real constants, like enums. If the constants are going to be used in bitfields, it also helps to write them out as binary literals using the 0b suffix: enum { A = 0b001, // 0x1 B = 0b010, // 0x2 BA = 0b011, // 0x3 C = 0b100, /...
62,188,513
62,188,744
how can i test void method using google test framework
example: I have a void method which just prints the elements of an array. #include <stdio.h> void PrintNumbers(); int arr[10]; int main(){ int i; int value = 0; for(i = 0 ; i<10; i++) arr[i] = value++; PrintNumbers(); return 0; } PrintNumbers(){ ...
To have the method tested properly in this case, I'd inject the stream to the method: void PrintNumbers(std::ostream& os = std::cout) { int a = 42; os << "Expected " << a; } TEST(PrintNumbersTest, TestWithStringStream) { std::stringstream myStream; PrintNumbers(myStream); ASSERT_EQ("Expected 42", ...
62,188,745
62,188,873
Best algorithm for print all children's for tree element?
I want to create a tree using smart pointers. The result is this structure: struct TreeElement { int data; std::shared_ptr<TreeElement> parent; std::list<std::weak_ptr<TreeElement>> childrens; } Now I want to display all the children for a specific item. How to do it better? Using which algorithm? Example:...
There are exactly 3 ways to visit/print a (sub)tree: in-order, pre-order, post-order. The precise 'best' algorithm depends on the problem domain. In your case, it looks like you want in-order printing, which would be implemented by void PrintAllChildrens(TreeElement element) { // Print current level std::cout <...
62,188,794
62,189,351
Conversion from _Ty to int warning in MSVC accumulate
I cranked up MSVC warnings to level 4 and have a problem using accumulate over boost::circular_buffer. This code: boost::circular_buffer<unsigned short> shorts; shorts.resize(10); unsigned short res = std::accumulate(shorts.begin(), shorts.end(), static_cast<unsigned short>(0)); Fail with a possible loss of data warni...
25.9.2 Accumulate [accumulate] defines effect of std::accumulate as acc = std::move(acc) + *i. Since C++ for some reason does not support arithmetic operations on integer types smaller than int and instead promotes arguments on both sides of + into int prior to summing, result will be an int. Therefore you are getting ...
62,188,983
62,189,185
How to declare a class already defined in static library?
I am linking a static library, which encapsulate implementation of class A. class A { private: B* _hal; int id; public: A(); bool Open(); } This class and it's .cpp are compiled to .o which are later part of the generated static library libTony.a. The constructor initializes id...
Defining A as a full class in the lib, but then hiding methods within it via the header file is going to lead to undefined behavior if you are not careful. Let's do this right with interfaces. class A inherits from InterfaceA. Put this in libTony.h #pragma once class InterfaceA { public virtual bool Open() = 0; ...
62,189,501
62,192,120
please spot the error its working in dev but not in hackerrank
code is not working in hackerrank but working in dev c++?? the output value is 1047095560 some number like this ive tried other ways to solve code and its working but this approach is not working. some of the test cases are 10 3 1 5 3 4 8 7 6 9 1 ans 10 second test case 5 3 1 2 100 2 5 100 3 4 100 ans 200 #include <ios...
Apart from a typo in your very first line (a semi-colon after include directive) and using non-standard VLAs, the main bug was your third loop which was resulting in a garbage value. You should change the check statement from i < n to i < n - 1. Here is a more portable and compact version, which shall support all compi...
62,190,287
62,190,379
How I can solve C++ output negative numbers when using modulo?
In a code written by me, I have used both below functions to calculate mod of displayed negative number. fmod(-10,11) (-10, 11) Though the correct answer is 1. It always displays the answer -10 in c++. How I can solve it?
From cppreference.com: double fmod (double numer, double denom); The floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where n is x/y with its fractional part truncated. The returned value has the same sign as x and is less than y in magnitude. In you...
62,190,525
62,190,912
What maximal integer, capable of adding 1 a float type can hold in c++?
Suppose I am using float to hold integer values and adding small shifts to it, approximately 1s or 2s. At which value float will stop to change? What is the name of this value?
The smallest positive value of an IEEE 754 floating-point variable a where you get a == a+1 is 2^bits_precision, where bits_precision is one more than the number of bits in the significand and can be found with std::numeric_limits<T>::digits. For a 32-bit float, that's 24; for a 64-bit double, that's 53 (again, in the ...
62,190,760
62,190,973
Compiling Issue with Inner class reference
Good morning everybody, I'm trying to write a member function of a class OUTER_CLASS which returns a unique_ptr to a private class INNER_CLASS defined within the OUTER_CLASS itself. My intent is to write a factory method which returns a reference to an Interface Class which allows to interact with the Implementation Cl...
Accessibility applies on name, not the type being referred to. So you just can't use the name OuterClass::InnerClass directly in main(), but you can still use the type like calling member functions on the returned object whose type is OuterClass::InnerClass like obj.CreateInnerClass()->myPrint(); Given auto innerObj =...
62,192,953
62,193,073
Is it safe to return a static string_view created from a string literal?
I have a relatively simple use case: I want to associate a trait to a class which will return some user defined string, namely some user-defined registration ID. As this registrations are supposed to be defined at compile-time I would like it to be constexpr so I wrote something like the following: template <typename T...
string literals are guaranteed to have the lifetime as long as that of the program itself That's correct. Therefore, is this usage of string_view safe and appropriate? Yes, your code is fine.
62,193,134
62,193,906
compiler error when trying to show text using winbgi
I have a string that I want to show on the winbgi window using outtextxy. The problem is outtextxy only takes the pointer of a char array which shows a compiler error. Here is the code for(int i=0;i<13;i++){ setcolor(RED); circle(otab[i].x1,otab[i].y1,otab[i].radius); string txt="obs"; t...
if string is a std::string, use txt.c_str() https://www.cplusplus.com/reference/string/string/c_str/
62,193,206
62,229,216
Mingw32 failing to statically link to libgcc_s_dw2-1, libstdc++-6, libwinpthread-1 (Qt 5.7.1)
I am struggling with a problem of statically linking with libgcc_s_dw2-1, libstdc++-6, libwinpthread-1 libraries when compiling with mingw32. Setting up a project with -static-libgcc -static-libstdc++ -static -lwinpthread flags helps in case if I build a standalone application. But when I use Qt 5.7.1 for mingw32 comp...
If your build and it's dependancies aren't static, those DLLs need to be distributed with your application. The article at https://lwn.net/Articles/549573/ explains the libstdc++-6 DLL can be distributed without licensing issues.
62,193,274
62,195,562
Reading a serialized struct at the receiver end boost asio
I am new to boost and networking ;). I am making a client server application with boost::asio, I need to pass structs as messages so used boost::asio::serialization for it : test.h #pragma once #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/serialization.hpp> struct Test { public: ...
You don't show enough code to know how you declared buf or managed the lifetime. I'm assuming you used boost::asio::streambuf buf; and it has static storage duration (namespace scope) or is a class member (but you didn't show a class). Either way, whatever you have you can do "the same" in reverse to receive. Here's a ...
62,193,821
62,194,039
Why is one algorithm faster than another with the same time complexity?
I was working on a codingame challenge : the horse racing dual. The goal is to find the minimum difference between two elements of a list. I started with this first algorithm, which is i think in O(nlog(n)) but the execution was timing out for large arrays. int array[N]; int min = numeric_limits<int>::max(); for (int ...
Am I wrong with the first code complexity? Yes, you are wrong, this complexity is not O(n log n), but O(n^2) instead. The outer loop runs n (N) times while the inner loop runs n/2 times in average. Thus, the complexity is O(n * n/2) which is O(n^2), since multiplicative constants doesn't matter in complexity calcula...
62,194,152
62,194,270
next_permutation not by reference?
I do not understand why inside the loop, the position of the values are changed. But outside do, while loop, all the values return to the original positions. Thus i need the //here code. I also tried a pointer array, but it showed the same behavior. Why so? #include <iostream> #include <algorithm> using namespace std;...
Thats how next_permutation is defined. The last permutation (the one that returns false) is the one that puts the elements in sorted order. I suppose there is another misunderstanding. Here: do { print_permutation(); } while (next_permutation(a, a + 3)); The last permutation you print inside the loop is that one ...
62,194,226
62,194,335
C++ on Arduino - General Questions
If I call a function do I need to delete all variables used in it at the end or is that done automatically. How to compare a String to "" and which object can I use instead of a string with is as easy as a string but not so big? Is it possible to run C Python on Arduino or would this be just a waste of already limited...
If you don't use new you don't need to delete a char array[] ( or a pointer to text in mem. ) Use strcmp to compare texts, if you need to. no.
62,194,484
62,194,552
Can't use std::cin with char* or char[] in C++20
It used to work: Reading from std::cin to a dynamically allocated char array - or to an array passed in as a parameter (see MCVE below). #include <iostream> void read (char str[256]) //or omit the # between the []'s -- no difference { std::cin >> str; //error } int main () { char s1 [256]; char* s2 = new...
But how do I use cin with arrays passed in as parameters, or dynamic arrays? Don't. If you have a char array, give it the char array like void read (char (&str)[256]) // now we have a reference to an array, so we know its size { std::cin >> str; } // or if we don't care about the size, we just want an array te...
62,194,900
62,195,478
Linked List Print() Function Printing Ascii number of Char
I creating type linked list and taking chars from the user. This is the class definition. template <class nodeT> struct nodeSLL { int data; //Data inside the node nodeSLL* link; //Address next node }; char itemC; ...
Instead of int data; You should templatize nodeSLL by changing it to nodeT data; If not, whether passing int or char or any other datatype still results in printing int. If not, passing the template won't affect the struct nodeSLL at all.
62,195,035
62,195,125
How to erase last comma when writing to a file
I'm using the following snippet to write values to a .txt file: fstream f1; f1.open("output.txt", ios::out); { for (const auto& avg : clusAvg) { f1 << avg << ","; } } f1.close(); This generates a list that looks like: 20,30,40,50, My question is, how can I eliminate that last comma in the list?
Try doing this fstream f1; f1.open("output.txt", ios::out); { bool first = true; for (const auto& avg : clusAvg) { if(!first) f1 << ", "; first = false; f1 << avg; } } f1.close();
62,195,231
62,195,903
how to select a specific file from a directory iterator and compare it
I have two directory iterators that take from the user two input of paths and print their entries name and size. What I want is to make the user enter a number of index and then the program will take that index's file from both of the directories and compare their size to see if they match each other or not. The code i...
If I understand your question correctly, you're looking for something like this std::vector<std::filesystem::directory_entry> v1, v2; size_t i; for (auto& p : std::recursive_directory_iterator(str1)) v1.push_back(p); for (auto& p : std::recursive_directory_iterator(str2)) v2.push_back(p); std::cin >> i; // ge...
62,195,566
62,196,086
My second last value is garbage,the program is about calculating sum
#include <iostream> using namespace std; int main() { int oldsize; string choice; cout << "Welcome to the Walmart Calculation Center!"; cout << endl; cout << "Enter the Number of Items" << endl; cin >> oldsize; int* items = new int[oldsize]; for (int i = 0; ...
You never change items array, but you change oldsize variable which represents it's size. When you the try to copy items from items to Nitems, you go out of bounds of items array (because oldsize is bigger that actual size of array). The simplest fix would be to repoint items to Nitems at the same moment when you chang...
62,195,701
62,196,667
What is wrong with this code as the answer to the following online judge problem?
The problem states that given the radius of three circles, and assuming that three circles touch themselves in a way shown: we need to find out the area of the blue portion between them. I have written the following code and run a few test cases. All of them worked fine. The online judge says the answer is wrong. #inc...
Look closely at the formulas: r1area = 0.5*(r1*r1)*(asin((2*tarea)/((r1+r2)*(r1+r3)))); r2area = 0.5*(r2*r2)*(asin((2*tarea)/((r2+r3)*(r1+r3)))); r3area = 0.5*(r3*r3)*(asin((2*tarea)/((r1+r2)*(r2+r3)))); res = tarea - (r1area + r2area + r3area); Without entering into the details of the maths I know that they cannot be...
62,196,021
62,199,681
Fill struct with a binary file
I want to fill the following struct: struct Data{ char id; // 1 byte char date[7]; // 7 bytes short int Ny; // 2 bytes short int Nx; short int L; unsigned char distance; short int N; std::vector<short int> quant_levels; std::vector<std::vector<unsigned char>> Pixels; }; Based on th...
Solution 1 (portable) Read the header into a byte vector and convert each value one-by-one. For example: // read the header std::vector<unsigned char> vec(26); fh.read((char*)&vec.data(), vec.size()); data.Ny = vec[18] | (vec[19] << 8); data.Nx = vec[20] | (vec[21] << 8); data.L = vec[22]; data.distance = vec[23] | (v...
62,196,135
62,196,872
Call up variables with inputs, does that works in C++?
I am a hobby programmer. I'm asking for help, because I'm wondering if you can call a variable which is equivalent to the input without the code snippet looking like that: std::string exampleVariable = "Hello"; std::string exampleInput; std::cin >> exampleInput; if(exampleInput == "exampleVariable") std::cout <...
In C++, you'd use a std::map<std::string, std::string> for that. This is a key-value map, where both are strings. E.g. std::map<std::string, std::string> variables; variables["Hi"] = "Hello"; std::string exampleInput; std::cin >> exampleInput; std::cout << variable[exampleInput]; It's safe to use a key that's not yet ...
62,196,429
62,196,691
Why is casting on shared_ptr like this?
I have seen one of the old posts on the topic. Due to my new account and lack of reputation points, I cannot comment there; hence, I am making this post. I was looking in the past for a way to cast shared pointers from one type to another (from base to derived) in order to access some private members on the derived-sid...
The point is that a cast to a non-pointer/reference type is always a conversion in C++. You get the converted value which is distinct from the original value. It is a new local object with its own place in memory. Consequently, any change to this copy will not affect the original value at all. In the case of classes A ...
62,196,604
62,196,898
the object has type qualifiers that are not compatible with the member function using vector
The example generates the error the object has type qualifiers that are not compatible with the member function and I can't figure out why. A.h class A { public: void f2(XXX* ..) const; protected: const vector<XYZ> f(){return m;} vector<XYZ> m; } A.cpp void A::f2(XXX* ..) const { const vector<XYZ>& P= th...
You can't call a non-const function from a const function. This means that f needs to be const qualified as well: const std::vector<XYZ> f() const { return m; } otherwise you can't call it from f2.
62,196,824
62,199,100
Sprite Image getting clipped/cropped in SFML window
I'm using this book called "Beginning C++ game programming" to learn, well, game programming. The following is a snippet from the book which display the background of the first game in an SFML window. (Apologies for my use of namespace I'm just following the book). #include <SFML/Graphics.hpp> using namespace sf; int...
Your laptop doesn't have a 1980x1080 resolution. Set the available resolution. Then change the view to fit the whole picture: Vector2f textureSize(1980, 1080); // or texture.getSize() VideoMode videomode(1980, 1080); if (!videomode.isValid()) { videomode = VideoMode::getDesktopMode(); } RenderWindow window(videomo...
62,196,830
62,197,963
Can I programmatically log what's sent/received to a USB/COM using a win32 HANDLE
I'm playing with a TEC-Microsystem device (DX5100), it provides a C++ dll with an API to open connection: HANDLE OpenSerialPort(char *PortName, DWORD SupporedBaud); For debugging pruprose, I'd like to trace every data being sent/received to the port (a kind of "sniffer" working within the same process). As I have acces...
As @Some programmer dude says, there is no guarantee that this is a valid Windows handle, but even if so, your options are limited: You would need a kernel mode driver to spy on i/o to the handle You would need to patch reading/writing functions to the handle using a library such as Detours or mhook. The latter appr...
62,197,008
62,197,337
Unable to clone a JSON Array properly using C++ Poco library
I would like to clone json objects. In order to do the job, I've developped two functions. One for objects and one for arrays. The method that's clone JSON::Object::Ptr works well. Here is the code Poco::JSON::Object::Ptr CJsonHelper::cloneJson(Poco::JSON::Object::Ptr obj) { Poco::JSON::Object::Iterator it; Po...
I've finally found my mistake ! I've missed a * to go through the auto iterator copy->add(item); becomes copy->add(*item); I post the updated function if it can help someone Poco::JSON::Array::Ptr CJsonHelper::cloneJson(Poco::JSON::Array::Ptr obj) { Poco::JSON::Array::Ptr copy = new Poco::JSON::Array; // loo...
62,198,304
62,222,360
Select member type of class template based on template type?
I have a class template that has members of some type. This type is determined based on the type that is provided when instantiating the template. It uses a default (double in the example below) unless an override is provided by that class. Classes used as template types may provide this override type (here "Two" provi...
I don't want the compiler to complain that "type" is not available here (because it should default to double anyhow since the class instructs not to use the override). But compiler does generate error. How to avoid this? Just defer the access to ::type with the below type_identity helper: template <typename T> struct...
62,198,788
62,200,220
confusing define directive in c++ project
I am trying to figure out what this bit of code I encountered does but can't quite seem to understand how it works. #define CODEC_BIND(classname, type) codec_creator cc_##classname##_##type ((type), new classname()); The codec_creator is a class that assigns a specific codec to an unordered map in the constructor as s...
The macro expands into a variable declaration (when used properly), probably used to create global variables. The variable type is codec_creator, the name is based off of the specific classname (an unsigned short number) and type values passed to the macro using the ## preprocessor operator. The variable's constructor ...
62,198,799
62,286,340
Structured binding initializer form { assignment-expression } fails for array type on clang
[dcl.dcl]/1 (final C++17 draft, N4659) describe the grammar of a simple-declaration as: [...] simple-declaration: - [...] - attribute-specifier-seq(opt) decl-specifier-seq ref-qualifier(opt) [ identifier-list ] initializer; [dcl.dcl]/8 describes that the latter form of a simple-declaration is a structured binding...
This is a known bug, with an open bug report LLVM open bug report: Bug 32466 - Clang doesn't support structured binding of initializer form {" expr }" for array Ryou Ezoe 2017-03-30 00:24:07 PDT: Clang doesn't support structured binding of initializer form {" expr }" if expr is id-expression of array object. Cl...
62,198,823
62,199,317
How to do a program execution check
I have to execute following codes upon pressing a push button: void stageProgram::on_pushButton_programKeyGrip_clicked() { ManageConfigFile configFile; //---> line 1 configFile.keyGripTest(pLabel); //---> line 2 tetra_grip_api::set_sensor_data_rate(SENSOR_ADDRESS_BROADCAST, 0); //--->line 3 disconnect(&ap...
is kind of hard to defined when a line is "executed successfully", because for that you need unit tests or at elast some bool checks... you can for example make the app stop if some criteria is not fulfilled by just using Assertions... like: int divide(int a, int b) { Q_ASSERT_X(b != 0, "divide", "division by zero"...
62,198,832
62,199,001
Understanding a reimplementation of std::is_base_of
I came across the following piece of code online. It's essentially meant to illustrate a way to implement std::is_base_of (perhaps not precisely). I added numbered comments to associate lines with particular questions asked below: #include <type_traits> #include <iostream> class Q {}; class Z : public Q {}; template...
It seems to me that IsDerivedFromHelper defines two static members of the same name (Test)? How is this possible? Those member functions with the same name have different parameter lists. This is called function overloading. The classes No and Yes both define no constructor, meaning they only have the default no-...
62,199,060
62,199,061
Can I initialize an object's C style function pointer at compile time so that it calls the object's member function?
I'm writing a class to wrap around a library that requires callback function pointers. See below: struct LibraryConfig { // Omitting other members... void (*callback)(const char *); }; class MyClass { private: LibraryConfig m_config; public: MyClass(const LibraryConfig &config) { // Initialize...
Yes, this is apparently possible. See the below snippet: struct LibraryConfig { void (*callback)(const char *); }; class MyClass { private: LibraryConfig config; public: consteval MyClass(const LibraryConfig& cfg) : config(cfg) {} void myCallback(const char *data); }; int main() { consti...
62,199,485
62,281,596
Using a c++ dll within a c# project
I am hoping someone can help me. i have a dll file called LC4_Comm_Lib.dll which allows communication to a device, however im trying to use it in a c# project. Honestly i am unaware if this will work at all, the dll file came with a h file /* ========================================================================...
you can use C++ DLL in C# code without using your .h file. First of all you have to do DLL import. Here i am creating a class MFCdllConnector to do the operation. class MFCdllConnector { [DllImport( "LC4_Comm_Lib.dll", CallingConvention = CallingConvention.Cdecl ) ] public static extern <your exporting funct...
62,199,603
62,199,813
About time complexity of this recurrence relation after memoizing it
I solved a question on LeetCode.com with some online help: There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. Return the minimum cost to fly every person to a city such that exactly N peo...
As a rule of thumb that you can almost always rely on, the time complexity of a DP is O(size of DP Table * O(transition)). This is because you can assume getting the memory for your DP Table is time itself, not to mention the fact that you, in most cases, would have the possibility to visit all of those states. For mos...
62,199,663
62,200,591
error: non-aggregate type vector<int> cannot be inititalised with an initialiser list
I am writing C++ code in vs code on my Macbook. While using the C++ standard template library, i am writing the code #include<iostream> #include<vector> using namespace std; int main() { vector<int> array={1,3,4}; for(int x:array) cout<<x<<" "; return 0; } This code, on compilation gives the error that...
But when i write this same code as: The other version is not really the same code. Your problem is with std::vector initializer list, probably arising from wrong compilation flags passed to your compiler. If you're using mac, try to download and install clang, then compile and run it. If it dosen't work then re-post....
62,200,443
62,200,475
Using unnecessary hexadecimal notation?
Whilst reading Apple's dlfcn.h header I can across these macros: #define RTLD_LAZY 0x1 #define RTLD_NOW 0x2 #define RTLD_LOCAL 0x4 #define RTLD_GLOBAL 0x8 Is there any reason why the author of this header wrote these as hexadecimal numbers when the prefixing 0x could be removed safely? 0x1, 0x2 e...
It's conventional to use hexadecimal rather than decimal for powers-of-2 sequences, because it scales legibly. Sure, there are only four options here, but consider a possible extension: 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 // ... While the equivalent sequence rendered in decimal notation will be instantly familiar ...
62,200,566
62,200,602
how can i pass template class which take parameter pack to other template class as a parameter?
I have something like that: template<int ... args> class X{}; and want to pass that class as parameters to 2nd template class. Now I have: template<class X<int... args1> el1, class X<int... args2> el2> class Y{}; Compiler is throwing errors Pack expansion does not contain any unexpanded parameter packsto me and i do...
You appear to be looking for template template parameters, which have the following syntax: template<template <int... args1> typename el1, template <int... args2> typename el2> class Y{}; Note that pre-c++17, you have to use the keyword class instead of typename here.
62,200,609
62,200,903
How is fstream / ifstream / ofstream objects convert to bool
I want to know, how these objects convert to bool. I mean what the compiler relies on when casting. On bit flags? As I think it works like that: the compiler checks the flags and if !goodbit then returns false else true. For example: #include <iostream> #include <fstream> int main() { std::ifstream file("someDir.t...
The compiler uses the operator bool to convert the stream to a boolean. In the documentation you can read that std::basic_ios<CharT,Traits>::operator bool Checks whether the stream has no errors. 1) Returns a null pointer if fail() returns true, otherwise returns a non-null pointer. This pointer is implicitly converti...
62,200,680
62,200,814
how to make user enter the path of the xml file in tinyxml2
How i can make the user enter the path of the xml file to be saved? I want the user to enter something like "c:\test.xml" and the xml file is generated by that name and location. I tried string PathName; cin >> PathName; XMLDocument doc; doc.SaveFile(PathName); but it gives me the error no instance of overloaded fu...
I think your error is telling the parameter type doesn't match an overload. Try this instead: auto result = doc.SaveFile(PathName.c_str()); Edited to include result from the function - if it fails it should give you an error code. Quoting the docs: Save the XML file to disk. Returns XML_SUCCESS (0) on success, or an ...
62,201,077
62,202,350
C++ function resolving base class pointer to derived class pointer
I tried implement something similar to JSON with pointers as a part of an exam question, and I ended up with an error that I didn't know how to solve. I had these classes (leaving out the implementation, because I don't think it is important for my error): struct JSON_BaseObject; template<typename J_Type> struct JSON_...
After trying out the visitor pattern I realized that it solves all my problems. It also resolves the base pointers in an easy way. It enabled a nice code like this: int main() { JSON_Object obj = JSON_Object(); JSON_String str = JSON_String("I am a string!"); std::vector<JSON_Base*> basePtrs { ...
62,201,467
62,204,097
Can we use maps for searching instead of binary search?
Maps give O(1) look-up. Can't we go through the array once and build a map corresponding to its index (the opposite of array) and when we want to search something we can call map[VALUE] and it will return the index. It might not work for large values in array but assuming a[i]<10^5, can't we do this instead of binary s...
A hash table, like a Python dictionary, will give amortized constant average cost per look up. For large data sets this may become an interesting alternative to binary search. Some algorithms may absolutely need a binary search for the following reason: When the lookup value is not in the data set, a binary search can ...
62,201,557
62,202,104
Scale only if the type is std::complex
I have the following template function: template <typename T0> struct ComplexTypeTraits { using type = T0; }; template <typename T0> struct ComplexTypeTraits<std::complex<T0> > { using type = T0; }; template<typename T> void myFunction(T& out, const T & in) { using T1 = typename ComplexTypeTraits<T>::type;...
The function doesn't compile because the line const T y(std::cos(theta),-1*std::sin(theta)); still needs to be valid; it's not when T = float. This would be easy to solve with C++17's constexpr if: if constexpr (std::is_same<T, T1>::value == false) If you cannot use C++17, you can use tag dispatching: template<typenam...