question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
63,260,951
63,261,026
C++ C4834 error moving from VS2017 to VS2019
I am getting this warning, until now I didn't get any warning : error C2220: the following warning is treated as an error warning C4834: discarding return value of function with 'nodiscard' attribute template <typename T> static void quick_hull(std::vector<T> &points) { points = hull(points); // Remove succe...
std::unique does not remove elements. It only reorders them in such a way that all unique values are moved to the front. Then it returns an iterator pointing to the element after the last unique value. You need this iterator to actually remove the duplicate elements with a container specific method. Without it you don'...
63,261,135
63,277,532
Missing bytes in between data during allocation of values
I have a packet of data and when i assign that data to variables bit by bit as per the requirement, it is missing some bytes in between. Don't know why? I am working in c++. For Example, I have structure like: struct __attribute__((packed)) { uint32 varA:9; uint32 varB:10; uint32 varC:9; uint32 varD...
I got the solution as the @StephenDuffy said, i am missing pragma directive. After adding that, the code works fine for me. the pragma directive is as:- #pragma pack(push,1) and ending it as:- #pragma pack(pop)
63,261,258
63,261,315
while vs for statement different behavior
I'm trying to understand why this while loop works as expected, but the equivalent (in my mind) for loop does not. #include <iostream> #include <fstream> #include <vector> using namespace std; int main() { ifstream ifs{ "loop-in.txt" }; if (!ifs) perror("can't open input file "); vector<int> ys; ...
for (int y; ifs >> y;) // <-- Read here. { if (!(ifs >> y)) // <-- And read here, overwriting read above. break; ys.push_back(y); // <-- Only pushes every second one. } There are two reads in every iteration of that loop, the first in the for statement, the second in the loop body. That means yo...
63,261,388
63,261,839
will compiler optimize out constructor call
If a constructor B() is called to create a temporary object, e.g. in a call f(B().name()), will the construction of B always carried out, or are compilers permitted and able to optimize out unnecessary allocations that go along with object creation? Specific example: class A { public: virtual std::string name() = ...
A compiler may completely remove a call to constructor just like any other function. While an instance of B is necessary for the code to be semantically correct, it doesn't mean that after compilation it needs to exist (as a piece of memory). Also remember that a call to constructor is not the same as allocation. So as...
63,261,654
63,261,725
Getting different sizeof values of the same array in main and in a function
In the following code, when I print sizeof(arr) in main(), I get output 32. However when I send the same array to a function print() and print out sizeof(arr), I get 8. My question is, shouldn't they both be 8, because arr is a pointer to the first element in both cases? Code: #include <iostream> using namespace std; ...
My question is, shouldn't they both be 8, because arr is a pointer to the first element in both cases? An array name is not a pointer. In main, where arr is declared and initialized you will get the real size of arr, which in your case is 32 bytes, 8 times(the number of elements) 4(your system int type size). sizeof ...
63,262,032
63,280,194
How to create a map from initializer_list with non-copyable members in C++?
So, I have a map that stores objects of a class with deleted copy constructor, due to it having a unique_ptr as one of the members. I'm trying to construct this map using std::initializer_list, but I'm getting a huge error, ending with "use of deleted function 'constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _...
So, I worked a bit on the constructor and managed to come up with the solution myself. As my objects are not copyable, there were no downsides to making a second argument of the initializer_list's pair an rvalue. std::initializer_list<std::pair<const std::string, ExitMessage&&>> However, now I couldn't use a default co...
63,262,961
63,263,183
check boundries in random iterator implementaion postfix and prefix
I'm trying to implement Vector class Iterator (similar to stl classes) and I'm not sure if I need to check boundries before I increases/ decreases the iterator. If I dont need to check so what happens if there is an exception, and if I do need to check whan happens if there is an exception?
The standard doesn't require std::vector::iterator::operator++ check. Incrementing it past end, or decrementing past begin is undefined behaviour. Undefined behaviour doesn't mean "throws an exception". Because it is undefined, an implementation that throws is valid, and so is an implementation that reads adjacent memo...
63,263,194
63,263,815
sorting strings with heap sort | C++
I'm new to c++ I have a problem with my code I want to sort an array of string. with selection sort, it works but with heap sort, there is a problem that nothing gets printed out (i also have this problem with merge sort) I think the problem is strcmp(), but IDK how to fix it #include<iostream> #include<cstring> #defin...
Several problems in your code. Starts with heapify(): You are calculating the left and right of a heap element as- l = 2 * i; r = 2 * i + 1; Assume that i is 0. In that case, it will give l as 0 which is incorrect. It should be l = 2 * i + 1; r = 2 * i + 2; Here, if(largest != i){ std::strcpy(arr[larges...
63,263,460
63,263,529
I'm getting error expected primary-expression before '=' for my for loop
#include <bits/stdc++.h> using namespace std; void SieveOfEratosthenes(int num) { bool pno[num + 1]; memset(pno, true, sizeof(pno)); for (int i = 2; i* i < = num; i++) { if (pno[i] == true) { for (int j = i * 2; j < = num; j + = i) pno[j] = false; } ...
Try removing space before =. for(int i=2; i*i<= num; i++) { ..
63,263,518
63,263,644
How can I find the code line where is located the code that put a yellow square in a windows control?
I am working with WinAppDrive library https://github.com/microsoft/WinAppDriver. If someone have worked with that library know that it is usefull to capture user actions, generate the code that replicate those same actions and finally implement that code that replicate those actions. I have a problem: I need to get th...
I searched for "Yellow" in the repository. Maybe the result in "Tools/UIRecorder/UIXPathLib/UiTreeWalk.cpp" is what you are looking for? void DrawYellowHighlightRect(HDC hdc, RECT rc) { HBRUSH hBr = SelectBrush(hdc, GetStockBrush(NULL_BRUSH)); int YellowInflat = -2; if (rc.bottom - rc.top < 30) { ...
63,263,775
63,263,899
Vector.push_back(std::function<void()>); way around compiler asking for expression
If I wrirte: Vector.push_back(std::function<void()>); Compiler tries to interpret it as the expression and fails.. My way around was: std::function<void()> fun; Vector.push_back(fun); Is there a way to fix this in one line?
It's the same reason why this: std::vector<int> vec; vec.push_back(int); won't work. You need an object, not a type: std::vector<int> vec; vec.push_back(int{}); // notice the {} Similarily, your: Vector.push_back(std::function<void()>); Tries to push a type, not an object. Create one the same way: Vector.push_back(s...
63,263,946
63,265,161
Finding minimum cost to reach the end of array
An array of costs was given. You can either take two jumps forward or one jump backward. If you land on a particular index, you have to add the cost to your total. Find the minimum cost needed to cross the array or reach the end of the array. Input: 5 (Number of elements in the array) [9,4,6,8,5] (Array) 1 (Index to ...
You can use recursive program with Dp //cur will the final destination that is last element at first execution //N is no of elements int Dp[N]={0}; Dp[0]=element[0]; //initial condition least_path(cur,*elements,N) { if(cur>N-1 || cur<0) return INT_MAX; if(Dp[cur]) return Dp[cur]; int temp1=least_path(cur...
63,264,371
63,264,855
How to extract data from string in C++
Note: I am working using C++11 standard I am looking to write a function that handles the following problem: Given the following input: a,b,c I want it to print a and b and c Given: a,b,c, I want it to print a and b and c and "" Given: ,a I want it to print "" and a Given , it should print "" and in case of empty strin...
While you could implement such a function, I'd strongly suggest using existing solutions. There are quite a few. I'm personally used to absl::StrSplit() (see https://abseil.io/docs/cpp/guides/strings) which by default will do what you want. Thomas Sablik also wrote in a comment: You can use boost::algorithm::split or ...
63,264,500
63,265,816
The graphics.h library when used , shows objects inverted and also inverts the coordinates too
I tried to write a code to draw a triangle with its base facing downwards, using the following program: #include<graphics.h> #include<conio.h> using namespace std; int main() { initwindow(400,400,"Triangle"); line(100,100,200,300); line(200,300,300,100); line(100,100,300,100); getch(); return 0...
It seems that you are using a library which supports the Borland Graphics Interface (BGI). In BGI the origin is the top left of the screen, as S.E.C.H surmised. Here some documentation: Each pixel is specified by its row and column position where coordinates (0, 0) corresponds to the pixel in the upper-left corner of ...
63,264,878
63,265,037
Simple cuda kernel add: Illegal memory after 2432 kernel calls
I build a simple cuda kernel that performs a sum on elements. Each thread adds an input value to an output buffer. Each thread calculates one value. 2432 threads are being used (19 blocks * 128 threads). The output buffer remains the same, the input buffer pointer is shifted by threadcount after each kernel execution. ...
static int aggregate(int* array, size_t size, int* out) { size_t const vectorCount = size / 2432; for (size_t i = 0; i < vectorCount-1; i++) { array += vectorCount; } } That's not vectorCount but the number of iterations you have been accidentally incrementing by. Works fine while vectorCount <...
63,264,996
63,269,214
WinAPI CryptBinaryToString without a null-terminator
I'm using a string as both the buffer and the output for WinAPI's CryptBinaryToString. When the function writes to the buffer, it writes an extra null terminator for the allocation (and needs it as such). DWORD size; CryptBinaryToString(..., &size, ...); std::string buf; buf.resize(size); CryptBinaryToString(..., &buf...
There is no way to ask CryptBinaryToString() to omit outputting a null terminator. However, resizing a std::string to remove trailing characters (whether you use resize(), erase(), pop_back(), etc) will not reallocate the std::string's data, it will merely decrement the value of its size() so that subsequent operations...
63,265,195
63,265,468
I am trying to use template metaprogramming to find the greatest common divisor, but the compiler reports an error
I am trying to find the greatest common divisor using template metaprogramming, and encountered some problems during the process. Please see the code, errors and other information: C++ code: #include <iostream> namespace meta{ namespace _algorithm{ template<bool size_,long long A_,long long B_> stru...
Too much code and compiler does not know which template specialization to use. But first template param can be omitted. Let's assume that first number is always bigger and keep this assumption during all instantiations: #include <iostream> template<long long A, long long B> struct GCD; template<long long A> struct GC...
63,265,270
63,265,546
Convert char* into char [ ]
Hello dear Internet :D So i coded a "Text to morse" translator which worked well. Now i want to do the same with an arduino. The morse code should be shown by a blinking led. My problem ist that i have a const char* morse[]={"....", ".-", ".-..", ".-..", "---"}; which i cant convert or reassign to a new variable char s...
You cant assign strings, and it is not needed here for(int i=0;i<b;i++) { showtime(letters[toupper(sentence[i])-'A']); } void showtime(const char *code) { while(*code) { if(*code++ == '1') { digitalWrite(SHORT, HIGH); delay(50); digitalWri...
63,265,586
63,265,647
Does C++ std::hex reverse bytes order? (printing decimal as hexadecimal)
I'm having some trouble understanding the following C++ code: std::cout << std::hex << 61183 << std::endl; // prints eeff I'm working on a little-endian machine (Intel x86-64), and I wanted to understand, at bit and byte level, how that result is produced, so I wrote the following table for a least significant bit arc...
Endianness is about how to store numbers in byte-addressed memory. On the other hand, std::hex produces hexadecimal text. 0x1000 * 14 + 0x100 * 14 + 0x10 * 15 + 0x1 * 15 == 61183, so 61183 is EEFF in hexadecimal. This won't be affected by endianness.
63,265,801
63,265,932
Default Visual Studio C++ Console App has 409 errors
I am attempting to start learning C++, however, Visual Studio 2019 Community Default Console app has 409 errors when I start it, and will not compile. The default project: Presssing "Local Windows Debugger" My Visual Studio Installation
Check your sdk version in your visual studio installer. Then set the version in Properties -> General Configuration -> Windows SDK
63,266,065
63,266,224
Why is my worker working in a wrong thread?
I have a class Messenger with two internal object pointers: std::unique_ptr<QThread> stdin_receiver_thread_ = nullptr; std::unique_ptr<ReceiverWorker> stdin_receiver_ = nullptr; In the constructor of the Messenger I create these objects and assign them to these smart pointers like so: Messenger::Messenger(QObj...
It's doing exactly what it should. The term stdin_receiver_thread_.get()->thread(); yields the QThread in which stdin_receiver_thread_ as a QObject lives. In other terms your main thread or wherever Messenger was constructed. If you had instead just written: qDebug() << "stdin_receiver_thread_:" << stdin_receiver_threa...
63,266,912
63,267,091
What is the meaning of assigning to return value of getter taking this pointer by value?
This doubt came to me when I jumped on an existing code and mistakenly used a getter to set a property, obj.getProp() = otherProp; instead of calling the setter, obj.setProp(otherProp); I did not realize the mistake because there was no error at compilation or runtime; the assignment resulted in a no-op. So I came up...
what in b.getAbyVal() = A{7}; is different from b.getXbyVal() = 3; so that the former compiles and the latter doesn't (beside the fact that the types are A and int)? Surprisingly, the difference in types is exactly what makes one compile correctly, and other to fail. A has an assignment operator defined for it, so co...
63,267,194
63,267,313
NULL returned from a function that returns an abstract class
I have an abstract class called Item and a function Item function(int x,int y); my question is can I return a NULL from that function?
Because you declared the return type as the class instance, no, you cannot return a pointer. NULL (should be nullptr) is a pointer. If Item is an abstract class, the proper function design would be: Item* function(int x,int y);
63,267,296
63,267,339
C++ modifying const pointer reference value
I've encountered similar code piece today and it got me wondering. I did a little experiment myself as shown below. Why does the first stuff function with shared pointer allow to modify the value while seconds one doesn't? #include <memory> void stuff(const std::shared_ptr<int> &var) { *var = 5; } void stuff(cons...
These two types: const std::shared_ptr<int> const int* (aka int const*) are fundamentally different: The first one is a const pointer to an int; The second one is a pointer to a const int. The shared_ptr equivalent of the version that doesn't permit modification of the pointee would be std::shared_ptr<const int>. T...
63,267,321
63,268,516
What is the purpose of echo command after executing a program?
Why do we exit issuing an echo command while executing a program? As far as I know, the echo command for console windows is: $ echo $ And for windows is: $ echo %ERRORLEVEL%
When the child process ends, the set variable ERRORLEVEL contains an integer returned by it. ERRORLEVEL is measured 0 if the process was successful (i.e. return 0). OTOH, 1 or greater if the process encountered an error. However, I don't know what do you exactly mean by: echo command after executing a program I never...
63,268,087
63,268,269
Atomic struct containing pointer
#include <atomic> #include <iostream> using namespace std; struct Simple{ int a = 0; int b = 0; }; struct WithPointer{ int *a = nullptr; int b = 0; }; int main(int argc, char const *argv[]) { atomic<Simple> simple; cout<<simple.is_lock_free()<<"\n"; atomic<Simple*> simple_p; cou...
You need to compile the program with the -latomic flag on clang and gcc. demo.
63,268,408
63,268,940
Using Preprocessor DATE dynamically
I'm trying to use __DATE__ in C++Builder, and I need to use it dynamically. For example, if a user click on a button, the label containing __DATE__ will update following the system date. I did that for now: label1->Text = "Data: " __DATE__; This is in a function to set the date, called DateTime(). For the button I al...
__DATE__ is a compile-time constant. It is the date on which the .cpp file is compiled. This is not what you want in this situation. C++Builder's RTL has a Sysutils::Date() function that you can use instead, eg: #include <System.SysUtils.hpp> label1->Text = _T("Data: ") + Date().DateString(); Date() returns a TDate...
63,268,716
63,268,990
class name as return type & use of this pointer
I was learning about the this pointer, and I came across the below code. Can anyone explain what the code does? What does *this mean? Why does setX() have a return type as class Test? What is the purpose of placing & before setX() and setY()? #include<iostream> using namespace std; class Test { private: int x...
With the following syntax: obj1.setX(10).setY(20); ^^^^^^^^ assigning y, returning the object obj1.setX(10) ^^^^^^^^ assigning x, returning the object obj1 a successfully initialized object In Test& setX(int a): Test& setX(int a) { x = a; return *this; } When the call that func...
63,269,126
65,251,509
Deterministic Library Build Using CMake
I've created a simple CMake C++ library example and I want to make its build deterministic (i.e. The same code in same machine always generates the same library with same file hash). Main.cpp #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } CMakeLists.txt cmake_min...
CMAKE_CXX_ARCHIVE_FINISH worked for me. CMakeLists.txt : cmake_minimum_required(VERSION 3.10) project(Test) SET(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> -crD <TARGET> <LINK_FLAGS> <OBJECTS>") SET(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> -rD <TARGET> <LINK_FLAGS> <OBJECTS>") SET(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARG...
63,269,489
63,269,610
How to pass std::sqrt as an argument
Im trying to create a generic function Foo that will accept an argument and Op what will be applied to it. template <template<class> class Op> float foo(float boo) { return Op(boo); } template <template<class> class Op> float foo(float a, float b) { return Op(a, b); } void caller() { float boo = 2.3...
You can't pass an overload set as a template argument. A simple workaround could be to wrap sqrt and exp into functors with a templated operator(): struct Sqrt { template<class T> T operator()(T t) const { return std::sqrt(t); } }; struct Exp { template<class T> T operator()(T t) const { return std::ex...
63,269,795
63,270,208
Efficiently Capture Frames in DirectX 11
I'm trying to capture every frame of a game I am playing. There are plenty of good screen capturing softwares out there, One of which is built right into Windows 10. However I need a custom approach for different reasons. I'm currently using the DirectX Tool Kits SaveWICTextureToFile() method to save every frame produc...
If this is being done in a debug build I suspect that the stringstream has logic that is causing the problems, I suggest using character arrays instead and swprintf. Even better if you keep track of where the directory ends and so only need to write out the file name part (you could go even further and make it so you o...
63,269,989
63,270,084
CMake header file that includes header files from other directory
Given this tree: project + lib + include + include_both.h + source + file1.cpp + file1.h + file2.cpp + file2.h + main_dir + main.cpp After linking lib to main_dir with CMake, I would like header files file1.h and file2.h to not to be visible from main.cpp. I want t...
You might try making the include directory a PUBLIC one, so it is visible to consumers of the library, but keep the source directory private: add_library(MyLib SHARED source/file1.cpp source/file2.cpp ) target_include_directories(MyLib PUBLIC include PRIVATE source )
63,269,998
63,270,116
Understanding the MIPS equivalent of this C++ code
How would you replicate: int* a; b = a[2]; In MIPS, without using .data? My answer for this was: lw $t1, 4($t0), where $t0 is a & $t1 is b--but this was incorrect. Similarly, how would you replicate: char* a; a[4] = b; Once again, my answer for this was lb 4($s0), $t0, where $t0 is b & $s0 is a--but this was also inc...
To replicate int* a; b = a[2]; a[2] is 2 elements after what is pointed at by a, so lh $t1, 4($t0) if int is 2-byte long and lw $t1, 8($t0) if int is 4-byte long. To replicate char* a; a[4] = b; The instruction to write 1-byte value to memory is sb, not lb. Therefore, sb $t0, 4($s0) should do assuming char is 1-byte ...
63,270,037
63,270,216
C++ anonymous string destruction time
We have a function GetString() that returns a std::string. We then have a function ConsumeString(char*) that consumes a C-style string. Is it a bug to write ConsumeString(GetString().c_str())? To me it looks like this would be a bug because after c_str() runs, the original anonymous string will get destructed and you...
Unless ConsumeString does some asynchronous processing of const char* provided to it (directly or indirectly) this code is very safe. A temporary returned by GetString() will be alive until the function ConsumeString returns, so if it is done all it's business with it's argument before returning, everything will work c...
63,270,366
63,271,740
A trick to enable casting over non-public inheritances
This is a followup related to my previous question where I investigated the problem and found that up- and downcasting seem to be working correctly over public inheritance relations. For example, this code does not even compile: class A { }; class B : protected A { }; int main() { B b; static_cast<A*>(&b); }; G+...
Conceptually getA is fine. B is choosing to expose the A in it. It can be simplified to return this;, the cast is unnecessary. I have reservations about fromA, because it is implying that all As are Bs, which might not be true. You should limit the accessibility of fromA to places where you can prove all the As are Bs....
63,270,458
63,270,898
Bad alloc exception thrown when using SVD from Eigen library
In my application, I want to obtain the left singular vectors from a given data matrix with double entries, which is given in the code as Eigen::MatrixXd m; and has dimensions 45 x 904140. Now I use the constructor for the SVD decomposition in the Eigen library as below Eigen::BDCSVD<Eigen::MatrixXd> svd(m, Eigen::Com...
The error std::bad_alloc usually means there is not enough memory to complete your task. You might not be able to compute the matrix that requires a 904140 x 904140 on your machine.
63,270,746
63,273,337
Adding a shortcut to QAction inside QGraphicsScene context menu
My QGraphicsScene subclass WorkspaceScene contains a variable for each action that it later uses inside the context menu. I have a function that sets up the actions and adds the shortcuts (which is called in the constructor of the class), and then I have a function that creates the context menu, which is called in the ...
I solved it by adding the QAction to the QGraphicsView parent of the QGraphicsScene.
63,271,762
63,271,949
Why does the replica work replace in c++?
I started learning C ++ and my task is to replace some characters in the text. Something similar to the template Here are some examples: <h1>Title</h1>$ js $<p>text...</p> result: <h1>Title</h1> </script>alert(1)</script> <p>text...</p> I tried to do it with this code, but nothing worked: #include <iostream> #include...
The second parameter of std::string::replace(size_type pos, size_type count, const basic_string& str); is the length of the substring that is going to be replaced e.g. how many characters should be removed after pos and before inserting str. You want to replace just 6 characters. Your code shoul...
63,272,460
63,272,621
Passing parameters to constructors with no parameters
I am trying to understand the what the program I am using is doing. Below, I included the relevant pieces of the code. An pointer of class StAnaPars is created: StAnaPars* anapars12 = new StAnaPars; The program accesses several members of anapars12 to set different analysis parameters. Then, another pointer of class St...
This code is using the copy constructor. A copy constructor is a constructor declared as T(const T& other). It can be user defined or, when no user defined copy constructor exists, it is implicitly defined and does a member-wise copy. If you want to explicitly disallow copying, you can declare the copy constructor as: ...
63,273,531
63,273,665
how can I access data from class through another class in c++?
Suppose there are three classes A, B and C and they are connected in a way that A has an object instance to B, and B has an object instance to C (A->B->C). Each of the classes has private data members, getters and setters. How can I get a value from class C to class A? The code example: class C{ private: int q = 3;...
Obviously you would not be able to directly access objC since it is set privately in objB. Another simple solution on top of the one you mentioned, which would kill the purpose of setting objectB to private, would be to create additional getter functions in objB that would call the corresponding getters in objC instead...
63,273,765
63,273,871
Conditionally constexpr expressions with if constexpr
Suppose you have a function template that calls another function, which may or may not be a constexpr function depending on a template parameter. C++ allows the callee to be declared constexpr anyway, as long as at least one possible instantiation produces a constexpr. For example: template <class T> constexpr bool ba...
It doesn't "degrade" for the same reason that this doesn't degrade: constexpr auto value = expression; If you declare a variable to be constexpr, then you mean it. You mean that its value is a compile-time constant, and the compiler will perform constant evaluation to generate its value. The same goes for if constexpr...
63,274,417
63,274,509
Can I use pointer in for loops in c++?
I know I can have any type in for loop to iterate over: #include <fstream> #include <iostream> using namespace std; int main() { int ar[] ={ 1, 2, 3 }; for (int i:ar) { cout << i << endl; } } But I could not have an pointer type: #include <fstream> #include <iostream> #include <string> using...
The difference in those samples is hidden inside the rules of passing parameters to functions. In the first example, when you write int ar[] = {1, 2, 3};, the type of ar is int[3] - "an array of 3 ints". std::begin is defined for arrays, so the code compiles and works. In the second example, char const *argv[] is actua...
63,274,518
63,274,718
Default template parameter with a default value?
We can have the following and it is valid: template<std::size_t Size = 10> fn(){...} template<typename Size = std::size_t> fn() {...} But how to do this? template<typename Size = std::size_t=10> fn() {...}
You could require that your parameter be a specialization of std::integral_constant (or some other type that provides both 'type' and 'value' members: template<typename Arg = std::integral_constant<size_t, 10>> struct foo { }; but in general I would say the two parameter method is preferable.
63,274,541
63,274,594
Vector that contain other vectors with a float and another vector of ints
I'm trying to create a vector that contain others vectors with a float and other vector of ints. Expected result: {{5.4 {1, 5, 4, 6, 9}, 4.8, {3, 6, 7, 8, 4}, 7.3 , {9, 12, 1, 0, 4}} This is one of my tries: #include <iostream> #include <vector> using namespace std; void _cost(){ vector<float, vector<int>> res...
It seems you want to create a vector of structures that have float and vector of int; #include <iostream> #include <vector> struct my_data { float hoge; std::vector<int> fuga; }; int main() { std::vector<my_data> result = { {5.4 , {1, 5, 4, 6, 9}}, {4.8 , {3, 6, 7, 8, 4}}, {7.3 , {...
63,274,544
63,280,979
Is it possible to initialise a static member in a static method of a class in C++?
So I have the static member precision and a public static method to set its value in my class (the code below is stripped down a lot). class Foo { private: typedef unsigned short precision_t; static precision_t precision; public: static void set_precision(precision_t value) { precision_t precision =...
Updated code: #include <iostream> using namespace std; class Foo { private: typedef unsigned short precision_t; static inline precision_t precision; //static precision_t precision; //when not using static inline public: static void set_precision(precision_t value) { //precision_t precision = v...
63,274,910
63,275,138
find the maximum and minimum value in vector
I want to do is to check whether an maximum and minimum element of x. i have address adress was vector written top of the code x stand for first number , t for row and i for column. want compare x value, and get maximum and minimum number which is between the 0 and 100 [28,13],[48,10],[48,81],[48,54],[48,0],[10,20] [48...
Let's assume we have a vector of x/y pairs, and we want to find those that have the smallest and largest x values. We could do this with std::minmax_element (or std::minmax, though in this case it's a tiny bit clumsier, IMO), something on this general order: #include <vector> #include <algorithm> #include <iostream> s...
63,275,036
63,288,283
CMake claims finding OpenGL but can't find EGL and OpenGL::GL
CMake is giving me confusing results when trying to find OpenGL on Ubuntu. The context is I need to do headless rendering on the server / docker without X display. I have installed OpenGL via apt-get install libgl1-mesa-dev and apt-get install libegl1-mesa-dev. Here is the relevant part in my CMakeLists.txt: cmake_mini...
As per the helpful comment of @Tsyvarev, this output is due to the wrong version of CMake. I forgot to link it but the documentation of FindOpenGL I look at is for version 3.18.1 while I required the min CMake version to be 3.5.1. In 3.5.1, there's no COMPONENTS part. Also OPENGL_FOUND does not check for EGL.
63,275,038
63,275,296
Leaking memory when calling exit(0)
I read before that: When you exit a C++ program by calling the exit() function, the object destructors are not run. This can result in Valgrind reporting memory leaks. But what if I'm waiting for user input and if it's exit then I want to exit the program, how may I do that? I am scanning input in a function called b...
According to cppreference: Returning from the the main function, either by a return statement or by reaching the end of the function, executes exit(), passing the argument of the return statement (or ​0​ if implicit return was used) as exit_code. In other words, calling exit is the same as returning from main (or fal...
63,275,170
63,275,276
sregex_token_iterator: Stroustrup example has errata?
I'm testing an example from Stroustrup C++ 4th Ed Page 1069, which may have unlisted errata here. Does anyone know how this code should be modified to correctly print the output below? The book claims this should be the output, however my test outputs nothing (no matches). #include <regex> #include <iostream> using n...
regex pat {R"((\w+)([[:punct:]]+)(\w+)\s∗)"}; Your "asterisk" at the end is not an actual * asterisk, but the Asterisk Operator Unicode character U+2217 instead. Replace it with a * and the code will work.
63,275,187
63,275,228
Looping over values in dynamically allocated arrays in c++
I came from python and I'm trying to learn c++ now, and I'm trying to print something that looks like python's list = [1, 2, 3] in c++. I let user to chose a size of array and insert a numbers inside and after that I would like to cout the result in above fashion, but I'm not able to loop over values in array because t...
If you use a std::vector instead of a C-style array, then you can iterate through it with a range-based for loop, like so: #include <vector> #include <iostream> int main() { int i; std::cout << "How many values?"; std::cin >> i; std::vector <int> v; for (int n = 0; n < i; n++) { std::cout...
63,275,325
63,275,508
Why is there a conversion error in this code?
I'm just making a program and this happens I don't understand where is converts like that. This program is supposed to see how many of each character is in a input string. It is work in progress but I already made a for loop to process the input. Error: 11:30: error: conversion from 'int' to non-scalar type 'std::vecto...
Your mistake is that you try to call constructor with 2 parameters, using assign without explicitly showing what are that 2 ints mean. You can choose 2 ways of this implementation: vector<int> letters = vector<int>(26, 0);//here you call copy constructor vector<int> letters(26,0); // here you call constructor with 2 ...
63,275,405
63,275,874
What is referencing the copy constructor?
Depending on how I construct my Log object, I get a compiler error stating that I'm trying to reference a deleted function (the copy constructor): C:\Projects\Logger\src\Logger.cpp(34,1): error C2280: 'Logger::Log::Log(const Logger::Log &)': attempting to reference a deleted function [C:\Projects\Logger\build\Logger.v...
It's not just about the unnecessary copy and C++17, we know that Logger::Log foo("sample.log"); works fine but why this flags C2280 Error Logger::Log foo = Logger::Log::Log("sample.log"); the problem is in ofstream that is in the class, I got your code and I compiled it, I had a doubt about ofstream object, I ...
63,275,410
63,276,001
How to make my "subscripted value" an array in c++
I am progressing on my "vending machine" code where users are able to add an unlimited amount of items to the cart until they press 0 to checkout. I ran into a problem with the array cost[item] in my "do-while" loop where it says "subscripted value is not an array, pointer, or vector." Could someone please help me with...
I will try to help you sort out where you did mistakes: About cost[item]: Maybe you already hear about "scope". It's about location of your variables, pointers, etc. In your program you declared float cost[5] = {2, 3, 2.50, 1.50, 1}; in global scope. This scope is where you declare something outside the main function....
63,275,446
63,275,485
Behaviour of delete on novtable base class without a virtual destructor
As I understand it, if you call delete on an interface pointer (or more specifically a base class pointer, pointing to a derived class instance), and that declaration does not have a virtual destructor, then the resulting behaviour is undefined, and the destructor of the derived object does not get invoked. class ITest...
The effect of __declspec(novtable) is to omit initialization of the vtable pointer in the constructor and destructor of a class. Since the vtable for a pure virtual interface is mostly useless anyway, this is a code-size-reduction technique. It only affects the availability of virtual functions within constructors, so...
63,275,557
63,276,251
How can I ensure that the virtual memory address allocated by VirtualAlloc is between 2-4GB
I tried to use while, but the effect is not very good. Is there any way to do it? bool found = false; uintptr_t memaddr = 0; int n = 0; while (!found && n < 10) { n += 1; memaddr = (uintptr_t)VirtualAlloc(0, 4, MEM_COMMIT, PAGE_EXECUTE_READWRITE); int g = memaddr / 1024 / 1024 / 1024; cout << "memaddr: ...
Use the lpAddress parameter of VirtualAlloc #include "pch.h" #include <iostream> #include <Windows.h> #include <TlHelp32.h> #include <Psapi.h> using namespace std; MODULEINFO GetModuleInfo(const wchar_t* name) { MODULEINFO mi{ 0 }; HMODULE hMod = GetModuleHandle(name); GetModuleInformation(GetCurrentProce...
63,275,672
63,290,898
Eigen and Numpy -> Passing Matrices from Python to C++
I'm working on a simulation project, and I'm trying to figure out the best way to pass matrices between Python and C++. I'm using Python's NumPy and C++'s Eigen library, and I'm using PyBind11 to get them to communicate with eachother. In my code (see below), I first create some arrays using NumPy in my Python script, ...
Figured out a compromise! I'm going to copy the values from Python to C++ once, and then just past references to the data from C++ to Python.
63,275,992
63,276,098
length of char array using dynamic allocation
Here is my code #include<iostream> #include<string> using namespace std; char* getString(char*& s) { string str; getline(cin, str); int length = str.length(); s = (char*)malloc(length); for (int i = 0; i < length; ++i) s[i] = str[i]; return s; } void main() { char* s; getString(...
When you have an array of characters the very last byte is called the null terminator, which is \0 in this case. Its what tells your program where the end of the characters in an array are. The str.length() function returns how many bytes are in a string. A null character does not count as a byte. So when str.length() ...
63,276,055
66,346,538
In C++ Core Guidelines Per.4, why is the bad example intended to be faster?
I am reading this recently, which states: Don’t assume that complicated code is necessarily faster than simple code. The code is copied as following: Example, good // clear expression of intent, fast execution vector<uint8_t> v(100000); for (auto& c : v) c = ~c; Example, bad // intended to be faster, but is of...
Compilers would attempt to vectorize operations by performing multiple operations at once using SIMD instructions (SSE/AVX on x86-64, others on other platforms). By vectoring manually using uint64_t you make the compiler performing 8 operations at once, which you see as an improvement in debug build, but may prevent it...
63,276,295
63,279,243
How to split a string by emojis in C++
I'm trying to take a string of emojis and split them into a vector of each emoji Given the string: std::string emojis = ""; I'm trying to get: std::vector<std::string> splitted_emojis = {"", "", "", "", "", "", "", ""}; Edit I've tried to do: std::string emojis = ""; std::vector<std::string> splitted_emojis; size_t p...
I would definitely recommend that you use a library with better unicode support (all large frameworks do), but in a pinch you can get by with knowing that the UTF-8 encoding spreads Unicode characters over multiple bytes, and that the first bits of the first byte determine how many bytes a character is made up of. I st...
63,276,423
63,276,475
How to safely "pop-front" from std::map without extra copy?
I have a std::map object. std::map<std::string, std::string> m; m.insert({ "abcd", "foo" }); m.insert({ "1234", "bar" }); and I want to get and remove the first element, like: auto iter = m.begin(); auto [key, value] = std::move(*iter); m.erase(iter); do_something_with(key, value); Is this considered safe? (Moving f...
Is this considered safe? On the condition that the map isn't empty, yes. However, note that the key will be a deep copy; not moved one. This is because the the key of the map element is const. How to safely “pop-front” from std::map without extra copy? It is possible to move from the key too, if you use the extract...
63,276,462
63,278,337
C++ cannot convert Student* to DYNVECTOR<Student,24>::Node* in initialization
Im trying to create an iterator for my dynamic vector class that i've implemented, The thing is I keep getting this error when I try to initilaize some student class for testing purposes on some assignment for the iterator, I cannot figure out why Im having this error wasted alot of hours on it and its impossible to fi...
The Problem inputIterator begin() { return inputIterator(pa);} is calling inputIterator's constructor Iter(T *N ) : _pointer(N) { } with a pointer to a T, a T *. Iter takes T * happily, but it tries to store that T * into _pointer and _pointer is defined as Node *_pointer; which is NOT a T *. The assignment fails be...
63,276,609
63,276,662
If the only input is a String and an additional String is created, is the function O(n) space complexity?
For example: string longestPalStartingAtIndex(string s, int index) { int i = index - 1; int j = index + 1; while (j < s.size() && s.at(index) == s.at(j)) j++; while (i >= 0 && j < s.size()) { if (s.at(i) == s.at(j)) { i--; j++; ...
Yes. You're correct. The code you've shown has O(s.size()) space complexity. Arguably the function calls to longestPalStartingAtIndex will also copy s and require space, but in the end we're talking about O(some_constant * s.size()) so it is still O(s.size()).
63,276,697
63,278,813
How to implement vector::clear()? (study purpose)
I'm trying to implement my own vector class (for study purpose). Currently I am stuck at vector::clear(), how can I implement it? It can't be like this, right? void clear() { for (size_t i = 0; i < _size; ++i) { _data = 0;//can't work with custom class } } Or void clear() { delete[] _data; _dat...
If you keep a capacity larger than the size this means you need to account for allocated memory that doesn't hold any object. This means that the new T[_cap] approach simply doesn't work: first and foremost your vector won't work for objects that are not default constructible even for those that are, you will be creat...
63,276,752
63,279,357
Cost Analysis of Recursive Pascal Triangle Program
#include<iostream> using namespace std; int pascal(int row, int col) { if (col == 0 || col == row) { return 1; } else { return pascal(row - 1, col - 1) + pascal(row - 1, col); } } int main() { system("cls"); int row; cout<<"Enter n : "; cin>>row; for (int i=0;i<row;i+...
First, I'm not sure exactly what you're trying to calculate, but you might want to pay more attention to edge cases, e.g. negative arguments or cases where row < col. Now, without the col == row condition (and assuming col >= 0), the number of total calls will be the sum of a Pascal’s Triangle, which is roughly pow(2, ...
63,276,765
63,280,666
F#: Calling native functions with custom type parameters
I'm calling into a native DLL from F#. It's proven pretty simple for functions that take no arguments or only basic types, but I'm having a lot of trouble getting my code to work otherwise. The C++ code is: struct CatDef { uint8_t cat; uint8_t arrogance; CatDef() : cat(0), arrogance(0) {} }; struct HomeI...
Never mind, I got it worked out. For anyone who might care, my F# code worked with just a couple of changes: I changed UnmanagedType.LPStr to UnmanagedType.ByValTStr In the extern function declaration, I decorated HomeQuery[] queries with [<In; Out>] (i.e. [<In; Out>]HomeQuery[] queries). That's all.
63,277,030
63,277,079
std::string implicit conversion priority, string_view over const char*
I have two overloaded functions: void Set(const char * str) { std::cout << "const char * setter: " << str << "\n"; } void Set(const std::string_view & sv) { std::cout << "string_view setter: " << sv << "\n"; } And I call Set() on a std::string. It picks the std::string_view overload rather than the const char * overlo...
std::string has a non-explicit conversion operator to std::string_view, so it could convert to std::string_view implicitly. But std::string doesn't have a conversion operator to const char*, it can't convert to const char*. You have to call its c_str() method explicitly to get a const char*: Set(some_string.c_str());
63,277,037
63,277,086
Pointer object calling a constructor gives some other not expected result
#include <iostream> using namespace std; class Test { public: int x; Test() { x = 5;} }; int main() { Test *t; cout << t->x; } It should print "5" but instead, it prints "1528349827". Test *t should initialize x by 5. and t->x should print 5. But it gives the above number. Can someone please ex...
Test *t; should initialize x by 5. That's false. This line of code just declares a pointer to a Test. There is no Test object, and so no constructor is run that initializes any x to 5. Doing t->x is undefined behavior, because there is no object to dereference. The program could do anything, including printing out a ...
63,277,370
63,293,171
Check number of available buffer characters in file descriptor
How do I check how many available characters there in the buffer in a socket file descriptor? I want to postpone reading bytes from a socket until at least 8 bytes are available (for the length of the following message). I am using select() to wait for incoming data. When the read handler for a socket is called, I want...
You can use ioctl() with the FIONREAD (SIOCINQ) request. From the tcp(7) manpage: The following ioctl(2) calls return information in value. The correct syntax is: int value; error = ioctl(tcp_socket, ioctl_type, &value); ioctl_type is one of the following: SIOCINQ Returns the amount of queued unread data in the rec...
63,277,639
63,285,242
Compare std::variant with int using C++20 <=> is not a constant expression
Since the std::variant is not allowed to compare with one of its alternative types in the standard library, I am implementing the compare function using C++20 <=> operator: template <typename... Args, typename T> constexpr auto operator<=>(const std::variant<Args...>& v, const T& t) { return std::visit([&t](const aut...
The first example reduces to: #include <compare> // this one is okay static_assert(std::partial_ordering(std::strong_ordering::less) < 0); // this one fails with non-constant condition static_assert(std::partial_ordering(1 <=> 2) < 0); Everything here is obviously a constant expression. The fact that strong_ordering...
63,278,510
63,278,700
Runtime error when vector in class constructor?
Hi I am unable to use a vector in the constructor. I'm trying to parse a vector that contains [x,y] coordinates into the object. The errors I've gotten are runtime error and bad alloc. Is there something I'm missing? Do I have to use dynamic memory allocation? ShapeTwoD(Parent Class of Child Class Square): class ShapeT...
In your Square constructor, you are not passing any arguments: Square() : ShapeTwoD(name,containsWarpSpace,vect){ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ That means that the name, containsWarpSpace and vect refer to the parent class fields, which haven't been initialized yet (because that's the job of the Sha...
63,278,624
63,309,047
map to a function pointer with different number of arguments and varying datatypes
In my code, I have several class, each with different methods. For example: class A { public: int sum(int a, int b); bool isScalable(double d); } class B { public: std:string ownerName(); } My aim is to create a map of all the function names as below std::map<std::string, FnPtr> myMap; // Add the newly i...
As comments suggest, it is unlikely you really want to do this. Assuming that you do, however - perhaps you should reconsider whether C++ is the right language for the task. Another language which has better runtime reflection facility might be more appropriate; perhaps an interpreted language like Python or Perl. Thos...
63,278,740
63,279,637
C++ application crashesbecause of unknown reason?
I don't know why but my QT application is crashing every time at the //Error (in last function of .cpp file) comment. Do you guys know why? I unfortunately have no debugger here :/ ServerSys.cpp #include "ServerSys.hpp" #include "ui_ServerSys.h" #include "ServerNet.hpp" #include <iostream> #include <iomanip> #include <...
std::stoll throws an std::invalid_argument exception when the conversion isn't possible. That's likely the crash you are experiencing, especially if your other test revealed that the string was already empty. Ui::ServerSys *serverSys; as a global variable is a really weird thing to do, if you already have ui as a membe...
63,279,013
63,279,175
Check if at least one member variable of struct is true
In my code I use the following type of struct that is initialized at program start. struct Parameters { Parameters() { bla = false; foo = false; bar = false; // and so on ... } bool bla; bool foo; bool bar; // and so on ... }; The actual struct in my ...
Edit: I have completely changed this answer as I have been told the previous answer could lead to problems on some compiler settings. The way you do this is by creating a pointer to member array of all struct members. This way you can easily loop through them all. Of course this isn't ideal because when you have a lot ...
63,279,038
63,279,280
What does for(auto &it: a) mean?
I'm a newbie and learning how to use the c++ language in a more flexible way. In a contest problem I have seen someone write code like this: #include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; ...
1. for (auto &it : a) cin >> it means you are taking the input of vector a. It's similar to: for(int i = 0 ; i < n; i++){ cin>>a[i]; } The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. So here it takes the references of a[i] and ...
63,279,641
63,281,608
Why Desktop PIDL's size is zero?
I have a question about Desktop PIDL. I got the Desktop PIDL using SHGetDesktopFolder and IPersistFolder2::GetCurFolder. But, I check this using ILIsEmpty, return true. So, I check Desktop PIDL, and cbSize in PIDL is zero. Why Desktop PIDL's size is zero??
If this PIDL is empty, the parent folder is the desktop. You can check if its name is "Desktop" using GetDisplayNameOf. IShellFolder *psfDesktop = NULL; hr = SHGetDesktopFolder(&psfDesktop); IPersistFolder2 *pf = NULL; hr = psfDesktop->QueryInterface(__uuidof(IPersistFolder2), (void**)(&pf)); PIDLIST_ABSOLUTE pidl = NU...
63,279,912
63,281,781
Qt - QTextDocument breaks word wrap if font is specified in html
I have to convert HTML into a pdf with QTextDocument but, if i specify the font in the html (that's what I need) the word wrap result broken. To make this code compile add QT += printsupport in .pro Example: #include <QGuiApplication> #include <QPrinter> #include <QTextDocument> int main(int argc, char *argv[]) { QG...
You just need to add following text to the style field of <pre>: white-space: pre-wrap like this: #include <QGuiApplication> #include <QPrinter> #include <QTextDocument> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QPrinter printer(QPrinter::PrinterResolution); printer.setPaperSize(QPri...
63,280,803
63,281,060
Why does returning a virtual class *by value* in C++ alter the v-table?
In the following code I return a derived class CDerived by-value from a function returning its base class, CBase. For example purposes, CDerived contains a _number field, and I understand that this is "sliced" off during its conversion to the by-value return type, CBase. However, what confuses me here is that the virtu...
That's how C++ works. You don't return a CDerived object, you return a CBase, copied from the CBase sub-object of the temporary CDerived.
63,280,857
63,280,953
inheritance C++ why father constructor is not evoked
I just want to test an inheritance pattern but it seems I lacks some understanding. I thought father class's constructor should be evoked. Some direction is apprecitated #include <stdio.h> #include <iostream> #include <memory> template<class Gender, class Race, class ChildType> class Father { public: Father() { ...
This code declares a function called child returning a shared_ptr which is not what you hoped for: std::shared_ptr<Father<Male, Vietnam, Child>> child(Child()); You may fix it with this: auto p = make_shared <Father<Male, Vietnam, Child>>();
63,280,875
63,281,094
How to pass multiple arguments to spawned threads (Mbed)?
I use Mbed RTOS and I need to pass multiple arguments to the threaded function. There is an example in API docs: #include "mbed.h" Thread thread; DigitalOut led1(LED1); volatile bool running = true; // Blink function toggles the led in a long running loop void blink(DigitalOut *led) { while (running) { *l...
You could use an std::tuple<> instead of defining a new struct. This is simpler in most cases, although as the number of argument members goes up, you might find yourself wanting a struct after all, to get names for them instead of having to std::get() by type or index. There is unlikely to be any other way, as such ca...
63,281,021
63,295,859
How can I fix this "undefined reference" error using G++ and CPLEX?
I apologize if this is not the correct community to ask this on, in that case, please tell me which one is. I tried some IBM forums but I get a (general?) error when I try to start a thread there. I am decently experienced with CPLEX (on Windows, with visual studio c++), but when I try to compile the following simple e...
It seems you are missing the required libraries for the linker. You only specified -L options to tell the linker where to find the libraries. You did not add -l options to tell which libraries to link. Try adding this before -o heuristic: -lconcert -lilocplex -lcplex -lm -lpthread -ldl In general, to find the right fl...
63,281,226
63,281,357
virtual function not accessible in derived class
The following code would not compile. GCC complains no matching function for call to ‘derived::print(std::__cxx11::string&). class base { public: virtual void print(float x){} virtual void print(std::string str){} }; template<class ProcessType> class CProcess : public base { public: CProcess(ProcessType* p...
The problem isn't caused by it being virtual. Since derived defines its own print, it shadows every inherited overload of print. The solution is to add using base::print; to the derived. Make sure this line is public, otherwise the inherited overloads won't be public.
63,281,255
63,281,506
Starting loop at specific index of a std::string?
I wrote the following function: std::regex r(""); for (std::sregex_iterator i = words_begin; i != words_end; ++i) {} It starts looking for regex matches from the beginning of the given string (str) But how may I tell it to exclude everything before specific index? For example I want it to delete with all of what come...
If I understand your question correctly you can pass a parameter to the function with the position where you'd like to start the search, and use it to set the iterator: void print_str(const std::string& str, int pos) { std::regex r("\\{[^}]*\\}"); auto words_begin = std::sregex_iterator(str.begin() + p...
63,281,925
63,282,270
C++ argument pack recursion with two arguments
I have a template class that uses two types: template<typename T1,typename T2> class Foo { ... }; I need to write a function that takes any number of Foo variables: template <typename T1, typename T2, typename... Others> size_t getSize(Foo<T1,T2> *f, Foo<Others>*... o) { ... }; If I implement the class Foo with only ...
What about template <typename ... Ts1, typename ... Ts2> std::size_t get_size (Foo<Ts1, Ts2> * ... fs) { /* ... */ } ? Or, maybe, template <typename T1, typename T2, typename ... Us1, typename ... Us2> std::size_t get_size (Foo<T1, T2> * f, Foo<Us1, Us2> * ... fs) { /* ... */ } if you want a first Foo managed diffe...
63,282,317
63,282,429
runtime error: load of misaligned address
I recently encountered this error. The full error is the following. external/libgit2/src/hash/sha1/sha1dc/sha1.c:438:2: runtime error: load of misaligned address 0x6110000205f5 for type 'const uint32_t', which requires 4 byte alignment 0x6110000205f5: note: pointer points here 65 6e 74 20 64 35 63 30 62 31 35 64 61 3...
0x6110000205f5 is not an aligned address. (It is one byte off to 4 byte alignment). This will happen, if you pass an unaligned pointer to the code. You could either to this manually or use functions from the memalign family or for windows _aligned_alloc
63,282,702
63,282,808
Can't build SSDL from the source code of the book C++ for the Lazy Programmers
I can't compile the SSDL source code from the book C++ for the Lazy Programmers (2019) by Will Briggs on my ubuntu 20x so could you please tell me what goes wrong? I installed SDL2 and it's working but most of the cases I get the following error when I compile an SSDL code; cpp-for-lazy-programmers/ch1/hello$ make -f M...
Just because they both have "SDL" in the name does not mean they are part of the same library. If you search for SDL_ttf.h on packages.ubuntu.com ("contents of packages"), it will tell you that you want the libsdl2-ttf-dev package This is also mentioned in the accompanying documentation.
63,283,393
63,283,778
Moving element from container does not empty container?
Given the following code: #include <vector> #include <iostream> struct number { int n{666}; }; int main() { std::vector<number> vec; std::cerr << vec.size() << std::endl; number n; vec.push_back(n); std::cerr << vec.size() << std::endl; auto b = std::move(vec.front()); std::cerr << "b...
Once you have used the value at the front and you want to get rid of it you will need to erase it from the vector. I won't talk about the front() returning a ref as 0x5453 mentioned that. But there is no reason to use std::move there - all that does is cast the value to a rvalue reference it does not actually "move" an...
63,283,436
63,283,615
passing generic iterator to function cpp
Trying to send an iterator function using Template, that can get any iterator (from array, queue, etc..). [in the example, I send vector] THE ERROR: line 15 not compile: ExampleVector <int> vec(values.begin(), values.end())") template <typename ExampleVectorType> class ExampleVector //new class { ...
After fixing one compile time error after another I get this code: #include <iostream> #include <vector> template <typename ExampleVectorType> class ExampleVector //new class { public: template <class InputIterator> // generic iterator ExampleVector (const InputIterator& f...
63,283,514
63,283,560
Trying to end for loop
I am trying to create a loop that allows the user to enter as many elements to the array as they would like then sum up those elements. I need the loop to terminate when the user enters a negative number. How would I go about terminating this? double sum = 0; double group[] = { 0 }; for (int i = 0; i >= 0; i++) { ...
I need the loop to terminate when the user enters a negative number. For that a while loop would be better than for. You should also use vector which allows arbitrary number of items. Something like this: vector<double> group; double salary; while (true) { cout << "Please enter employ...
63,283,651
63,283,867
Would a statically sized Rcpp empty list be more efficient than list.push_back()?
If one wishes to iterate over a function and add the results to a list in Rcpp, one can use the .push_back() method, for example: List appended_list() { List emptylist = List::create(); for (int i = 0; i < 3; i++) { emptylist.push_back(i); } return emptylist; } However, am I correct in saying tha...
A pre-allocated list will be much faster. If you are unsure how to create a list of pre-determined size, my suggestion is that you probably need to spend some time with introductory Rcpp materials. Some good resources are: The vignettes offered by Rcpp, in particular the Introduction and FAQ vignettes. In addition to ...
63,283,701
63,285,037
Flight destination check programm - C++
I am trying to solve the following question: Write a program, which will get from the user the Number of flights (N) the destination of train (city) the train number for certain destination (number) the name of the wanted destination city, for which we are searching possible trains. The program should find and display...
On your comment: C++ is much harder than python. Programming languages are just tools. You use them to solve a problem. If you don't know how to use a tool, you can't solve the problem. Your computer is a tool, if you don't know how to operate it, you can't do your homework. That doesn't mean computers are difficult ...
63,284,176
63,288,010
Detect if exe is running from a USB
I am writing an app using windows API that needs to check on startup that it is running from a USB device. What I have achieved so far List devices using SetupDiEnumDeviceInfo Detecting which device is removable Here is my code to do the above 2 tasks HDEVINFO hdevinfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE,N...
Windows API function GetDriveType returns the following: DRIVE_UNKNOWN - 0 - The drive type cannot be determined. DRIVE_NO_ROOT_DIR - 1 - The root path is invalid; for example, there is no volume mounted at the specified path. DRIVE_REMOVABLE - 2 - The drive has removable media; for example, a floppy drive, thumb drive...
63,284,423
63,284,568
How do I use c++20 std::is_constant_evaluated in Visual C++ 2019 Community?
MS claim to support is_consant_evaluated on their conformance page and their <type_traits> header does include an implementation, guarded with #if _HAS_CXX20. It seems though that (with MSVC Community 16.6.5, at least) /std:c++latest does not cause _HAS_CXX20 to be defined. The UI does not offer a /std:c++20 option. e...
I can't reproduce your errors, it works fine for me, _HAS_CXX20 is properly set. and is_constant_evaluated works fine. std::cout << _HAS_CXX20; outputs 1. My implementation: #if _HAS_CXX20 // FUNCTION is_constant_evaluated _NODISCARD constexpr bool is_constant_evaluated() noexcept { return __builtin_is_constant_ev...
63,284,587
63,285,070
Strange behaviour when adding doubles
I am working on a Direct3D project and in my code there is a function which takes a double as a parameter, this double represents the time since the last frame, the idea was to sum this time with another double which represents the angle of rotation of a cube, and then store the new value as the new angle, but after de...
As lastFrame is initialised to 0 the first call to GetFrameTime will return the value of QueryPerformanceCounter in seconds. You should either call GetFrameTime once at the start of your program and discard the value or initialise lastFrame in StartTimer.
63,284,797
63,284,852
How exactly does constexpr double Point::* coords[3] work?
So I've been looking at some stuff and found this thread Aliasing struct and array the C++ way And this is the answer to the question #include <math.h> struct Point { double x; double y; double z; }; double dist(struct Point *p1, struct Point *p2) { constexpr double Point::* coords[3] = {&Point::x, &P...
This syntax is a pointer to member, and is essentially a way to store a member to a variable and retrieve it. It's useful for a case like this, when you want to loop through a list of members.
63,284,835
63,286,378
Qt XML duplicate tags
I have a xml file and just want to duplicate some specific nodes: From (example): <1> <2> </2> </1> to: <1> <2> </2> <2> </2> </1> I tried the following: for(int i = 0; i < xmlRoot.childNodes().count(); i++) { if(xmlRoot.childNodes().at(i).isElement()){ if(xmlRoot.childNodes().at(i).toElement...
The problem is with this line: xmlRoot.childNodes().at(i).insertAfter(teamNode, xmlRoot.childNodes().at(i)) The insertAfter method takes two arguments - the new node and the node that will be a reference for the new node insertion. But, both of these arguments need to be a children of common parent on which insertAf...
63,284,970
63,285,842
How To Extract Tokens from String?
Edit: May someone add a regex solution? I was looking on the following regex: [\(\)!*-+^] I had the a function that extracts tokens from a text according to the special chars I declared in its body. There are 2 problems in the function: 1) It doesn't print the special chars. 2) It outputs wrong when two special chars ...
Here's a regex solution that should parse the tokens you want: void find(std::string str) { static const std::regex r(R"(\+|\^|-|\*|!|\(|\)|([\w|\s]+))"); std::copy( std::sregex_token_iterator(str.begin(), str.end(), r, 0), std::sregex_token_iterator(), std::ostream_iterator<std::s...
63,286,266
63,286,343
Program implementing stack exits with "code=3221225477"
The program is just a simple implementation of a stack that keeps popping until the stack is empty. It pops the last letter and then crashes; although, technically it does what it's supposed to do. I'd just like to know why I'm getting the error code 3221225477 and how to fix it. I'm sure it's something simple. #inc...
Here if the current element is the last element, you pop() and then access top() with the stack with no elements. cout << "Popping " << s.top() << endl; s.pop(); cout << "Top element is now " << s.top() << endl; cout << "The stack size is now " << s.size() << endl; To cout << "Popping " << s.top() << endl; s.pop(); if...
63,286,483
63,292,064
how to replace the last matched character in string with last matched character and constant
I have a string like, string basestring= "A\B+C+E\FG+\K987+54h\"; I have to replace all the occurrence of special character with the same special character and . Output should be : "A\\B\+C\+E\\FG\+\\K987\+54h\\" Currently I am using the following code to get the result. regex Reg("[^A-Z0-9]", regex_constants::icase)...
Use std::regex Reg("[^A-Z0-9]", std::regex_constants::icase); std::string help = std::regex_replace(R"(A\B+C+E\FG+\K987+54h\)", Reg, R"(\$&)"); The replacement is a backslash followed with the match value (the backreference to the whole match is $&).
63,286,664
63,687,819
PJSIP Get Codec from current call
I want to log which codec is used on a specific call. I'm using PJSIP to make the call, but I don't know to get the codec from an active call. Can someone point me to how I can get the currently used codec?
You can use a pjmedia_stream_get_info (link) function, which takes pointer to structure pjmedia_stream_info (link) as its second argument. Then you can get negotiated codec name from pjmedia_codec_info (link) structure, which is a part of stream information.
63,286,741
63,287,656
Creating a binary tree out of string. Ex: 1,2,3,#,#,4,5,#,#,#,#,
I am creating a binary tree out of string using BFS algorithm and I have a question: Why should I write "TreeNode node = tree.front();" after while loop instead of "root = tree.front();". Why I can't just use already created TreeNode root ? TreeNode* helper(queue<string> &q) { string data = q.front(); q.pop(); ...
Because root points to the root of the tree, which is what the function should return, and the root of the tree has already been determined (it is the first element of the input queue). Writing root = tree.front() would make the last created node the root of the tree, and the tree would have only one element.