question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
67,500,353
67,501,188
How to unit test a void function in C++
I am working on a hobby project mainly to learn cpp unit testing and database programming. However I am a little bit lost & confused about how should I write my code for proper testing. I tend to write a lot of void functions for my cpp projects. But now I can not figure out how should I test those functions. I have be...
The problem is not so much in the function returning void. Think about how it signals errors and make sure all cases (success and failures) are tested, simple as that. However, I don't see any error signalling at all there, apart from logging it. As a rule of thumb, logging should only be used for post-mortem research ...
67,500,388
67,500,539
Outputing integer as float in printf_s function
Having such simple C++ instructions: int f1 = 3238; printf_s("Printf_1.cpp 1 - float: %d\n", f1); printf_s("Printf_1.cpp 2 - float: %f\n", f1); The output of the second printf_s is 0.000000 My question is why there isn't just 3238.000000? What happened with 3238 integral part of the number? PS. My specs: Win 10, Micr...
printf requires variable argument types to match your format specifiers. In particular, %f expects you to pass double, and you pass int. printf interprets bytes of your int in that way so it prints out 0.000000, but in general there is no warranty what such combination should produce (and that's called "Undefined Behav...
67,500,671
67,500,914
Abbreviated Syntax to define a std::vector of class enum values in C++
Due to my inability to find an answer or the right words to search for I ask here: I have a (lengthy) class enum defined by enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 }; The only way I know to define a vector of those is: #include <vector> enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 }; int m...
C++20 added using enum X syntax, which does what it looks like. #include <vector> enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 }; int main() { using enum SomeLongName; std::vector<SomeLongName> v1 = { Foo, Bar }; return 0; } In previous versions, you can use an enum instead of an enum class.
67,500,740
67,514,467
How to change pointopoint link datarate during run time in NS3
I'm new to NS3. I have a query in changing the pointtopoint link datarate during the runtime. I tried a solution which is mentioned in https://stackoverflow.com/a/65514090/13121848. But here SetDeviceAttribute is not resolved for me. void ModifyLinkRate(PointToPointNetDevice *dev) { dev->SetDeviceAttribute("DataRat...
Inorder to change the datarate of a pointTopoint link, the PointToPointNetDevice installed in a node has to be retrieved. This can be done using the NetDeviceContainer where the node is associated. The example code is below, void ModifyLinkRate(NetDeviceContainer *ptp, DataRate lr) { StaticCast<PointToPointNetDevic...
67,500,798
67,500,931
Qt5 - QBoxLayout Piling Everything on Top of Each Other
I'm trying to learn about Qt and I'm having trouble understanding layouts. No matter what I do, it's just piling everything on top of each other and not actually laying anything out. This is just to sort of get something together for me to get a format going, but what I'm going after is this - Three widgets that are a...
The easiest way to assign a layout to a widget is to pass the widget in the layout's constructor: RotorSlot::RotorSlot(QWidget *parent) { // Set up widgets [...] // layout_ should lay out this widget layout_ = new QVBoxLayout(this); // Add things to layout [...] } However, a QMainWindow is a bit of a speci...
67,500,933
67,501,038
Trigger a test failure when UBSAN (-fsanitize=undefined) finds undefined behaviour
I have a small unit test here which has undefined behaviour. Source code: #include <gtest/gtest.h> TEST(test, test) { int k = 0x7fffffff; k += 1; // cause integer overflow } GTEST_API_ int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } I enable UBSAN in ...
According to the documentation: -fsanitize=...: print a verbose error report and continue execution (default); -fno-sanitize-recover=...: print a verbose error report and exit the program; -fsanitize-trap=...: execute a trap instruction (doesn’t require UBSan run-time support). Note that the trap / recover option...
67,501,684
67,502,661
Returning references to CUDA-specific vector types
I would like to implement f1 with the argument and return value exactly as in the code below. It fails with the error: a reference of type "float1 &" (not const-qualified) cannot be initialized with a value of type "float" However, almost the same function f2 with a native C++ type float instead of CUDA-specific wrapp...
This solution was discussed in the comments and there I also stated that I find this a bit dirty, however if CUDA specification guarantees the alignment of the float4 and float1 values then this could be a valid option; __device__ float1& f1(float4& v) { return *reinterpret_cast<float1*>(&v); } __device__ float& f...
67,501,728
67,504,962
Partial ordering rules of template parameter pack in C++17
Here is an example from temp.deduct.partial. template<class... Args> void f(Args... args); // #1 template<class T1, class... Args> void f(T1 a1, Args... args); // #2 template<class T1, class T2> void f(T1 a1, T2 a2); // #3 f(); // calls #1 f(1, 2, 3); // calls #2 ...
CWG1395 does not appear to change anything related to the example you cited from the standard. Keep in mind that CWG1935 was issued to allow for e.g. template<class T> void print(ostream &os, const T &t) { os << t; } template <class T, class... Args> void print(ostream &os, const T &t, cons...
67,502,217
67,510,503
warning C5240: 'nodiscard': attribute is ignored in this syntactic position
Recently version 16.9.5 of Visual Studio 2019 has been released. It apparently introduced new warning: [[nodiscard]] __declspec(dllexport) bool foo(); //ok __declspec(dllexport) [[nodiscard]] bool bar(); // warning C5240: 'nodiscard': attribute is ignored in this syntactic position Actually I thought that both nodisca...
I got this warning today too, so decided to look into it. This requires looking a bit at the standard, and putting different sections together. According to [dcl.fct.def.general], a function is defined as: function-definition: attribute-specifier-seq_opt decl-specifier-seq_opt declarator virt-specifier-seq_opt funct...
67,502,381
67,503,356
How can I avoid circular dependency causing error C2039?
I am still learning C++ hard and have now generated a circular dependency that, according to C2039: Class is not a member of Namespace may be the cause to my issue that I get a C2039 error. Can somebody help me how to cut this circle? I have two template classes and the template class tXmlGeometry<Part> has a member fu...
Since they're both template classes, I'd consider placing them in the same header. In order to avoid dependency issues, you can separate the declarations and definitions. Something like this: namespace nXml { // tXmlGeometry<Part> declaration template<class Part> class tXmlGeometry : public tXmlNode<Part> ...
67,502,415
67,502,643
Overload operator [ ] to return the integer at subscript location.If values of wrong data type passed as index ,handle by exception using c++
if index value is integer then it will return the corresponding value. if index value is float then it will throw an error which will be handled by exception such that values of wrong data type do not get passed as index; and if passed it will get handled by exception. When I access A[f] it should be handled by excepti...
Here is some code that does what I think you're trying to do. Note that if you want the operator[] functions to be called the you need to use [] on an object of the type of the class, not on a normal array. I've added another line to your main function to show how to use [] on the Vector object. If you do want to us...
67,502,680
67,502,969
How to downsample grid in OpenVDB
Is there any good way to downsample voxels grid in OpenVDB? For example I have grid 8x8x8 with voxel size - 1.0, and I want to get grid 4x4x4 with voxel size - 2.0: each voxel of new grid is some interpolation of original voxels, e. g. [0,0,0] voxel of new grid is average value of [0,0,0]-[1,1,1] (8 voxels) of original...
The thing I was looking for is resampleToMatch openvdb::FloatGrid::Ptr dest = openvdb::FloatGrid::create(); dest->setTransform( openvdb::math::Transform::createLinearTransform( 2.0f ) ); // org voxel size is 1.0f openvdb::tools::resampleToMatch<openvdb::tools::BoxSampler>( *org, *dest );
67,503,247
67,503,932
Quick regex_search/replace, or clear indication of replacement?
I must browse a collection of strings to replace a pattern and save the changes. The saving operation is (very) expensive and out of my hands, so I would like to know beforehand if the replacement did anything. I can use std::regex_search to gain knowledge on the pattern's presence in my input, and use capture groups t...
No regex_replace doesn't provide this info and yes you can do it with a regex_search loop. For example like this: std::regex pattern("..."); std::string replacement_format = "..."; std::string input = "......"; // a very, very long string std::string output, replacement; std::smatch match; auto begin = input.cbegin();...
67,504,121
67,504,309
Why when drawBackground is called does it override the setBackgroundBrush colour?
I'm following this series on youtube Node Editor. I'm attempting to learn both Qt and C++ at the same time, possibly a stupid idea, but "hello world" tutorials don't do much for me. Episode 1 We are to create a grid using the drawBackground method, however before this in the class constructor we have set the background...
I suspect the problem is simply that your drawBackground override doesn't use the background brush -- you just set the QPainter pen and use it to draw lines. I think the simplest solution would be to call the base class implementation of drawBackground at the top of your own, so... void QDMGraphicsScene::drawBackground...
67,504,613
67,600,935
How can I include .dylib files in ".json" configuration files? - VS Code on Mac iOS - Clang++ compiler - Language: c++
I unsuccessfully was looking 2 days on google to find a clear paragraph to describe how to include dynamic libraries (files with .dylib extension on Mac iOS) in order to be compiled by clang++ when someone is setting up the task.json and/or c_cpp_properties.json files - (prior to press F5 in order to launch the task an...
The solution to this particular problem is to add in task.json the next command arguments: task.json { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "type": "shell", "label": "clang++ buil...
67,504,639
67,515,698
Convert HICON to QIcon in Qt 6
I'm trying to convert a HICON to a QIcon/QPixmap in Qt6. In older Qt versions there used to be a fromHICON function that made this conversion very easy. Unfortunately, they removed it in Qt6 so I tried to do it myself following this answer: HDC hdc = GetDC(hwnd); HBITMAP hbitmap = CreateCompatibleBitmap(hdc, 32, 32); h...
In QT 6, the implementation (minus a convert to QPixmap) for QtWin::fromHICON() has moved into a static function for QImage. So now you just need to. QPixmap pixmap = QPixmap::fromImage(QImage::fromHICON(icon));
67,505,585
67,505,607
Why does the constructor returns an empty vector?
I am working on an end-of-year project for my university CS course, but I have been stuck at this one function for several days, I haven't been able to get much help, and my time is starting to run out. Can you please help me fixing this? The function definition in hpp contains a constructor: class Grille { vector<...
The constructor is declaring a local variable vector<vector<Place>> grille(20); that is shadowing (hiding) the member variable vector<vector<Place>> grille;. You should remove the local variable, and instead initialize the member variable grille via the constructor's member initialization list. Grille::Grille() : grill...
67,505,775
67,506,027
How to create import to CodeQL
I want to create an import to my CodeQL query. I want that this import will be named Utils and I will created inside it a predicate named isNumber. How can I creat such import? This how I want my code to look like: import cpp import Utils where if exists(...) then isNumber(size.(VariableAccess).getTarget()) ...
I found how to do it. Need to create a file named Utils.qll in the same folder of your CodeQL query. This is its code: import cpp predicate isNumber(Variable v){ v.getUnspecifiedType() instanceof IntegralType }
67,505,900
67,506,864
Inherited static method does not use new overridden static attribute
I have a c++ class in a header file: class Component { public: static const char identifier = '_'; static bool represented_by(const std::string& token_str); }; The represented_by method is implemented in a separate file: bool Component::represented_by(const std::string &token_str) { return token_str.rfind(...
You cannot expect polymorphism behaviour over static members. But as char is an integral type, you can use templates: template <char Identifier = '_'> class Component { public: static const char identifier = Identifier; static bool represented_by(const std::string& token_str); }; template <char Identifier> boo...
67,506,579
67,513,683
How to export template instantiation as non weak?
C++ template functions are exported as weak symbols to work around the one definition rule (related question). In a situation where the function is explicitly instantiated for every use case, is there a way to export the symbol as non-weak? Example use case: // foo.hpp template<typename T> void foo(); // All allowed i...
objcopy supports the --weaken option, but you want the opposite. It also supports the --globalize-symbol, but that appears to have no effect on weak symbols: gcc -c t.cc readelf -Ws t.o | grep _Z3fooI 14: 0000000000000000 7 FUNC WEAK DEFAULT 7 _Z3fooIiEvv 15: 0000000000000000 7 FUNC WEAK D...
67,506,738
67,511,099
taking input until end of file in c++
I am solving a graph problem where I have to take input from a file. Below is my input.txt file. 12 1 2 2 3 2 4 2 5 3 6 4 5 4 7 5 2 5 6 5 7 6 3 6 8 7 8 7 10 8 7 9 7 10 9 10 11 11 12 12 10 In the above input.txt file first input is no of vertices and the others till the end of the file are directed edge of Graph. The f...
Your code is wrong for 2 reasons: you use a hardcoded number of edges when should use the number of vertex you use an array with an index starting at 0 when the number of the vertex is read from file and does not start at 0 If you want to be safe, you should use a map (or unordered map) int -> list: ... class Graph {...
67,507,494
67,507,739
Run function when header is include c++
I am building a quick trigonometry function approximation in a single header file. #ifndef COOL_MATH_H #define COOL_MATH_H #include <cmath> const float PI = std::acos(-1); namespace trigonometry { namespace { float _cos[180]; } void init() { for (int i = 0; i < 90; i++) { ...
How can I run the function trigonometry::init() when the header file is included (i.e. only once)? #ifndef COOL_MATH_H #define COOL_MATH_H #include <cmath> #include <array> const float PI = std::acos(-1); namespace trigonometry { namespace { std::array<float, 180> init() { std::a...
67,507,815
67,507,887
error: no matching function for call to 'displayScreenXY' in 2D Table
I'm learning c++, I'm trying to display simple table with X Y coordinates in each case. But when I build it I get this error : error: no matching function for call to 'displayScreenXY' I tried to replace void displayScreenXY(int **tab, int x, int y); by void displayScreenXY(int tab[][], int x, int y); but I get this ...
The conversion of a pointer to an array only applies to the outermost dimension of a multidimensional array. So a int [yDiv][xDiv] cannot be converted to a int **. If you change the signature to: void displayScreenXY(int tab[yDiv][xDiv], int x, int y); It will work as expected.
67,507,896
67,507,971
How to introduce values in an array of structs? (c++)
I want to make a program that lets the user input the brand, price and color of a car for an unknown amount of cars, and cant figure out how to do that or what i have to search for in order to understand. Example of what i want it to do: i want 20 cars, and i want to input values for each one of them and at the end hav...
Your first step will be: int main() { car m[20]; // todo better: std::vector for(int i=0; i < 20; i++) { cout << "Brand of first car: "; cin >> m[i].brand; cout << endl; cout << "Color of first car: "; cin >> m[i].color; cout << endl; cout << "Price of first car: "; cin >> m[i].pric...
67,508,433
67,508,501
Pointer input issue to template function - probably "programmer error"
I am trying to write a couple of template functions that convert back and forth between a value of any data type (within reason) bytewise into a character string. The idea is to (eventually) store the values in a .bin file, and also to be able to recover the values from said .bin file. However, I need to get the conver...
Here template<typename T> void buildabin(char*& X, T x) { X = (char*)&x; } you are trying to set a reference to the address of function parameter, which leaves you with dangling pointer. You probably want void buildabin(char*& X, T& x). However, I have no idea what you are actually trying to achieve, so this answe...
67,508,855
67,509,572
initializing enum with a constructor
I already found this really good explanation Initialising enum via constructors but it didn't fit my needs. So I declare an enum inside a class and want to initialize it inside the class constructor and then call this enum via a switch statement inside a method but I'm not able to implement it. Here is a code: clas...
Inside of your class you'll want to include a variable of type State: class myClass { myClass(); enum class State; // create a class member variable of type State named enumState; State enumState; void update(); }; Then inside of the constructor you can initialize the new enumState var...
67,509,359
67,509,928
Pointer vs Reference
I know this is already a commonly asked question, but I'm more curious about how pointers and references behave at a lower level (like how compiler deals with them, and how they look like in memory), and I didn't find a solution, so here I am. At first I was wondering if an array can be passed as a parameter without be...
The old C idiom is, that arrays get turned into pointers to the array type, when a function is called. And that is mostly still true für C++. So for the details of it, let's look at two functions taking an integer argument, first: void f(int x) { x = 42; } // function called with x by value void g(int& x) ...
67,509,601
67,509,734
How *(&arr + 1) - arr is working to give the array size
int arr[] = { 3, 5, 9, 2, 8, 10, 11 }; int arrSize = *(&arr + 1) - arr; std::cout << arrSize; I am not able to get how this is working. So anyone can help me with this.
If we "draw" the array together with the pointers, it will look something like this: +--------+--------+-----+--------+-----+ | arr[0] | arr[1] | ... | arr[6] | ... | +--------+--------+-----+--------+-----+ ^ ^ ^ | | | &arr[0] &arr[1] | | ...
67,509,860
67,509,931
Is it possible to construct a `std::span` from a view in C++20?
This example program does not compile, because the transform_view cannot be converted to a std::span: class Foo { private: std::vector<std::string> strings = { "a", "b", "c" }; public: std::span<const char*> getStrings() { return strings | std::views::transform([](const std::string& str) { return str.c...
Is it possible to construct a std::span from a view in C++20? It is possible to construct a span from any contiguous range (of appropriate underlying type). The problem here: std::span<const char*> getStrings() { return strings | std::views::transform([](const std::string& str) { return str.c_str(); }); } is tha...
67,510,097
67,510,131
How to only use some of the optional arguments of a function
Is there a way to only use some optional arguments of a function? So if I have a function like this, void f(int a = 0, int b = 1) {} can I call f() and only specify b and leave a on its default value?
I wish. C++ lacks this feature that is common in other languages (like C# or Python). For now, you are stuck with either being very clever about designing the order of your parameters, or refactoring your parameters into a small struct: struct f_args { int a = 0; int b = 1; }; Now you can optionally set whatever...
67,510,233
67,510,468
How can I change the letters of a sequence in a text file?
I must improve and extend this code. Into detail, I have a text file with codes of genotype (i.e. AGGGGCCCTATTCGCCC.....) that want to change these codes like this: A -> T G -> C C -> G T -> A I mean that A change to T like above. Then I save this new code in my file. I would be grateful if you guided me through this. ...
How about something like this? This version processes each character, not each line. And to keep things short, I didn't include any domain-specific error handling. I'm assuming you wanted to process each individual character... and each character is either replaced inline or left as is. int main() { // ... Open t...
67,510,555
67,510,852
Why in Python the choice of IDE does not matter, while in C++ it does?
This summer, I am a teaching assistant for a professor in a Python course. Last Wednesday, I explained to the students that they absolutely must use the IDE of the course, i.e. PyCharm. Otherwise, if a student is doing practical work using another IDE (e.g. VS Code), it is possible that the interpreter of PyCharm is di...
I think you're actually mixing up two important things. The editor that is used to create the code can technically be anything. There are a number of nice-to-haves with editors that help you write code, such as auto-indentation, variable name expansion, etc. But many editors (e.g. IDEs) also have built in compilatio...
67,510,806
67,510,940
Why doesn't the compiler like all the strings that are associated with "Iter"?
I am implementing one of the behavioral design patterns. The compiler gives errors in lines that are related to "Iter". I don't understand at all why this happens, and even more so, how can it be fixed? I thought that maybe there was a clerical error somewhere (I'm doing a program following the example from the book, t...
You need a forward declaration class Iter; outside the declaration of class ContainerPerson. Otherwise the friend class is ContainerPerson::Iter which is unrelated to the Iter you declare later. See Why does a C++ friend class need a forward declaration only in other namespaces? Typo in the definition of Iter* Cont...
67,511,029
67,512,899
How to mark dynamically initialized globals as "discardable if unused" in MSVC?
I have some globals like FARPROC const f = GetProcAddress(...); Is there any way to urge the compiler or linker to discard them (and related initialization code) if it is determined the code is unused at link-time (like with /Gy and /OPT:REF)?
I figured it out. It seems __declspec(selectany) does this, even without passing /Gw. As an example, this program will only contain GetTickCount_: #include <Windows.h> FARPROC GetTickCount_ = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetTickCount"); __declspec(selectany) FARPROC GetTickCount64_ = ...
67,511,245
67,511,319
Reason of additional destructor call?
Given is the following simple class: #include <iostream> class Foo{ int a, b; public: Foo(int _a = 0, int _b = 0) : a(_a), b(_b) { std::cout << "Foo(int, int)" << "\n"; } Foo(const Foo& foo) : a(foo.a), b(foo.b) { std::cout << "Foo(const Foo&)" << "\n"; ...
what am I missing here? The destruction of T2. There are 3+2 constructors called, there must be 3+2 destructors called too!
67,511,884
67,512,086
Writing a wrapper for OLED SSD1306
I'm struggling to learn Arduino's C++ right now. I'm trying to write a simple wrapper so I can use multiple OLED's on my project. Here is what I've got so far : class Screen { private: Adafruit_SSD1306 display; unsigned long startTime = 0; public : Screen(){ Adafruit_SSD1306 this->display(128,...
This line: Adafruit_SSD1306 this->display(128, 64, &Wire, -1); is not valid C++. If you want to initialise the display member in your Screen object, you can do something like: this->display = Adafruit_SSD1306 (128, 64, &Wire, -1); Disclaimer: I don't know what parameters the Adafruit_SSD1306 constructor is expecting...
67,512,097
67,512,151
C++ : Copy-constructing from different instantiation
I would like to be able to copy-construct a Particle<Color::X> using a differently-"colored" instance. Different instantiations might contain a very distinct set of members, but they all have any number of members in common (exemplified below by intensity) which must be copied by the ctor. The ctor in question must, of...
If you want a copy constructor that accepts instances of other instantiations then you just need a copy constructor that accepts instances of any instantiation: enum class Color { RED, GREEN, BLUE }; template <Color c> struct Particle { int intensity; Particle(int i) : intensity{i} {}; templa...
67,512,428
67,513,576
"sell_seat()" function getting skipped over
I'm in the last part of a C++ online course and having difficulty with one of my labs. The lab describes writing a program that lets the user know of available and sold tickets for a theater. The output for the code should be: AA 101 sold AA 102 available However, I continue to receive an output of: AA 101 AA 10...
For the first if statement, the function is never entered because the is_sold function returns true. You're using the not operator, so the statement is evaluated as false. Therefore the status never updates and that's why it's blank. bool ShowTicket::is_sold() { return (row == "AA" && seatNum = "101"); //simplified ...
67,512,606
67,512,632
merging a list in C++
I am new to the concept of STL and I came across a problem in List merge code. list<int> lst1; list<int> lst2; lst1.push_back(5); lst1.push_back(7); lst1.push_back(1); lst1.push_back(9); lst1.push_back(12); lst2.push_back(45); lst2.push_back(6); lst2.push_back(9); the output for the code: lst1.merge(lst2) is 5 7 1...
This is why you need to read at least the summary of the function's documentation before guessing at what it does. Literally the first line: Merges two sorted lists into one. The lists should be sorted into ascending order. The whole point of the function is to merge two sorted inputs into a single sorted result. If ...
67,513,024
67,513,143
Template funtion returning an iterator
i would like to make a reusable function that returns an iterator to make it easy to find the middle point of a container and need some help fixed; template <typename T> std::vector<int>::const_iterator middlepoint(std::vector<T> const& arr){ auto temp = arr.begin() + arr.size() / 2; return temp; } the caller...
It looks like you're taking the beginning and end iterators and dividing them by 2 to get the middle position. Iterators don't have a valid expression for division, so what you're doing won't work. The best way I can think to implement this would be to use the size of the container divided by 2 as an offset from the be...
67,513,342
67,520,621
How can I allocate class memory?
#include <iostream> #include <vector> using namespace std; enum Color { RED, BLUE, YELLOW }; class Shape { Color lineColor; public: Color getLineColor() const { return lineColor; } virtual Shape* clone() const = 0; virtual void print() const = 0; virtual float getLength() const = 0; }; class Poin...
I'm seeing these errors related to Rectangle when building with clang: <source>:70:32: error: allocating an object of abstract class type 'Rectangle' ClosedShape* const r = new Rectangle(p1, p2, p3, p4); ^ <source>:49:20: note: unimplemented pure virtual method 'clone' in 'Rectangle' ...
67,513,570
67,529,191
Explicit template instantiation for a range of template parameters in C++
Explicit template instantiation is very useful when creating libraries. Suppose I have a template with an int paramater: template <int i> struct S { ... }; To perform explicit template instantiation, the grammar is something like template struct S<1>; However, I can only instantiate one instance using one line in thi...
Let's start with a slight shift in perspective. The goal is to instantiate certain instances of a given template. Note that I dropped the word "explicit" – while there will be an explicit instantiation, it need not be of the template in question. Rather, I would explicitly instantiate a helper template that will implic...
67,513,616
67,513,735
is there any methods can do round(a, n) in c++?
I want to round a float number. in python, i have: round(x, 2) # 3.1415 -> 3.14 but in c++, i find round function can only round to integer. Is there any similar method in c++?
AFAIK the standard library provides no such function, but it shouldn't be too hard to roll out your own: #include <iostream> #include <cmath> // fast pow for int, credit to https://stackoverflow.com/a/101613/13188071 int ipow(int base, int exp) { int result = 1; while (true) { if (exp & 1) ...
67,514,002
67,514,532
Problem with thread function arguments in C++
The objective of this main function is to find the number of prime numbers in a range using threading to divide the problem into the selected number of threads. I'm having issues with std::thread and getting an error because of the arguments. I'm not sure of how to fix it. Any help would be greatly appreciated. Here is...
If you follow error messages further compiler tells you exactly what is the problem: prog.cpp:41:82: note: variable-sized array type ‘int (&)[numThreads]’ is not a valid template argument std::thread* th = new std::thread(myRun, minThread, maxThread, threadCount, i); Note VLA is not allowed in C++, use std::vector ...
67,514,040
67,514,136
Why push_back() will change the previous value?
I want to build a series of paths with serial numbers through a for loop, so I use a series of strcpy and strcat (I know there is a string method, but please forgive me, my technique is really poor). But after the loop, I get a series of the same results. Here is my code: #include <iostream> #include <io.h> #include <v...
Your vector's elements are all the same pointer value, the address of the array TempFilePathChar. In your loop you are overwriting the content of that array so you are always getting the content produced by the last iteration of the loop.
67,514,254
67,514,350
Advice on uploading trading bot .exe files to a VPS to run 24/7
I've made a trading bot that uses a c++ .exe for the backend (compute the predictions) and a python .exe for the the frontend (UI, placing trades, keeping track of trades, fetching market data, etc..). Currently I'm running it simply on my laptop, the backend only uses ~1mb process memory at any point, while the fronte...
I'm also implementing a bot. So cool that you are doing so as well. I think that it's really the way to go, making emotionless, data-driven trades. Anyways, if I were you, I would start an AWS instance. Either Linux or Windows. If you can run your software on Linux, that would be cheaper, as you won't have to pay the (...
67,514,441
67,514,471
How to copy a array consisting of vectors
I have this array of vectors, vectors of pair: vector<pair<int, int> > adj[V]; How can i copy this to another variable ? vector<pair<int, int> > adjCopy[V] = adj; //not working; I also tried using std:copy but is shows that vector(variable size) is inside the array so, cannot copy.
vector<pair<int, int> > adjCopy[V]; std::copy_n(&adj[0], V, &adjCopy[0]); // or std::copy(&adj[0], &adj[0] + V, &adjCopy[0]); More idiomatic: vector<pair<int, int> > adjCopy[V]; std::copy_n(begin(adj), V, begin(adjCopy)); // or std::copy(begin(adj), end(adj), begin(adjCopy)); In general, don't use C-arrays, use std:...
67,514,634
67,514,717
Clang error: Dependent nested name specifier for friend class declaration not supported
I am trying to write a hash function for my custom class, and make my code compatible with both gcc 11.1 and clang 12.0.0, but clang gives the warning/error: <source>:30:25: warning: dependent nested name specifier 'std::hash<Base<U>>::' for friend class declaration is not supported; turning off access control for 'Bas...
You can change the friend declaration only valid for the Base of current template parameter T, i.e. current instantiation. template<typename T> class Base { std::set<int> data_; public: Base(const std::set<int>& data): data_{data} {} friend std::size_t std::hash<Base<T>>::operator()(const Base<T>...
67,514,703
67,514,829
Euler Method for system of differential equations
I'm trying to recreate computation of a SIR model as described here, with extra midpoint calculations. But for some reason no values actually change during the Euler calculations. #include <iostream> using namespace std; int main(){ double s[100]; double i[100]; double r[100]; double bb = 1/2; do...
Your variables bb and kk are both zero due to integer division. Always use double literals: double bb = 1.0/2.0; double kk = 1.0/3.0;
67,514,994
67,515,081
Does C++ guarantee the lambda unnamed class always has an "operator bool()" defined?
#include <type_traits> int main() { auto f = [] {}; static_assert(std::is_same_v<decltype(!f), bool>); // ok f.operator bool(); // error: ‘struct main()::<lambda()>’ // has no member named ‘operator bool’ } Does C++ guarantee the lambda unnamed class always has an operator bool() ...
No, lambdas doesn't have operator bool(). !f works because lambdas without captures could convert to function pointer (which have a conversion operator for it), and then could convert to bool, with the value true since the pointer is not null. On the other hand, int x; auto f = [x] {}; !f; // not work; lambdas with cap...
67,515,062
67,515,192
does implicit pointer conversion occur during assignment?
For e.g. int x = 3; float * ptr = (float*)&x; // here compiler does not implicitly do conversion, but we have to manually convert to float* so my question is, why here we don't need to manually convert it. Base_Class * ptr = Derived_Class pointer; is here implicit conversion occuring ?
here compiler does not implicitly do conversion Because int and float are unrelated types. Accessing one as if it's the other (type punning) is Undefined Behavior. Why is here implicit conversion occurring Because accessing a derived object via a pointer of type base is a fundamental mechanism by which runtime poly...
67,515,618
67,515,882
Compiler not recognizing the constructor, expects arguments and recognizes zero
I am trying to organize data into a binary tree and have created a struct to better organize the data. However, my compiler has this error message every time I try to run my code: BinaryTree.cpp:41:37: error: no matching function for call to 'person::person()' node (person i, node * l, node * r){ ...
Since you defined a non-default constructor, the compiler will not generate a default constructor, see https://en.cppreference.com/w/cpp/language/default_constructor for more info. To solve this, see default constructor not generated?.
67,515,778
69,317,738
Unable to find GCC Code coverage libgcov.so for arm toolchain
Steps to Reproduce the issue #include<iostream> int main(){ std::cout << "Hello World" << std::endl; } Write main.cpp Download Toolchain from this link Compile with below commands. . /opt/poky/1.6/environment-setup-armv7a-vfp-neon-poky-linux-gnueabi arm-poky-linux-gnueabi-g++ main.cpp -o main --coverage Wil...
Build the application using yocto build system bitbake Copy the libgcov.so generated from /tmp/deploy/ into /opt/poky/1.6.1/sysroots/i686-pokysdk-linux/usr/lib/ Trigger the build using g++
67,515,941
67,516,052
The loop is not ending, and I need to find the error in the code
#include<iostream> using namespace std; int main(){ int64_t n; int64_t m; int64_t Sum; cin >> n; for(int64_t i=0; i<n-1; i++){ int64_t a, b; cin >> a >> b; int64_t m = 0; while(m <= b){ int64_t y = 0; m = a + y; Sum += m; ...
The problem is in this part: while(m<=b){ int64_t y=0; m=a+y; Sum +=m; y++; } There's int64_t y = 0 which will make a new y equal to 0 in every single iteration. y++ is useless, and so m = a + y will be the same as m = a + 0 which will never change the value of m and the boolean m <= b will always...
67,516,479
67,517,574
How do I avoid large number of locks?
Let arr be declared as follows. std::vector<std::vector<int>> arr(10,000,000); My code in serial is something like for (const auto [x, y] : XY) { arr[x].push_back(y); } I use openmp and define an array of locks as follows. std::vector<omp_lock_t> locks(10,000,000); With locks, I use #pragma omp parallel for schedu...
According to the OpenMP documentation, omp_lock_t represents "a simple lock". I suppose it is some kind of a spinlock. You, therefore, don't need to care about limits for a number of mutexes. (Mutexes require some interaction with a kernel / scheduler, which is likely a reason for restricting their count.) omp_lock_t u...
67,517,248
67,517,515
about equal_func of unodered set/map
#include <string> #include <unordered_set> using namespace std; class EQ { public: bool operator()(const string& a, const string& b) const { bool temp{ a.size() < b.size() }; const string& shorter{ temp ? a : b }; const string& longer{ temp ? b : a }; return equal(shorter.begin(), ...
unordered_set uses buckets to store the values. A bucket may contain one or more objects. The bucket to store an object in is based on the value the hash function returns. During a lookub (whether that's done for insertion or to check, if a object is already part of the set) unordered_set first determines the bucket ba...
67,517,939
67,518,435
How to connect the theory of fixed-point numbers and its practical implementation?
The theory of fixed-point number is that we divide certain number of bits between integer part and fractional part. This amount is fixed. For example, 26.5 is stored in that order: To convert from floating-point to fixed-point, we follow this algorithm: Calculate x = floating_input * 2^(fractional_bits) 27.3 * 2^10 ...
Fixed-point formats are used as a way to represent fractional numbers. Quite commonly, processors perform fixed-point or integer arithmetic faster or more efficiently than floating-point arithmetic. Whether fixed-point arithmetic is suitable for an application depends on what numbers the application needs to work with....
67,518,135
67,520,288
Calling Matlab SDK function from C++
I created a C library using Matlab Compiler SDK, and am struggling to call the function in it. The function definition in Matlab looks like this, so it has no arguments and returns one value of double(3) function val = test6() val = double(3); end And the header file has this line. extern LIB_libtest6_C_API bool M...
[I don’t have the MATLAB Compiler, so cannot test any of this, excuse inaccuracies.] The function’s return value is a Boolean indicating whether the call was successful or not. The function will output its result as an mxArray. The mxArray is allocated by the function and assigned into your pointer array, but you do n...
67,518,371
67,518,438
Initializer lists for multidimensional arrays and vectors
I want to use initializer lists for my vectors and arrays. Ultimately, I would like to initialize an array of vectors of some class A, but I do not get there while getting weird compiler errors. Here is some code: #include <vector> #include <array> class A { public: A(int x_, int y_): x(x_), y(y_) {} p...
Use one more pair of braces. auto data4 = std::array<std::vector<int>, 3> { { {0,0,0}, {1,1,1}, {2,2,2} } }; Otherwise the first list {0,0,0} is considered as an initializer of the whole object of the type std::array<std::vector<int>, 3 >.. std::array is an aggregate. From the C++ 14 Standard (23.3.2.1 Class template ...
67,518,425
67,518,586
C++ STL and multiple definitions
While searching the doc on cppreference.com, I've seen that some features are defined multiple times in different headers... For example: std::move (in <algorithm> and <utility>), std::size_t, etc (see below). The page about std::size_t starts with this precision: Defined in header <cstddef> Defined in header <cstdio>...
Every standard library header needs to be self contained. If we want to use it, we are not to be forced into including anything else. Since all of the headers in the list you cite end up using size_t in some capacity, including them must also make size_t available. So it's standard mandated behavior. Mind you, that the...
67,518,513
67,519,751
AArch64 SVE/2 - Left pack elements from list
I'm trying to implement a SIMD algorithm with AArch64 SVE (or SVE2) that takes a list of elements and only selects the ones that meet a certain condition. It's often called Left Packing (SSE/AVX/AVX-512), or Stream Compaction (CUDA)? Is it possible to vectorize this operation with SVE? Equivalent SQL and scalar code c...
Use svcompact to compact the active elements, then a normal linear store to store the result.
67,518,599
67,518,776
How to fix duplicated functions in object files?
I'm building a program just to increase my OOP skills. This is my project structure: Project -.vscode -build -includes - ContactInfo.h - Customer.h - Owner.h - PersonalInfo.h - User.h -src - ContactInfo.cpp - Customer.cpp - Owner.cpp - PersonalInfo.cpp - User.cpp - wrapper.h - wr...
In your wrapper.h extern char key; void printUI(); void RunApplication(); PersonalInfo CreatePersonalInfo(std::string &, std::string &, int & ); ContactInfo CreateContactInfo(std::string &, std::string &, std::string &, int&); void DisplayAllCustomers(); void AddCustomerToList(Customer &); Customer CreateCustomer(Pers...
67,518,693
67,518,823
g++ isn't compiling all of the files in my project
I'm trying to build a c++ project in VS Code but when i try to build it g++ throws an error saying: g++ -std=c++17 -ggdb -Iinclude src/main.cpp -o bin/main Undefined symbols for architecture x86_64: "MessageBus::MessageBus()", referenced from: _main in main-244f95.o ld: symbol(s) not found for architecture x86...
You list the "working" command as: g++ main.cpp EventSystem/MessageBus.cpp -o maintest but your recipe is: $(BIN)/$(EXECUTABLE): $(SRC)/*.cpp The glob expression $(SRC)/*.cpp won't match the file main.cpp. If we could see your link line, we'd probably be able to see that main.cpp is missing.
67,518,848
67,518,923
Why cant we assign char to strings?
in C++, I noticed if I make a string str="kls";, then I can't write string s1=str[0]; I have to instead write: string s1; s1=str[0]; Why so?
The reason is that the class std::string does not have a constructor that accepts a single argument of the type char. While there is a copy assignment operator that accepts as an argument a single character. basic_string& operator=(charT c); You could write std::string s1( 1, str[0] ); or (there is used the initializ...
67,518,959
67,519,314
How can I use iterator values in templates?
Consider the following code: #include <iostream> enum class E { A, B }; template<E e> int f(); template<> int f<E::A>(){ return 1; } template<> int f<E::B>(){ return 2; } int main() { for( const E i : {E::A, E::B} ) { std::cout << f<i>() << "\n"; } } This fails to compile, because i is not init...
This is very related: Why isn't a for-loop a compile-time expression?. i in your loop is not a constant expression. However, by stealing from this answer one can make your code call f<i> inside the loop. It is not directly what you asked for because the proposed solution is for size_t index based loops instead of itera...
67,519,181
67,519,271
How to implement a #include function into own programming language
I am building my own programming language and I came across a problem. All programming languages, I discovered, have # include, import, # import function .I am trying to implement this same function in my own programming language, but I am not sure how to. Could you explain how import functions operate, how compilers i...
#include is rather simple actually, if you want to implement it yourself. The way I usually implement it (when not using a "proper" preprocessor) is to treat the source files as a stack. When you encounter a #include directive, get the whole line, parse it and figure out what source file to "include". Then push it onto...
67,519,285
67,519,455
Blank line file handling c++
void aggiungi_libro(struct cartello books[nmax]) { ofstream d; cout<<"Inserisci il codice del libro: "<<endl; cin>>books[0].code; cout<<"Inserisci il titolo del libro: "<<endl; cin>>books[0].title; cout<<"Inserisci l'autore del libro: "<<endl; cin>>books[0].author; cout<<"Inserisci l'anno di pubblicazione del libro: "...
If you use cin >> std:string (or ifstream >>), you will not detect blank lines. You need to use getline. This will return an empty string on a blank line. For starting to write at a given position, you'll want to use seekp.
67,519,458
67,520,384
2 bytes to custom format floating point
I have an array of bytes with this specification: byte[0]: upper 4 bits is the exponential part, the rest is significant (high) byte[1]: significant low Number of decimals is 2 Unit is in "m" full specification (P2Device Control > P2_Device_Control_Protocol_&_Command.pdf > page 111) Some sample values: 0xB3 0x70 shou...
According to the values provided and given exponent k and significand s the formula for the value seems to be s * 10^(k-16) (^ being exponentiation here) so you could implement the conversion as #include <iostream> #include <cmath> constexpr float toExponent(unsigned char value) { return value - 16; } float conv...
67,519,466
67,521,039
C++ function to safely compare integers of different types?
Due to implicit conversion and the fact that std::numeric_limits<T>::max() and friends return type T, it seems non-trivial to write a function bool cmp(IntA a, IntB b) that "does the right thing" to conceptually return a < b;. That is, if they share a common range, compare, if not, determine if a is less than b regardl...
If you can use C++20, then you can use the newly added functions to do just this. We now have template< class T, class U > constexpr bool cmp_equal( T t, U u ) noexcept; template< class T, class U > constexpr bool cmp_not_equal( T t, U u ) noexcept; template< class T, class U > constexpr bool cmp_less( T t, U u ) no...
67,520,191
67,520,521
Error when Initialising a reference to a pointer to const string with pointer to a non-const string
Hi i am trying to understand how references and pointers work in C++ and so was trying out different examples, in one of which i am unable to understand why the error is produces: int main() { cout << "Hello World" << endl; std::string s="hg"; std::string *ptr=&s; const std::string * &k=ptr ; ...
Given const std::string * &k=ptr ;, as you've seen, types don't match here. You're trying to bind a std::string* to reference to const std::string*. References can't bind to objects with different type directly, std::string* needs to be converted to const std::string*, which is a temporary, i.e. an rvalue, then you go...
67,520,410
67,520,808
How to deduce template return type with another template parameter with explicit specialization?
I have a (member) function with the following signature: template<Type TypeToAllocate, typename Str> Str* allocate(); Type is an enum and depending on the supplied enum, I want to return different pointers of type Str. Now I am not sure how I can do this. An example code is here: #include <functional> #include <ve...
I am not sure about the role of Str in your code. If this was just part of your attempt to map the enum values to either Bar or Baz, then I think you do not need it. I would use a trait, that can easily be specialized for different values of Type: enum class Type { A, B }; struct Bar{}; struct Baz{}; template...
67,520,793
67,521,619
Pass derived object to function and access overridden member function
I‘m trying to pass a pointer to an object which class inherits from another class to a function and then access the member functions of it. This is the base class: class Base { public: virtual int funcA(int paramA) = 0; } This is the derived class: class Derived : public Base { public: Derived(); ~Derived(); i...
First of all the definition of Derived::funcA(int paramA) lacks the return argument int and having a return type int it will have to return something e.g. paramA. For the sake of clarity that you want to override the function of the Base class I would also mark funcA as override or final. Secondly by passing a pointer ...
67,520,883
67,521,005
Define a class variable member in cpp file
I am trying to declare a class member variable in .h file and define it in .cpp file but in VS2019 I get the error: "redeclaration of member is not allowed". The example of my code is: .h file #include<iostream> class test { public: test(); int a; static int v; }; And the .cpp file is: #include"test.h" i...
For nonstatic members, you'll need an instance of the class to change variables. For example: // In the .cpp file test test_1; test_1.a = 1; // note that there is no need to include the type here test test_2; test_2.a = 2; assert(test_1.a != test_2.a); // since they are two separate instances Nonstatic members don't...
67,521,214
67,521,344
C++20: Force usage of designated initializers to emulate named function arguments
I am a big fan of using ad-hoc structs and designated initializers to emulate named parameters for my functions. struct Args { int a; int b; }; int f(Args a) { return a.a + a.b; } int g() { return f({.a = 1, .b = 2}); // Works! That's what I want. return f({1, 2}); // Also works. I want to forbid ...
The best way is just code review. Tell people to use designated initializers. Designated initializers are awesome, people like using them. This is really more of a social problem than a technical one. If you really want to give a nudge, you could always stick in some truly awful data members first, like so: class Args ...
67,521,245
67,521,313
When exactly are function arguments being destructed?
I have a question because it is not clear to me when function arguments get destroyed. Therefore, is the concatenation of the following doSomething function error-prone or not? I’m asking because "it is the programmer's responsibility to ensure that std::string_view does not outlive the pointed-to character array". Can...
The anonymous temporary passed to the (const reference) parameter const std::string_view& str_view survives the function call. Since there are nested functions, the anonymous temporaries are not destroyed until, conceptually, the closing semicolon of std::string output_str{ doSomething(doSomething(doSomething(input_str...
67,521,312
67,539,748
Safe equivalent of std::bit_cast in C++11
C++20 introduced std::bit_cast for treating the same bits as if they were a different type. So, basically it does this: template <typename T1, typename T2> T2 undefined_bit_cast(T1 v1) { T1 *p1 = &v1; T2 *p2 = (T2 *)p1; // Uh oh. T2 v2 = *p2; // Oh no! Don't do that! return v2; } except without the und...
template <class T2, class T1> T2 cpp11_bit_cast(T1 t1) { static_assert(sizeof(T1)==sizeof(T2), "Types must match sizes"); static_assert(std::is_pod<T1>::value, "Requires POD input"); static_assert(std::is_pod<T2>::value, "Requires POD output"); T2 t2; std::memcpy( std::addressof(t2), std::addressof(t1), size...
67,521,807
67,522,059
Is there an efficient way to provide an alias for a class member in C++?
Here is a base class: class Base { public: int foo; // ... }; This class is declared in a header file that I cannot change because I don't have the rights to do so. Here is a derived class: class Derived : public Base { public: // provide alias to Base::foo // ... }; Is there a way I can provide an al...
No, there is no renaming feature (though there was some work done on such a feature in the early days but it was dropped). There's no way to do what you want other than adding the desired name as a member to Derived, and forwarding it to the base class function. Note however that this can be inline and should be absor...
67,522,227
67,522,279
Call C++ function from (C) header file gives linker error
I am integrating a library (lwip) and I want to reroute the logging mechanism from printf to something I wrote myself (which logs directly to my uart). In some header file the following code exists /** Platform specific diagnostic output.\n * Note the default implementation pulls in printf, which may * in turn pull i...
extern "C" void logLineToUart(const char * log, ...); You need to tell it to make the name C-linker compatible the first time it is seen. update The extern "C" is only when compiling as C++. It is not legal syntax in C. You can use extern by itself (it is implied if you leave it off). Editorial That's not very friend...
67,522,441
67,522,649
Statically using namespace
This may be a duplicate but I didn't see exactly similar question. Does a using namespace declaration stops at the end of it's source file if not written in header ? foo.cpp using namespace foo; // will this using namespace's scope end at the end of this file? some random code... or do we need to create a scope ? bar....
The short answer is that in the 99% of time your using namespace ... is limited to the single .cpp it's in and other .cpp files don't have it. But you should learn about compilation units and how they work with the preprocessor. Usually a single compilation unit is a single source file. That single source file might of...
67,523,566
67,523,771
Infinite loop of zero in table
this code is dividing a circle into X part and display a table of radian value of each part. but I get an infinite loop of 0 display when I'm using value superior to 6 with value under 6 I get '0 1 2 3 4 5 6' It seems that displayed value are not float either. I have the code using degrees and work fine. #include <iost...
The obvious move here is to change i in your loop to be a double (or float) instead of an int. Along with that, when computing radian, 360/nbObjets does integer division, so if nbObjets is > 360, it'll give a result of 0. Changing 360 to 360.0 fixes that problem. But that leaves another problem: depending on the vagari...
67,523,881
67,533,235
Quickly finding array element by pointer
I have an array of strings where each string can also be clearly identified by a unique pointer assigned to it. The order of the elements in that array often changes, for example because of sorting. I want to be able to quickly find the numeric index of an array item just from its accompanying pointer. For example, aft...
This is what I came up with after Paul's explanations in the comments. It seems to do the trick. As suggested by Paul, it doesn't sort the original vector but keeps that as it is. Since the positions in the original vector now stay the same, we can use a simple map to map the pointer values to the corresponding index. ...
67,524,093
67,524,176
Why destructor is calling?
I have a simple code. #include <iostream> struct BABE { std::string* babe = nullptr; BABE(const char* str) { babe = new std::string(str); } ~BABE() { delete babe; } }; int main() { BABE bomb = "hello"; bomb = "world"; system("pause"); return 0; } When...
Why is it happening? Because in this line: bomb = "world"; To assign a const char * to your class, a temporary of struct BABE is created, that temporary is assigned to bomb (using the compiler-generated assignment operator), and then that temporary is destructed. As you violated the Rule of 3/5/0, the assignment lea...
67,524,558
67,524,707
Auto cast to void unused variable C++
I am trying to solve huge number of warnings in a C++ project that is generated by a lot of unused variables. For example, consider this function: void functionOne(int a, int b) { // other stuff and implementations :D doSomethingElse(); runProcedureA(); } In my project, in order to surpress the warnings I ...
A simple alternative is to not give names for the parameters instead of the cast. This way the unusage would be considered intentional: void functionOne(int, int) Another way to achieve the same is: void functionOne([[maybe_unused]] int a, [[maybe_unused]] int b) Is there any way to auto refactor all these functions...
67,524,617
67,525,192
how to make static "polymorphic" member variables
Basically what I am trying to do here is make an ID for each derived type of Shape. ( Square is 1, Circle is 2, etc.) How can I make a static member variable that has polymorphic capabilities? How would I create the getters and setters? class Shape { public: Shape() {} static int ID; }; class Square : public S...
you can do something like this if you really need to, but I suggest just making a constructor in base that accepts an id and pass it from the childs to the parent int getNextId() { static int lastId{0}; return lastId++; } template<typename T> int getDerivedId() { static int id{getNextId()}; return id; ...
67,524,892
67,526,997
OpenGL: Exception when binding uniform buffer
I have the following opengl code to bind a created buffer and fill it with some data. #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <array> #include <iostream> template <size_t max_lights = 100> class SceneLights { private: struct Light { glm::vec4 position; gl...
Got repro on my machine when compiling for 64-bit. Didn't crash on 32-bit but I suspect I just got lucky with page sizes/layouts. Noticed this: constexpr size_t size_bytes() const noexcept { return size() * 2 * sizeof(glm::mat4); ^^^^ not a vec4? } Changing the mat4 to match th...
67,525,808
67,525,983
What is the meaning of .end()->first in maps
Considering this piece of c++ code. Why is the output of mp.end()->first the number of keys in the container. #include<iostream> #include<bits/stdc++.h> using namespace std; int main(){ map<int, char> mp; mp[0]='a'; mp[1]='b'; mp[2]='c'; mp[3]='d'; mp[3]='e'; mp[7]='f'; map<int, char>:...
Probably the best answer is going to come from the reference The end() function returns an iterator past the end of the map. Dereferencing it is undefined, so whatever output you see from this code is irrelevant. What you probably want to do instead is look at end() - 1, in which case the result will be a std::pair of...
67,526,070
67,533,415
I can't compile SimGrid - S4U
How to compile a C ++ simulation in SimGrid? I am using Ubuntu, following the installation steps in the documentation but when I try to test some example of the documentation itself, there are several errors and warnings. I went to the examples folder and tried to run some of the S4U interface, but without success. I t...
Build example: tar xvf simgrid-3.27.tar.gz cd simgrid-3.27/ && mkdir build && cd build/ cmake .. make make tests ## build tests and examples sudo make install The make options https://simgrid.org/doc/latest/Installing_SimGrid.html .. ( Ref. https://simgrid.org/doc/latest/index.html ) and simgrid-3.27/docs/sourc...
67,526,169
67,526,213
Why is it possible to use rvalue references as members without lifetime problems?
Sometimes I see people using rvalue references as members and I always wonder how this is possible and how it doesn't lead to lifetime problems. Take this as an example: class Foo { public: Foo(int&& i) : i_(std::move(i)) { } void printNum() { std::cout << i_ << std::endl; } privat...
The int is destroyed at the end of the expression Foo f{5}; so the program has undefined behavior.
67,527,019
67,527,648
Avoiding need to specify using operator=
I'm attempting to create a base class for creating helpers around various scoped operations, and to do so the base class allows the assignment of a callable. A simple predicate determines whether or not the callable is invoked. Regardless, the dtor is always invoked. The catch is that each derived class needs to explic...
The catch is that each derived class needs to explicitly inherit the operator=. Is there a way to write the base class so that this is not required? No, this isn't possible. The rule is that functions in different scopes do not overload. Since the derived class will always have something named operator= (either the d...
67,527,299
67,692,412
C++ proto2 "expression is not assignable" error
I am trying to figure out how to assign a message field in protobuf2 in C++. Here is a small snippet of the code. message Sub { optional double x = 1 [[default = 46.0]; } message Master { optional Sub sub_message; } Now when I try to initialize a Master message, I got the following error: Master msg; msg.mutable_...
msg.mutable_sub_message() returns a pointer to the field, i.e. a Sub*. The idea is that you use that pointer to manipulate the field as you need. Assigning a different pointer to it wouldn't change the value inside the class, it would at most change the temporary pointer that was returned, which doesn't make sense. I g...
67,527,983
67,531,080
In cmake, can we avoid using find_package to import other packages?
Okay, the title is obviously weird. I hope anyone who can define my curiosity cleanly, would edit the title into proper one. When using CMakeLists.txt, we usually import third-party packages via command find_package() macro, which looks for proper find_XXX.cmake script, and then results outputting variables such as XXX...
can we avoid using find_package to import other packages? You can, but it's the tool to be used just for that. find_package() is basically an include() with some special options. wouldn't this be much cleaner way to describe exported package's compositions, rather than linking and adding those verbose *_LIBS *_DIRS ...
67,528,206
67,528,245
Why does my code need cout for printf() to work?
I'm pretty new to coding and stumbled upon this issue when trying to code a program that prints the biggest number in an array. Basically, if I don't include cout<<i;, the printf() will print the array location instead of the number 20. Any ideas why? (I'm guessing it is something stupid I overlooked, so sorry in advan...
You shadow maxInt by declaring another variable with the same name. See my comments here: int maxinlst(int lst[], int size) { // First declaration int maxNum; for (int i = 0; i < size; i++) { cout << i; if (lst[i] == lst[0]) // Second declaration int maxNum = lst[i]; ...
67,528,577
67,528,706
Why is incrementing a long long much slower than incrementing an int?
I was recently curious to see roughly how many integer increments C++ could handle in a second. To test this, I wrote a short driver program, which is shown below: #include <iostream> using namespace std; int main() { int num = 0; while(++num) { if(num%100000000 == 0) { // prints num every 100 million...
Signed division is accomplished with the IDIV instruction. Per Agner Fog's instruction tables, on the Haswell architecture, the reciprocal throughput of IDIV for 32 bit registers is 8-11, while for 64 bit registers its 24-81. That is, it takes roughly between 2x and 10x longer to do 64 bit integer division when using 6...
67,528,630
67,529,567
How copy existing object and cast the copy into r-value reference in a single expression
Is there a quick and expressive way to make a copy of an existing object and pass it into r-value reference? I've an existing API that takes r-value references as parameter. But I can't change it due to backwards compatibility nor I can overload it because of the shear amount of overloads it have already. For example, ...
You can make a copy like this: foo(+n); or this: foo(int(n)); or in a more generic way like this: foo(decltype(n)(n));
67,528,767
67,529,660
No operator ">=" matches these operands error in c++ when using while loop
Here is the code int main() { int x; while((cin >> x) >= 2){ cout<<"Greater than 2"; } } and I am using these preprocessor directives #include <iostream> #include <ios> #include <string> #include <iomanip> using std::cout; using std::cin; I am getting error in the while loop, it says this: no oper...
In the while condition, you are comparing cin>>x and 2. I believe you wanted to check for conditions where x>= 2. But, in your code, the compiler is comparing the output of cin>>x with 2. As the output of the cin operator is not INT, hence you are getting the error. For more information on this, you can refer to: http...
67,528,855
67,530,512
How to Synchronize function calls with callbacks?
I am using a SDK that provides some functions and one callback to send the results. Code is in C++. SDK APIs: typedef void(*onSdkCallBackFn)(int cmdType, const char *jsonResult); void SetCallback(onSdkIotCallBackFn Fn); void SetCommand(int commandId); There is no return value for SetCommand, so need to wait for SDK to...
Well one way to do it is to e.g. wait on std::condition_variable: int DoCommandNo5() { int result = -1; bool resultReady = false; std::mutex m; std::unique_lock<std::mutex> lk(m); std::condition_variable cv; auto getResult = [&](int commandResult) { resultReady = true; resul...
67,529,776
67,530,163
How to force the C++ only read input that ends with #
I tried to found the answer on google but didn't find anything, so, the task is to create a program that will read input(a string of numbers) only with # in the end ("1234#") and count odd and even numbers. I managed with counter via: char ch; int odd_number, even_number; odd_number=even_number = 0; printf("To leav...
What you need to do is: Do all operations in a loop, until user input contains a '%' Inform user what to do Read a complete input line from the user Check, if that is a none empty string, consisting of digity and having an # at the end If the line does not fit to the requested format, then ignore it Count odds. The nu...
67,530,104
67,548,725
Compare multiple chars without using string compare functions
I am trying to create a switch statement using the parameters that can be passed into my File classes constructor in the mode parameter. However, as mode can be up to 2 chars ('r', 'r+', 'w', or 'w+'), I do not know how to create a switch statement that will get this done for me. Does anyone have any suggestions on how...
You can't use more than one value in case. 1 - You can use more than one switch: switch(mode[0]){ case 'r': switch(mode[1]){ case '+': switch(mode[2]){ case 0: fileMode = O_RDWR | O_CREAT; canWeRead = true; ...
67,530,177
67,530,341
Which is the preferred way to clear a std::string object?
#include <string> using namespace std::literals; int main() { auto str = std::string{}; str.resize(1024); // #1 str = {}; // #2 str = ""; // #3 str = ""s; // #4 str.clear(); // #5 str.resize(0); str.shrink_to_fit(); } Which is the preferred way to clear a...
The correct answer to your question Which is the preferred way to clear a std::string object? (and you knew this before asking), is #4, str.clear();, since this clears the string. #1 is initialization #2 and #3 are assignments #4, the answer, clears the string #5 resizes the string You can copy and paste your code ...
67,530,327
67,530,411
is Destructor really destroy memory or just runs before the lifetime of object is going to end?
there are few question like this but not exactly same so please care to read whole question before cast it as duplicate one 1. objects created using new keyword (dynamic objects). we explicitly use delete keyword to de-allocate there memory. so when program encounter delete keyword it get sense that object is going t...
or just runs before the lifetime of object is going to end? To be clear: The lifetime of the object ending and the calling of the destructor happen in the same point in time, not one after the other. is destructor de-allocate there memory ? Not necessarily. See following example for details. if destructor do not ...