question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
68,983,938
68,994,124
No such file errors when compiling "Hello, world!" wx-widgets app on macOS
I have installed wx-widgets on my Mac (macOS Big Sur) via Homebrew brew install wxwidgets But when I try to compile this or this Hello, World! example I get and errors clang: error: no such file or directory: 'libexpat.tbd' clang: error: no such file or directory: 'libz.tbd' clang: error: no such file or directory: 'l...
I solved the issue by building wxwidgets from source. The command to build apps also need to be changed to g++ `full/path/to/wx-config ` -o HelloWorld HelloWorld.cpp `full/path/to/wx-config --libs` or g++ -o HelloWorld HelloWorld.cpp `full/path/to/wx-config --libs --cxxflags`
68,983,979
68,984,065
Why does (infinite) recursion give different results with and w/o -O3 in clang (and gcc/g++)?
When I compile and run this code #include <stdio.h> int collatz(int a) { return a == 1 ? 1 : collatz((a%2) ? 3*a+1 : a/2); } int main() { for (int a = 0; a < 10; ++a) printf("%d: %d\n", a, collatz(a)); } in clang (10.0.0-4ubuntu1) it crashes, but when I add -O3 it runs fine. (This holds both when pas...
Is that a (known) bug in the optimization or am I missing something? It's not a bug in optimisation. It's a bug in the program that is being compiled. The behaviour of the program is undefined in C++. it returns 0: 1, which is wrong There is no "wrong" behaviour when the behaviour of the program is undefined. but ...
68,984,321
68,984,386
What is the diffrence between std::greater{} and std::greater<int>()?
Some people write std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater{}); and some write like this std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater<int>()); What is thre diffrence between std::greater{} and std::greater<int>()?
This is new as of C++14, and this results in two completely different classes. In C++14, std::greater acquires a default value for its template parameter: void. You end up with either std::greater<void> or std::greater<int>. std::greater<void> is a specialization for a so-called "transparent" comparator that deduces it...
68,984,395
68,984,587
Number always outputs as decimal in edit box, regardless if it is an int or a double
I'm pretty new to coding and for the last couple of days I've been exploring WINAPI and trying to learn something new, so I decided to make a calculator (honestly, was harder than I anticipated). Now I've got everything working, but the only problem left is that when I try to use the calculator, I always get a result t...
Custom formatting is not really available when you use the std::to_string() function. Instead, what you can do is to use the standard formatted output operator to write your data to a string stream, then read your std::string from that: // std::wstring s = std::to_wstring(Res); std::wstringstream ss; ss << Res; /...
68,984,596
68,985,361
SYCL/DPC++ cpu version gives correct result, but gpu gives incorrect data
I compiled and ran the below code with intel dpc++ compiler. I am getting right result when using cpu selector but gpu selector gives garbage value. All that my code does is an array named data is intialised with all 1's. In sycl kernel an accessor to this array is multiplied by 3 and saved to a result array. I try to ...
You are not triggering a copy back to host. Presumably on CPU, your SYCL implementation just decides to operate directly on the input pointer, so you don't see the problem. Think about this: How could the SYCL implementation know that resultarray is being used in your cout and that data has to be copied back? It cannot...
68,984,884
68,985,736
Is it possible to use ranges adaptors to revert the projected member to the original class object?
C++20 brings a very powerful projection utility. Some range adaptors such as transform_view and elements_view allow us to easily project operations to the member variable of the origin class object (godbolt): auto historical_figures = vector{ pair{"Lovelace"sv, 1815}, {"Turing"sv, 1912}, {"Babbage"sv, 1791}...
It’s not in general possible to identify an object based on the identity of one of its subobjects, even if you know which subobject it is rather than just its type (which might leave multiple possibilities). The pointer arithmetic model just doesn’t allow it, partly because it allows certain aliasing optimizations whe...
68,985,039
68,987,092
AVX2: BitScanReverse or CountLeadingZeros on 8 bit elements in AVX register
I would like to extract the index of the highest set bit in a 256 bit AVX register with 8 bit elements. I could neither find a bsr nor a clz implementation for this. For clz with 32 bit elements, there is the bithack with a float conversion, but that is probably not possible for 8 bits. Currently, I am working on a sol...
Here is a vpshufb based solution. The idea is to split the input into two halves, make a lookup on both and combine the results: __m256i clz_epu8(__m256i values) { // extract upper nibble: __m256i hi = _mm256_and_si256(_mm256_srli_epi16(values, 4), _mm256_set1_epi8(0xf)); // this sets the highest bit for va...
68,985,286
68,985,848
c++ assign the value of the user input into another variable and swap the value everything it get loop
i think i could get a little help from you guys, so i'm trying to swap swap the player's name that i get it from user input. I try to assign the value of one of the player's name into variable current_name_turn. So, everytime it get loop through, the current_name_turn will change the value into the other player's name ...
This is the working code that switches between the entered names: #include <iostream> using namespace std; bool game_is_playing = true; string name[] = {"x","o"}; string player_1, player_2; string current_name_turn = player_1; string ask_player_name_1(string player_1){ cout << " Player 1's name: "; cin >> na...
68,985,350
69,757,666
Tell gdb to skip _only_ std when stepping
As mentioned in this question, I want to skip over all std functions when stepping. Making skip -rfu "std::.*" sort of works but sometimes it's too crude. Let's say I have a code like this: auto p = std::make_shared<Something>(yadda yadda); When skip is enabled, step will just step over this entire line even if ctor ...
This answer suggests using python scripting ability for gdb. So I managed to construct this a bit messy script that works for me most of the time (although sometimes it requires a step or two to step out of ASAN assembly): import gdb import re def stop_handler(event): frame_name = gdb.selected_frame().name() i...
68,985,458
68,985,589
Configuring C++11/14 in Mac Terminal by default
I want to use c++11/14 features like range-based loops, but get a warning while doing g++ program.cpp. If done with compiler flag g++ -std=c++11 program.cpp the warning goes away. Is there a way to use c++11/14 by default on the g++ command (i.e without passing compiler flag every time). Please explain to someone with ...
Short Answer: Update your g++ According to g++ documentation The default, if no C++ language dialect options are given, is -std=gnu++17. You are probably using an older version of g++. You can check it using by running g++ --version in your terminal. If you are using Linux, you can also extract your default c++ stand...
68,985,998
68,986,852
How to do an action when button is pressed
I am creating a log in screen for my app, I created the buttons but I dont know how to make my program do something when one of these buttons are pressed.Here is my code(I dont think it will be usefull) LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_...
The first thing you need to change is to assign an ID to your button CreateWindow calls, this is done through the HMENU parameter. The next thing you need to do is handle WM_COMMAND for those IDs and the BN_CLICKED command identifier. For example, to assign the ID 1 to your Confirm button: CreateWindow(TEXT("button"), ...
68,986,376
68,987,290
C++ How to display Unicode wstring as Number in Unicode format
I have a std::wstring like that: std::wstring mystr = L"abc\U0000FFFF\U0000000A\U00000061\U00000010de"; I want to print it out to the console where it should look like that: abc\U0000FFFF\U0000000A\U00000061\U00000010de When I try this : for (int i = 0; i < 9; i++) { char16_t* ctest = &c[i]; std::cout << *cte...
Just inspect each character as you output it. If it's in the printable ASCII range, output it as a char; otherwise output it as a hex sequence. std::wstring mystr = L"abc\U0000FFFF\U0000000A\U00000061\U00000010de"; for (int i = 0; i < mystr.size(); ++i) { if (mystr[i] >= 0x20 && mystr[i] < 0xff) ...
68,986,479
68,986,600
How to get arguments from Variadics Template
This is a good answer already, however, they passed arbitrary numbers of arguments as the parameters when I tried to do the same with arguments as typename (don't know the exact word) like this for example: int sum=0; int func() { return sum; } template <int first, int ... rest> int func() { sum += first; ...
First of all, the "base" function also needs to be a template. Then to differentiate the two templates, the parameter-pack template needs to take at least two template arguments. And lastly, you can solve this without the global sum variable, but using the addition in the return statement. Putting it all together: temp...
68,986,506
68,988,473
Having an issue passing an array to a Function as only first word is printed c++
I am new to passing values to functions, please guide me what I am doing wrong here, thanks! The question: Write a C++ program in which, read a c-string sentence one by one from a file “sentence .txt”. Now your task is to break each word of sentence into another c-string word, now write that word into a file “word.txt...
The following program show how to get started with reading and writing from/into text files in C++. This is just to get you started and in practice i use std::string and std::istringstream to do this but in your note it is written that we cannot use strings so i did not use std::string. The program reads line by line ...
68,986,552
68,993,913
SWIG Converting Python list to a char ** example fails
I am following the SWIG tutorial and I'm currently on the section: "32.9.1 Converting Python list to a char **". The example in question returns a malloc error on my machine: import example example.print_args(["a","bc","dc"]) python(57911,0x10bd32e00) malloc: *** error for object 0x7f7ee0406b90: pointer being freed...
The example code would work with Python 2, but has a bug as well as a syntax change for Python 3. char** must be passed byte strings, which are the default in Python 2 when using "string" syntax, but need a leading b, e.g. b"string" in Python 3. This works: import example example.print_args([b"a",b"bc",b"dc"]) The ...
68,986,683
68,999,291
Refactoring using variadic templates
I need to refactor 3-versions of a given function. Each has virtually identical code but parameters types differ. template <typename... Args> void myfunction(int value, varied_parameter_type param, Args... args) { ... do some work ... } Where varied_parameter_type is either: no-parameter at all (void), a const char...
I've decided to follow @Ted Lyngmo's initial suggestion of just passing the varied-parameters as the first parameter of Args... args. I don't really care for this approach but it is extraordinarily simple when compared to the other options that I was trying to use. I'd much rather that the varied_parameter be explicity...
68,986,810
68,987,008
Why do I get stack overflow error when I use this function for Merge Sort(using Linked Lists)?
I am using a mid_element() function to return the address of the middle node and a Merge() function to merge two sorted linked lists. Both these functions work fine. But I have attached the code just in case. I went through the merge sort algorithm that partitions the linked list into two, one containing the first node...
This line in Merge() dereferences a potentially null pointer. Node *h=h1->data<h2->data?h1:h2,*t=h; And it is potentially null because mid_element() contains this line if(head==NULL || head->next==NULL) return head; ... which can return a pointer whose next element is null, and MergeSort() takes that return value...
68,986,939
68,987,257
Is it possible to have restricted access to included class?
I have a class say A in A.h file and class B: public A in B.h file. A.h file #ifndef A_H #define A_H class A { public: void foo {} }; #endif B.h file #ifndef B_H #define B_H #include "A.h" class B: public A { ... }; #endif Is there a way to include B but not to have access to A until I include A.h? Like ...
No. B.h depends on the definition of A, so there is no way to include B.h without including the definition of A. And there is no way of getting around that dependency if B must be defined in B.h and if B must inherit A. You can make the creation of separate A into an error by changing A to be an abstract type. But that...
68,987,050
68,987,083
Why is this compiling successfully?
What is the reason which why this code compile : #include <iostream> using namespace std; class being { public: void running(char c) { cout << "No one know "; } }; class human :public being { public: using being::running; void running(char y) { cout << "I am a human"; } }; int main() ...
This is expected behavior of using declaration. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class. So human::running(char) hides being::running(char) in...
68,987,349
69,418,376
Is it allowed comparing the pointers on static class fields in static_assert?
I was trying to verify in a static_assert that a program had really two distinct classes produced from a template by comparing the pointers on their static fields. After some simplifications the program looks as follows: template<int N> struct C { static int x; }; template<int N> int C<N>::x = 0; int main() { ...
Compile-time equality comparison of the pointers on static class members is allowed. The problem with original code was only in GCC and due to old GCC bug 85428. To workaround it, one can explicitly instantiate the templates as follows: template<int N> struct C { static int x; }; template<int N> int C<N>::x = 0;...
68,987,560
68,989,083
Possible to import classes from a module, use them as private base classes, but not re-export?
I'm trying to make sure I understand modules correctly with some toy examples. One use case that I could see being relevant would be implementation-hiding by having base classes that aren't part of the exported portion of a module. Using Visual Studio 16.11.2, the following code behaves as I would expect: PublicModule....
Your understanding is correct for both examples: this is evidently a compiler bug. Name lookup doesn’t consider whether a name is used in some other translation unit.
68,987,701
69,004,154
Is there an advantage to using 2d kernels in CUDA beyond convenience?
I'm wondering if there is any inherent advantage to having a kernel be > 1d besides the convenience of abstraction. I figure that if the dimension of the kernel is relevant, the answer might have to do with the layout of the gpu. I would generally prefer to stick to 1d and flatten higher dimensional data. Is there anyt...
It's even worse that what Jerome said... combining 2D/3D locations is not so cheap. Just think about it: flattened_block_id = blockIdx.x + blockIdx.y * gridDim.x + blockIdx.z * gridDim.y * gridDim.z; flattened_thread_id = threadIdx.x + threadIdx.y * blockDim.x + threadIdx.z * blockDim.y * blockDim.z; block_volume = bl...
68,987,980
68,988,294
How do I solve the "array initializer must be an initializer list" error?
I've written a problem for an algorithm problem. I'm new to C++, and I'm getting the following error message when I try to run my code: "array initializer must be an initializer list". Here's the code itself: #include <iostream> #include <algorithm> #include <array> using namespace std; int main(){ int n; cin>...
cin>>n; int a[n][2]; The size of an array variable must be compile time constant. n is not compile time constant. The program is ill-formed. What alternative do I have? If you want a runtime size array, then you must create the array in dynamic storage. Simplest approach is to use std::vector. Elements of vector c...
68,988,076
69,002,127
Win32 API: CreateFont/SelectObject not rendering text properly on a different computer
I cloned and tweaked a version of Open-Shell on Visual Studio and used their makefile to compile it into an installer. To be more specific, I wanted to make the 'All Programs' text button bold: To do so, I called CreateFont inside Src/StartMenu/StartMenuDLL/MenuPaint.cpp on line 2336 (which gets called each time you o...
It turns out the code does work on my laptop. However, another program is interfering/overriding font settings (WindowBlinds 10 in this case). My approach is still not ideal (as stated by Vlad Feinstein) but I hope it helps.
68,988,186
68,988,328
How to call a polymorphic method in a thread object?
struct Base { virtual void do_work() = 0; }; struct Derived_A : Base { void do_work() override { // work A } }; struct Derived_B : Base { void do_work() override { // work B } }; int main() { std::vector<std::unique_ptr<Base>> workers; workers.emplace_back(std::unique_ptr<...
The polymorphism should just work, because a pointer to a virtual member function will always behave polymorphically when invoked. There are only two changes required to make your program correct: You have to write worker.get() when creating the thread. This is because the pointer to member function Base::do_work is "...
68,988,539
68,988,579
C++ perform action when command line argument is empty
I've been working on a program recently, and got a bit stuck on a step. When the program is run from the shell, it performs an action when there are no parameters passed. Perhaps someone could assist me, or point me in a proper direction? int main(int argc, char* argv[]) { string paramPassed = argv[1]; if(param...
If there are no command line arguments, then indexing at argv[1] is undefined behavior. There is simply nothing at that index, as opposed to an empty string which is what you're checking. To check that there are no command line arguments (after the program name, which is always argv[0]), you can simply use the value of...
68,988,589
68,989,123
Can't find calculator01.cpp from PPP example code
the books says to run calculator01.cpp but I can't find it anywhere. I've tried Where is Bjarne C++ PPP book calculator example code? but gives me Forbidden access when accessing it. The chapter is chapter 6.
You can download all the code from the book at Stroustrup's site as well, at: https://stroustrup.com/Programming/code.tar The filenames are based on the chapter names, not the names in the text; so for calculator01.cpp, which appears at the beginning of section 6.7, you'd be looking in the code/Chapter06 folder for cha...
68,988,674
69,018,524
QChart points are incorrectly plotted when I change the XAxis and YAxis
I am making a QScatterSeries. I have some points plotted in 3 different series (red, green, blue). It all plots perfectly when I use chart->createDefaultAxes(). All points are where they should be. The issue is that when I change the X Axis and Y Axis in my chart, all my points become incorrectly plotted. None of them ...
I found the answer to my question in another post. Posting here in case it helps someone QtCharts add custom axis
68,988,705
68,988,787
Type parameter <T> behind the “function name” operator
what is the difference between the following two snippets? with <T> for operator << template<typename T> class Stack { ... friend std::ostream& operator<< <T> (std::ostream&, Stack<T> const&); }; without <T> template<typename T> class Stack { ... friend std::ostream& operator<< (std::ostream&, Stack<T> const&); };...
In #1, the compiler will look for a function template called operator<< such that operator<< <T> has the precise signature given, and the class Stack<T> will befriend only that particular specialization. In #2, the compiler will look for a non-template function called operator<< which has the precise signature given. I...
68,989,259
68,989,319
Is there any point to the const variable here?
#include <iostream> int square(int const &i) { return i * i; } int main() { int side = 5; std::cout << square(side) << "\n"; } Just looking at some code and this is a basic question but the const doesn't really do anything here does it? I mean it ensures that I can't change the value of i but I mean it...
I mean it ensures that I can't change the value of i Yes, that is what it does. but I mean it's kinda useless isn't it? In this example it's not useful, but imagine that your function was 300 lines long instead of 1 line long, and was being maintained over several years by multiple different programmers of varying ...
68,989,843
68,990,615
Why is there an access error when trying to access a protected member of a base template class?
It works fine with regular classes: class Base { public: Base() {} protected: int* a; }; class Derived : public Base { public: Derived() {} void foo() { int** pa = &a; } }; int main() { Derived* d = new Derived(); d->foo(); delete d; } But it reports an error when Base and De...
The error is mostly unrelated to templates, and occurs also without any inheritance. The simple issue is that the expression &Base<T>::a is parsed as a pointer to member, as the following snippet shows: #include <iostream> #include <typeinfo> using namespace std; class B { public: void foo() { int* B:...
68,989,876
68,990,006
Does a template function with different definitions cause undefined behaviour?
0.cc template <class T> T get(){ return 5; } int get(){ return 6; } int main(){ return get<int>(); } 1.cc template <class T> T get(){ return 7; } template int get<int>(); // This forces code generation. Compiling with g++ -Wall 0.cc 1.cc causes no link errors, returned output is 5. Questions 1- Do templates hav...
Does a template function with different definitions cause undefined behaviour? Yes. 1- Do templates have external linkage by default even if extern isn't used? Yes, template functions have external linkage unless declared in anonymous namespace or if declared static or if attached to a module and is not exported. ...
68,990,099
68,990,348
libjpeg-turbo segmentation fault when writing scanlines to file c++
I have the following code running on windows 10 in QT Creator, I am trying to write rgb formatted data to a jpeg file using the libjpeg-turbo library #include <stdio.h> #include <jpeglib.h> void writeJpeg(const char *filename, std::vector<unsigned char> &image, uint w, uint h) { struct jpeg_compress_struct cinfo; ...
I see nothing wrong in your code, except C++ bool value true is passed instead of C value TRUE in these calls: jpeg_set_quality(&cinfo, 100, true); ... jpeg_start_compress(&cinfo, true); It may lead to weird crashes sometimes. Also, the first thing I would try in this case - what if just to output somewher...
68,990,128
68,990,175
Function not being called in QML
I have a QML context set up with a Q_PROPERTY to read, write and notify a combo box with an updated list of the COM ports. However, the function is simply not being called, I have qDebugs to specify whether the function is being called. *.cpp #include "input.h" #include <QDebug> void Input::setComPorts(QList<QString> ...
The Q_PROPERTY is irrelevant to this question. To call a function from QML, the function must be declared as Q_INVOKABLE. class Input : public QObject { Q_OBJECT public: Q_INVOKABLE void updatePortList(); ... }; And you have to call it as a function from qml: input.updatePortList()
68,990,203
69,026,493
How to listen to the signal of a view while having a QObject instance of it?
I have created an attached object as described here. This is my qml file in which I have used the attached object (Constraint.widthInParent): Window { id: root width: 640 height: 480 visible: true title: qsTr("Hello World") Rectangle { id: rect color: "black" h...
As you already have a valid pointer to a QObject* that lives inside the QML engine, you can simply do whatever you may do with any other QObject. So, the short answer is : connect(parent, SIGNAL(widthChanged()), this, SLOT(doSomething())); This is the older signal/slot syntax where you use the SIGNAL() and SLOT() macr...
68,991,222
68,998,003
Compile Veins models with c++14
I want to use PyTorch with Veins due to which I need to compile the code using C++14 standard. I looked up OMNET++ and Veins documentation but found nothing. I am using macOS (11.5) and Ubuntu (18.04 and 20.04). I could install the precxx11 version of PyTorch for Ubuntu but there is no such option for macOS. Hence, I h...
Check configure.user change (uncomment) the CXXFLAGS variable there and set it to -std=c++14, then run ./configure and then clean/rebuild OMNeT++ and all of your models so everything would use C++14 as default. OMNeT++ 6.x is using C++14 by default.
68,991,241
68,991,378
Trying to build C++ exe that uses .so that uses other .so files
I'm trying to build a C++ executable that links with a shared library, libA.so. libA.so was built and linked with another shared library, libB.so. libB.so was built using -rpath to look for a custom build of a system library in my home directory (liblapack.so). If I do a "readelf -d" on libB.so, I see liblapack.so a...
Use -rpath-link when linking and specify your custom library location. gcc -o app source.o -lA -Wl,-rpath-link=$HOME This will cause the linker to look in $HOME to find shared libraries referenced by other shared libraries. But only when linking. At run time, when dynamic linking is done, the rpath-link option has n...
68,992,061
68,992,269
Possible to use a variadic functions/templates in this way?
I was wondering whether given the below constraints, it is possible to use variadic functions/templates in order to pass a variable number of parameters (which are themselves a return value of a function) into a variadic function. Constraints: No STL/Boost/other libraries. No loops/recursion. C++17 or earlier complian...
It seems that you want to repeat a statement multiple times based on the number of parameters, in that case, you can take help of C++ templates: #include <cstddef> #include <utility> template <size_t N> struct repeater { template <typename F, typename ...Args> static void do_work(F&& f, Args&&... args) { ...
68,992,250
68,992,315
How do I reset the value passed to the class constructor?
I have a class Vector. Vector::Vector(int x, int y, int z) { if (x > 100 || y > 100 || z > 100) { std::cout<<"the value should not be higher than 100"<<std::endl; this->x = 0; this->y = 0; this->z = 0; // This entry does not work } } int main() { Vector di...
Firstly you do not have an overloaded operator to do cout<<direction;. Furthermore, in your constructor you are checking for >100 not >=100 which is why you are not getting your output here is the working code- #include <iostream> class Vector { int x, y, z; public: Vector(int, int, int); friend std::ostre...
68,992,461
68,992,582
Why sizeof (array A[n]) without n defined in C++is fixed?
When I try to find the sizeof(A) where A is of type int with size as 'n', n is an int that is not defined. I get an output of 496 and when I give a value to n and then check it, sizeof(A) gives me the same values of 496. I know Array is a static data type so it will have memory irrespective of 'n' but can anyone explai...
where A is of type int with size as 'n' int n; int A[n]; The type of A is not "int with size as 'n'". The type of A is int[n] which is array of n integers. However, since n is not a compile time constant, the program is ill-formed. If we were to look past the ill-formedness, the value of n is indeterminate. Reading...
68,992,941
68,993,150
traits if a type `T` has a `template<> struct Writer<T>` to serialize itself
I have a Writer struct to do some serialization template<typename T> struct Writer {}; // only specialized version has ::wrap_t template<> struct Writer <int> { typedef int wrap_t; }; template <typename T> using Writer_wrap_t = typename Writer<T>::wrap_t; template<> struct Writer<float> { typedef float wrap_...
You're not using SFINAE correctly. The typical pattern is to define a primary template where the second template parameter is void template<typename T, typename = void> struct has_writer : std::false_type {}; and then specialize the template using std::void_t of whatever type you want to check as the second parameter ...
68,994,302
68,995,441
What is the cleanest way to do a `std::partial_sum` with a `0` in front?
In C++, there is a function std::partial_sum to compute prefix sum. The code #include <iostream> #include <vector> #include <iterator> #include <numeric> int main() { std::vector<int> a = {1, 2, 3, 4, 5}; std::partial_sum(a.begin(), a.end(), a.begin()); return 0; } will override a to 1 3 6 10 15, which is...
Is there a way to achieve it with the std::partial_sum function? Just write a 0 to the output iterator before calling std::partial_sum. Care should be taken as the output is one larger than the input, and this won't work in-place, as it writes the first output before reading the first input. template<class InputIt, c...
68,994,331
68,994,599
Why is there no overload for printing `std::byte`?
The following code does not compile in C++20 #include <iostream> #include <cstddef> int main(){ std::byte b {65}; std::cout<<"byte: "<<b<<'\n';// Missing overload } When std::byte was added in C++17, why was there no corresponding operator<< overloading for printing it? I can maybe understand the choice of n...
From the paper on std::byte (P0298R3): (emphasis mine) Design Decisions std::byte is not an integer and not a character The key motivation here is to make byte a distinct type – to improve program safety by leveraging the type system. This leads to the design that std::byte is not an integer type, nor a character type...
68,995,563
68,995,791
Error while trying to overload << operator
I can't get the below code to compile while trying to overload the << operator. Can anyone point whats going wrong? #include <iostream> std::ostream& operator<<(std::ostream& i, int n) { return i; } int main() { std::cout << 5 << std::endl; std::cin.get(); return 0; }
There is already defined the operator << for an object of the type int in the C++ standard library basic_ostream<charT, traits>& operator<<(int n); so this call of the operator in this statement std::cout << 5 << std::endl; is ambiguous because the standard operator is found due to the argument dependent lookup. To d...
68,995,654
68,995,968
What is the meaning of "range-based for loop is a C++11 extension" and what is expected expression?
This is my code : class YouTubeChannel { public: string Name; string OwnerName; int SubsCount; list<string> PublishedVideos; }; int main(){ YouTubeChannel ytChannel; ytChannel.Name = "Wonder World"; ytChannel.OwnerName = "Sally"; ytChannel.SubsCount = 1200; ytChannel.Publish...
warning: range-based for loop is a C++11 extension [-Wc++11-extensions] What this means is that you are compiling your code with a version of C++ selected that is prior to C++11, but as an extension, your compiler is going to allow you to do it anyway. However, the code is not portable because not all compilers will ...
68,995,859
68,995,918
Cannot edit an std::atomic value in Visual Studio debugger
This is my test program: #include <iostream> #include <atomic> std::atomic<int> Counter = 200; int main() { if(Counter > 0) std::cout << "Hello World!\n"; } I'm setting a breakpoint to the if(Counter > 0), and when it is hit I'm adding Counter to the watch window: As you can see, the "Edit Value" entry ...
Yes add the following to your watch window: Counter._Storage._Value
68,996,404
68,997,178
What does template<typename T, T> mean?
I was reading this prehistoric metaprogam example to detect whether a class supports member find. (or any other member). template<typename T> class DetectFind { struct Fallback { int find; }; struct Derived : T, Fallback { }; template<typename U, U> struct Check; typedef char Yes[1]; typedef ch...
First, let us consider the struct Derived. Since it derives from Fallback it certainly contains a int field find, and possibly a member function find, whose existence is what you want to check. As noted in the answer above, in the declaration of the struct Check, the first template parameter is as type, and the second ...
68,997,575
68,997,776
Why does printing address of data member of a struct enabled, although there is no object?
Suppose I have the following code. I have expected that this has to at least give me a warning. #include <iostream> struct test { int whatever; }; int main() { int test::* p = &test::whatever; std::cout << p; } However, I was surprised to find out that this code compiles without complaints. So I woul...
how is the test::whatever stored This is not specified in the language. But we can make a reasonable guess that it stores an offset from the beginning of the object to the pointed member. so we can access its address? No. what is actually printed in this case 1 is printed. There is no operator overload for member...
68,997,656
68,997,864
Exception Unhandled: at cvtColor() in openCV
I am trying to detect color using openCV in c++ on visual studio. When I try debugging the code using local windows debugger I get exception unhandle message on the line cvtColor(img, imgHSV, COLOR_BGR2HSV); THIS IS MY CODE: #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> ...
Your cv::imread probably failed and returned an empty matrix. Try: Mat img = imread(path); if (!img.data) { cout << "could not open: " << path << endl; return 1; } And fix your image path if it prints this message.
68,998,153
68,998,999
Assignment operator of std::variant of custom type with deleted special member functions?
Consider: #include <variant> struct A { A() = default; A(A&&) = delete; }; struct B { B() = delete; B(A&&) {}; }; int main() { std::variant<A, B> v{}; v = A{}; } MSVC accepted it, while GCC and Clang rejected it with the same error message: opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/1...
EDIT Initially, there was no language-lawyer tag, which was why I used cppreference for the analysis. However, looking into the latest draft (relevant section), I don't see anything that would make it invalid. I believe MSVC is incorrect. According to the documentation: Converting assignment. Determines the altern...
68,998,623
68,998,670
how can I use a function to print the name of args not use define In c++
#include <iostream> using namespace std; #define debug(x) cout<<#x<<": "<<(x)<<endl; int main() { int a = 0; debug(a) return 0; } the output is: a:0 I want to print the name of variable like a can I do it by a function not use define
i think the answers here can help you : generic way to print out variable name in c++ and it seems the only way is using macro!
68,999,038
68,999,417
Is there a C++ function which enables to divide vector into three seperate vectors?
I am looking for a solution to divide vector into 3 separate vectors with proportion of elements 9:1:1, for example if we had 1100 elements in original vector then I expect to get 3 vectors with consecutively 900, 100 and 100 elements. There is a function std::partition_copy, however it copies data only to 2 separate v...
There is no standard algorithm to do what you want directly. I suppose there are too many special cases to be considered. For example, how to distribute elements according to 9:1:1 when the initial vector has only eg 9 elements? Should each partition contain at least 1 element? Should the result be 7:1:1 or 8:1:0? Howe...
68,999,195
69,012,774
Apply a 4x5 Matrix (instead of 4x4) to Transform in OpenCV (C++)
On Flutter side I use a 4x5 Matrix to apply a Color Filter to an image (for preview). Via FFI, I then apply the filter with OpenCV and transform on the image and save the new image result. However, the result is always different to the preview. So I was wondering, how can I achieve the same result with the same Matrix ...
The most common channel order of color images is RGB. OpenCV's native channel order is BGR (the reverse) for historical reasons. // maps RGB to RGB Mat filter = (Mat_<float>(4, 4) << 0.9, 0.11, 0.11, 0.0 0.11, 0.7, 0.44, 0.0 0.22, 0.22, 0.9, 0.0 0.0, 0.0, 0.0, 1.0); Your color matrix for mapping ...
68,999,980
69,000,126
Finding the N-th term of a Cantor set of rational numbers efficiently
George Cantor gave a proof that a set of rational numbers is countable. It is possible to find the n-th term of it using the method shown in this image 1. I have found the solution here 2. But it is very slow for big numbers, as I have the n that can be up to 10^18. Is there any way to do this fast?
The problem you face is an algorithmic one. If you try to navigate with a den and num variable, you'll need to take 10^18 steps. your program will never finish. (well, it might, but we won't be there anymore) The first optimization you can do is to loop over the diagonals. You'll only need to iterate over roughly 10^9 ...
68,999,989
69,002,949
How to use wait_for in a looping thread?
I want to have a thread (std::thread) that does its work every 60 seconds, otherwise sleeps and instantly returns if the outside requests it. std::jthread is not an option, I'm limited to C++14. std::condition_variable cv; //Thread1: void ThreadWork { while(cv.wait_for(someLock, 60s) == std::cv_status_timeout) ...
std::future<void> seems to do the trick. // Worker thread setup void Work(std::future<void> killSwitch) { while(killSwitch.wait_for(60s) == std::future_status::timeout) { // ... Stuff } } // Controller thread std::promise<void> killSwitch; std::thread worker{ Work, std::move(killSwitch.get_future()...
69,000,196
69,025,708
Class Templates and Friendship in C++
I am trying to understand how templates and friendship works in C++. So looking/trying out some examples by myself. One such example that i am unable to understand is given below: VERSION 1 #include <iostream> using namespace std; //template<typename T> void func4(); //template<typename T> class NAME; // template<...
Answer 1 There is no error for operator<< because you have used using namespace std; and in the std namespace there is already overloaded operator<<. Answer 3 The quoted statement talks about calling(i.e., using) overloaded operators not defining/declaring them Answer 2 VERSION 1 #include <iostream> template<typename ...
69,000,371
69,000,585
error: no matching function for call to ‘std::vector<std:
I write func to write strings from file to vector and have a error error : error: no matching function for call to ‘std::vector<std::__cxx11::basic_string<char> >::push_back(std::ifstream&) code: //parse file file #include <fstream> #include <vector> const unsigned short numOfStrings=5; void ReadFromFile (std::ifst...
You are trying to push into the vector the ifstream, not reading from it. To read from ifstream, you could have done the following. void ReadFromFile (std::ifstream& thisin, std::vector<std::string>& thisData) { std::string word; while(thisin >> word) { thisData.push_back(word); } }
69,000,422
69,009,647
spidev ioctl return Invalid argument error
I created a simple program to send spi messages using spidev. I have two Raspberry pi 4 model B, one with Ubuntu and the other with the Raspberrypi OS. The program works on Ubuntu, but it does not on the Rasperrypi OS. It returns a Invalid argument error when trying to send a message using SPI_IOC_MESSAGE via ioctl. Co...
It seems like changing int status = ioctl(fd, SPI_IOC_MESSAGE(1), xfer); to int status = ioctl(fd, SPI_IOC_MESSAGE(1), &xfer); resolves the problem. This respects the example of the documentation of spidev.h SPI_IOC_MESSAGE gives userspace the equivalent of kernel spi_sync(). Pass it an array of related transfers, t...
69,000,693
69,000,894
C++ return by rvalue reference
template<typename T> class Stack { private: std::vector<T> elems; public: Stack () = default; Stack (T const& elem) : elems({elem}) {} }; template<typename T> Stack<T>&& dummy(Stack<T>&& a){ return std::move(a); } int main(){ Stack<int> first_a = 10; Stack<int> ...
How does it work? second_a is copy initialised from the return value. Is there a implicit conversion? Yes. The rvalue reference to non-const is implicity converted into the lvalue reference to const that is the parameter of the copy constructor. dummy is quite pointless function. It's just std::move that can be cal...
69,000,833
69,009,121
Boost::log stdout is displayed only after execution when called from bash script
I'm running a php file on a webserver, which executes a bash script. The stdout of the script should be streamed to a file, such that the client can fetch and display it. The script myscript.sh: #!/bin/bash echo "-- starting --" EXE="/home/username/mybinary" ARGS="/home/username/config.cfg" PRE="sudo" $PRE $EXE $ARGS e...
Edit: boost::log will disable its default output stream whenever another one is active. To circumvent that, add a custom console log like so: ... #include <boost/log/utility/setup/console.hpp> ... boost::log::add_console_log( std::cout, /* use stdout */ boost::log::keywords::auto_flush = true); /* auto flush af...
69,001,345
69,001,420
Assigning a reference with if statements?
In C++, we can assign a reference using the conditional operator as such: int main (int argc, char *argv[]) { int i, j; int &k = (false) ? i : j; } Is it possible to do this with if-else statements? I don't see how you can do it because you can't reassign a reference.
Sure, but you probably don't want to. int main(int argc, char *argv[]) { int i, j; bool cond = false; int &k = [&]() -> int& { if (cond) return i; else return j; }(); } Or, if you're allergic to stupid lambda tricks: int& pickARef(bool cond, int& trueRef, int& falseRef) { if (cond) { return...
69,001,846
69,001,921
Can anyone please Explain the recursion logic of this program?
#include <iostream> template <int N> { class P { public: static void print() { P<N-1>::print(); std::cout << N << std::endl; } }; template<> class P<1> { public: static void print() { std::cout << 1 << std::endl; } }; int main() { const int N = 10; ...
Can you understand this program? void p10_print() {p9_print(); std::cout << 10 << std::endl;} void p9_print() {p8_print(); std::cout << 9 << std::endl;} void p8_print() {p7_print(); std::cout << 8 << std::endl;} void p7_print() {p6_print(); std::cout << 7 << std::endl;} void p6_print() {p5_print(); std::cout << 6 << st...
69,001,933
69,002,154
C++ dll for VBA - problem with reading/encoding strings
I need to read entries from old-fashioned INI-file with a DLL and after some manipulation export them to VBA code. The c++ code for the function looks like this: BSTR __stdcall GetSectionEntry(LPCSTR sSection, LPCSTR sEntry) { LPCTSTR gszINIfilename = "C:\\test\\test.ini"; TCHAR localStr[64]; GetFile...
CComBSTR bstrt(localStr); return bstrt; This return statement converts the CComBSTR to a BSTR, and returns that, and then destroys the CComBSTR since it's no longer in scope. When the CComBSTR object is destroyed the string is freed. Try return bstrt.Detach(); which detaches the string from the CComBSTR object...
69,002,535
69,002,653
vector.resize isn't increasing size of the vector in c++
I am a c++ beginner. I was practicing how to work with class and header files. The program manages Rents of a building. It has a Rent class and a Floor class. Here're some definitions of those classes. rent.cpp (Copied important functions only) Manages information about Floors and has vector<Floor> paid_by_floors; pr...
The Floor Rent::get_floor(int index) { return this->paid_per_floors[index]; } returns a copy of the Floor object and you apply the reservation to the copy while the original object is still unchanged. You should return a reference so that you will change the original object: Floor& Rent::get_floor(int index) { ...
69,002,900
69,197,622
OpenXR - unresolved external symbol
I keep getting unresolved external symbol on xrCreateSpatialGraphNodeSpaceMSFT and at this point I just ran out of things I could try to make this thing work. I wouldn't call myself an experienced programmer by any means so I guess it is very possible I'm just doing something very stupid. I'll be very thankful for any ...
xrCreateSpatialGraphNodeSpaceMSFT is not a core OpenXR function (as indicated by the MSFT suffix). You must first retrieve a function pointer to it, as explained here. Also, be sure that the corresponding extension (XR_MSFT_spatial_graph_bridge) is enabled when creating the OpenXR instance, as described here. Finally, ...
69,003,217
69,003,422
Question about the 'Stack' basic problem (C++)
I am a student studying basic algorithm. I wrote a code to get the sum of all the elements by stl:stack. #include <bits/stdc++.h> using namespace std; int main(void) { ios::sync_with_stdio(0); cin.tie(0); int k; cin >> k; stack<int> s; int a...
There is a problem with the for loop terminating condition. for (int i = 0; i < s.size(); i++) Before the 1st iteration: i = 0 and s.size() is 5 so i < s.size() is true Before the 2nd iteration: i = 1 and s.size() is 4 so i < s.size() is true Before the 3rd iteration: i = 2 and s.size() is 3 so i < s.size() is true B...
69,003,319
69,003,796
deleting node using free
When I use delete p in deleteAlternateNodes(), I am getting a runtime error. But, when I use free(p), the code works fine. What is the reason for this? Node contains the data and a pointer to the next node: #include <iostream> class Node { public: int data; Node * next; Node(int data){ thi...
There are a number of problems with your code. Your deleteAlternateNodes() function is simply broken, and is causing undefined behavior, which is why your code is crashing. Specifically: it is not handling the case where head is NULL for an empty list. inside the while loop, when p reaches the last node in the list, ...
69,003,420
69,234,093
Best practice for compatibility with 32-bit systems for softwares using version dependent data files?
In the easy case, when the program is independent of any external data-base, one could write something of the form: #include <stdint.h> #if UINTPTR_MAX == 0xffffffff /* 32-bit */ typedef some_type_for_32_bit_version Type; #elif UINTPTR_MAX == 0xffffffffffffffff /* 64-bit */ typedef some_type_for_64_bit_version Type; #...
There are two things you need: You only want to write one parser that can be used in both configurations depending on a flag in a file. The concept that helps here is templates. In C++, you can use templates to make a function or class work for multiple types. There is no real nice mechanism for this in C, so there it...
69,003,592
69,003,745
How to call a hidden method from two times inherited base class in C++?
Consider a class D inherited from two classes B and C, each of which inherits not-virtually class A. There is a method f in A, and the same named method in B hiding the method from A. I would like to call A::f() from B-base class of D object as follows: struct A { void f() {} }; struct B : A { void f() {} }; struct C :...
Are they right in doing so according to the standard? Yes. The nested name specifier in A::, B::A, or D::B::A all serve the same purpose, to name the class A. [basic.lookup.classref] 4 If the id-expression in a class member access is a qualified-id of the form class-name-or-namespace-name::... the class-name-or-nam...
69,004,879
69,004,973
C++ Visitor Pattern with variable return types
I have the following setup: class IVisitor{ public: virtual SomeType visit(IVisitable& visitable) = 0; }; class IVisitable{ public: virtual SomeType accept(IVisitor& visitor) = 0; }; class ConcreteVisitor : public IVisitor{ public: SomeType visit(IVisitable& visitable) override { return calculateS...
Several options: Don't return anything, handle the value inside the visitor. The visitor is completely free to store or handle any return value and type. Return a variadic type (std::any or std::variant). Note that using them requires you to find out the actual type, which is kind-of similar to your original problem ...
69,004,895
69,005,789
nlohmann::json usage with better_enum
Is it possible to use better enum(https://github.com/aantron/better-enums) with nlohmann::json(https://github.com/nlohmann/json)? I'm trying to migrate a integer/short field to a better_enum generated class. i did try to add to_json and from_json methods still i'm receiving at compile time. error: static_assert failed...
Yes. From nlohmann::json's documentation: How can I use get() for non-default constructible/non-copyable types? There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload. In this case, you'd probably want something like: namespace ...
69,005,109
69,005,127
why does define conflict with enum class?
Here is a small code in which the conflict occurs. is there any way to get around this correctly? #define DEBUG 0 enum class TypeEnum : int { DEBUG = 0, INFO = 1 };
It's the nature of the preprocessor. Lines beginning with # are commands to the preprocessor. #define is a command that defines a text replacement, which will rewrite your code when preprocessed. In this case, all instances of DEBUG will be replaced with 0, so the code becomes: enum class TypeEnum : int { 0 = 0, ...
69,005,795
69,006,051
Passing this pointer and arguments of class method to local lambda function at compile time
Suppose you have a scenario when you want to create a constexpr lambda inside a method for calculating something at compile time. struct A { int a; constexpr A(int a) : a(a) {} constexpr auto operator+(const A& rhs) { constexpr auto l = [&]() { return A(this->a + rhs.a); }; ...
You can't capture the a members of this and rhs (by reference) and maintain constexpr validity1; however, you can pass those members as by (const) reference arguments to your lambda: struct A { int a; constexpr A(int a) : a(a) { } constexpr auto operator+(const A rhs) { constexpr auto l = [](const i...
69,005,802
69,006,041
istream_iterator behavior misunderstanding
The goal is to read 16 bit signed integers from a binary file. First, I open the file as an ifstream, then I would like to copy each numbers into a vector using istream_iterator and the copy algorithm. I dont' understand what's wrong with this snippet: int main(int argc, char *argv[]) { std::string filename("test.b...
First off, to read a binary file with ifstream, you need to open the file in binary mode, not text mode (the default). Otherwise, read operations may mis-interpret linebreak bytes and translate them between platform encodings (ie, CRLF->LF, or vice versa), thus corrupting your binary data. Second, istream_iterator uses...
69,005,905
69,005,980
C++ primer 5th edition ch 19 Bitfieds
I have this example from C++ primer 5th edition. ch-19 Bit fields: typedef unsigned int Bit; class File { Bit mode: 2; // mode has 2 bits Bit modified: 1; // modified has 1 bit Bit prot_owner: 3; // prot_owner has 3 bits Bit prot_group: 3; // prot_group has 3 bits Bit prot_world: 3; /...
The mode field is not being treated as a bitmask, and the modes type is not defining values in powers of 2. So you should not be using bitwise operations to set/query the mode, for exactly this reason that EXECUTE shares bits with READ and WRITE, which goes against your desire to have each mode be independent. In a pro...
69,005,937
69,065,318
Removing titlebar from Qt window while keeping the default window borders
I'm trying to remove the default Windows titlebar from my Qt window (QT version 5.12.2 and using C++) while still keeping the window borders. I've more or less achieved this using the flag Qt::CustomizeWindowHint. However, this changes the window borders to white lines instead of the default borders. Example of how the...
Your description isn't really clear. One should not be using a QMainWindow for a logon/in dialog. Having said that I created an application on Ubuntu 20.04 (should build fine for you as I used qmake). You can download the project zip here. When the application starts it looks like this: After clicking on "golden" it l...
69,006,371
69,006,436
Why is unlocking an unlocked std::mutex UB?
Unlocking a std::mutex that wasn't locked is UB. Why is this so? Why doesn't it just have no effect, as the mutex isn't locked yet, or was already unlocked, so what's the harm of calling unlock again?
Unlocking std::mutex that wasn't locked is UB. Why is it so? Why isn't it just have no effect, as mutex isn't locked yet, or was already unlocked, so what's the harm of calling unlock again? Because that would have a cost. That would require every implementation to contain the necessary internal checks to ensure this...
69,006,609
69,006,670
C++ SFML Failed to load image, reason: Unable to open file
I am trying to display an empty window in C++ using the SFML library. However, it gives me an error when I am loading an image with loadFromFile. Failed to load image "enemy.png". Reason: Unable to open file The image, "enemy.png" is in the source files directory (Using Visual Studio 2019), as well as the main.cpp fi...
You do not specify the path to you png file, so the "current working directory" is used. This is NOT reliable, as the Visual Studio may use the project folder or something else. You can also change that in the Progect's properties. For Windows, I suggest to keep your assets in the path relative to the folder containing...
69,006,612
69,095,051
std::unique_ptr reset() order of operations
Calling void reset( pointer ptr = pointer() ) noexcept; invokes the following actions Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order: Saves a copy of the current pointer old_ptr = current_ptr Overwrites the current pointer with the argument current_ptr = ptr I...
It's often useful when analysing a prescribed order of steps, to consider which ones could throw and and what state that would leave everything in - with the intent that we should never end up in an unrecoverable situation. Note that from the docs here that: Unlike std::shared_ptr, std::unique_ptr may manage an object...
69,007,366
69,007,414
Is it good to use int_fastN_t to replace intN_t
I just read this link: The difference of int8_t, int_least8_t and int_fast8_t? and now I know that int8_t is exactly 8 bits whereas int_fast8_t is the fastest int type that has at least 8 bits. I'm a developer who develops backend processes with c++11 on Linux. Most of time I don't need to worry about the size of my pr...
So I'm thinking if it's good to use int_fast8_t everywhere No. It's not good to use it everywhere. I still want to know if there is any drawback if I change all of intN_t into int_fastN_t The main drawback is that the size of the integer won't be exactly N bits. In some use cases, this is crucial. Another potential...
69,007,947
69,008,077
What is the correct way to return a template lambda function?
I am experimenting with lambda functions in C++, and I'd like to make a function that is roughly equivalent to the take function in Haskell. take :: Int -> [a] -> [a] Given an integer n, and a list containing any type a, it returns a the first n elements of the list. I'm attempting to do this with a curried function i...
take is a function template with a non-deducible template parameter. Template parameters can be deduced from function arguments when corresponding function parameters depend on template parameters; but int does not depend on T. In contrast to how type inference works in some other languages, C++ doesn't allow to deduce...
69,008,008
69,384,543
TinyGSM c++ CRTP implementation
I am trying to understand the internals of https://github.com/vshymanskyy/TinyGSM/tree/master/src and am confused with how the classes are constructed. In particular I see that in TinyGsmClientBG96.h they define a class that inherits from multiple templated parent classes. class TinyGsmBG96 : public TinyGsmModem<TinyG...
Is this a common pattern in c++? Yes, it is called CRTP - curiously recurring template pattern. Why not use function overriding in this case? override relies on virtual tables, causing extra runtime overhead. What is the thinking behind this implementation? Say, we want a class hierarchy with overridable methods....
69,008,219
69,008,450
What is the best data structure for storing a fixed length collection of named constants that can be used in a switch without explicit casting?
What is the best data structure for storing a fixed length collection of named constants that can be used in a switch without explicit casting? I want to write clean code that looks like this: enum class EventType : uint8_t{ NOTE_ON = 9, NOTE_OFF = 8, CONTROL_CHANGE = 11, CHANNEL_PRESSURE = 1...
Cast the condition for the switch to the enumeration type: switch(static_cast<EventType>((Status & 0xF0)>>4)) {…}
69,008,489
69,023,332
Access index of current element in range-for loop c++20
In a pre-c++20 question Access index in range-for loop (answer), it was mentioned that 2020 note: It would probably be more wise to use a lambda-based solution instead of macro trickery. Could someone post the lambda-based solution for c++20? Are there any other solutions new to c++20? Edit: I have a main loop which...
After looking into defining a view interface, I decided to use range-v3. There are several things missing from std::ranges https://stackoverflow.com/a/68172842/11998382, and until they are added in future standards, it is sensible to use range-v3 rather than repeatedly attempting non-trivial implementations yourself.
69,008,855
69,010,458
Copy the contents of std::ofstream into an std::string
I have an std::ofstream object that hasn't been flushed yet. Is there a way to get the contents of this ofstream and store it into a std::string? What I want essentially is: std::ofstream ofs("somefile.txt"); ofs << "stuff"; someMethod(ofs); //This method streams into ofs as well ofs <<"blah"; yetAnotherMethod(ofs); //...
No. "the contents of this std::ofstream" is nonsensical. The file has contents, the stream is a handle that represents writing to the file. Either flush ofs and read the file, or use std::ostream & in place of std::ofstream &.
69,009,171
69,011,367
Legacy code giving core dump when compiled on new OS
I am working on a legacy c/c++ project. The project initially was on UNIX and then they migrated to Linux many years back. Now, we upgraded to RHEL 7.9. Since we upgraded, we compiled all the old code with new dependent libraries. The code has the following thing... #include <pwd.h> ... { struct passwd *pwd; ...
You're a victim of undefined behavior due to dereferencing through an uninitialized pointer. It looks like whoever commented out pwd = ACMgetpwuid(primuid) broke the code that follows. At the very least they should have commented out both if statements. pwd is uninitialized, so its value is indeterminate; it can depend...
69,009,464
69,009,535
Populating a buffer in C++
I am trying to populate this entire buffer that I created with the numerical value 9. This buffer is suppose to be 1024 MB I know I can create the buffer like this. LPVOID buffer = VirtualAlloc(nullptr,(1 * 1024 * 1024) * 1024, MEM_COMMIT,PAGE_READWRITE); My question is how can I populate this buffer. Basically what I...
Standard C Library has also memory functions in the string header file. #include <string> memset(buffer, 9, (1 * 1024 * 1024) * 1024)); or just use the for loop and do explicit type casts. You can do everything you want with memory in C++ uint8_t* buffer_as_int = static_cast<uint8_t*>(buffer); for(size_t i=0,sz=(1024...
69,009,468
69,009,879
Call a derived member function from parent class
I need to call B::f() in the thread member function. What I get is "pure virtual method called". How can I do this? I assume all this happens because of &A::thread_f in the A initializer list where I explicitly name a scope. class A { protected: std::thread _thread; A() : _thread(&A::thread_f, this) { } ~...
as @Evg says, by starting a thread,A ctor call member function f of B before constructing B. The solution is to start thread after B is constructed. #include<iostream> #include<vector> #include <stdlib.h> #include <thread> using namespace std; class A { public: ~A() { _thread.join(); } void start()...
69,010,408
69,010,457
How to output enum elements using cout?
I am trying to output a element of enum I declared but for example, when I input push_ups, it outputs a number like 8621623 instead of showing push_ups. I have no idea why. I am Japanese so I am sorry if my English is broken. Thank you so much. #include <iostream> #include <string> using namespace std; enum exercise {...
I am trying to output a element of enum I declared but for example, when I input push_ups, it outputs a number like 8621623 instead of showing push_ups. In the operator>> overload, std::cin accepts integers so push_ups isn't an integer, so std::cin will fail and and the line i = static_cast<exercise>(tmp); will be sk...
69,010,464
69,010,637
What is time complexity of stoi (string to integer) function in C++?
implementation of Stoi function can be seen here what is time complexity of above mentioned stoi function?
The time complexity of std::stoi is unspecified. A conforming implementation can use any algorithm that eventually generates the correct result. As a quality-of-implementation issue, it will probably do a linear scan through at most logbase(INT_MAX) + 3 digits, which is bounded above by sizeof(int) * CHAR_BIT. That's O...
69,010,585
69,014,564
C++ class Design with Inheritance
class Base { public: static int GetType_S() { return 1; } virtual int GetType() { return GetType_S(); } }; class Son1 : public Base { public: static int GetType_S() { return 2; } virtual int GetType() { return GetType_S(); } }; My Ques...
You can have a class template that each SonN inherits from, which in turn inherits Base. template <int Type> class Middle : public Base { public: static int GetType_S() { return Type; } virtual int GetType() { return GetType_S(); } }; class Son1 : public Middle<2> {}; class S...
69,010,718
69,011,439
Deleting node containing address of other node
I know the logic in the code given below is wrong but I have doubts about what happens when we delete p having the address of the next node. What will the destructor do? will it go to all the node make them null until the Next in node p don't become null Also tell me what destructors do to memory. I have read many arti...
In this statement of the operator delete delete p; all nodes that follow the node pointed to by the pointer p (due to the data member next) will be deleted. So the function deleteAlternateNodes invokes undefined behavior because all nodes pointed to by the expression q->next that is assigned like q->next = p->next...
69,010,889
69,011,532
C++ output window not working as expected
ok so I just started learning today, This simple code works as expected when I run it in the integrated terminal but not in the output window, I'm not able to type in the numbers, any suggestions on how to solve the issue ? Executed in output window Executed in terminal window
As described in this Question: Cannot edit in read-only editor VS Code. The VS Code Output window is read-only. So you cannot input any values there. And as your code requires input, it will only work in a terminal (as you can input values there).
69,010,978
69,011,116
Error: Unresolved external symbol error in C++
The compilation issue is caused by the global variable [ All_Sockets ], here is the minimal example main.cpp #include <winsock2.h> #include <windows.h> #include <vector> #include "global.h" int main() { std::vector<SOCKET> All_Sockets(10, INVALID_SOCKET); // definition of global var getchar(); return...
You must define All_Sockets as global variable. Currently, All_Sockets is defined as local variable, so All_Sockets must be defined above main function. std::vector<SOCKET> All_Sockets(10, INVALID_SOCKET); // definition of global var int main() { getchar(); return 1; }
69,011,063
69,011,290
How to new a dynamic array after cin
I'm trying to make a class that contains a pointer, which is the core of a dynamic array. How to overload the operator >> so I can cin >> to the pointer without know how many characters are going to put? I was trying: #include <iostream> class MyString { private: char* str; size_t length; public: //some co...
A naive implementation would use is.get() to retrieve one character at a time, and append it to other, resizing if needed. And stop when std::isspace(chr) is true, of course. For that, you need to dynamically allocate memory and keep track of how much space you are using / have available in the implementation of MyStri...
69,011,254
69,011,318
The function call inside sizeof doesn't invoke it? C++
Consider this code, I am trying to print the sizeof return value of the function: int f(int); int main() { std::cout << sizeof(f(2)) << std::endl; } This surprisingly (for me at least) prints 4. But should this give me a link error as the function is not defined? Are functions inside sizoef not invoked? Is there ...
Yes, according to cppreference: When applied to an expression, sizeof does not evaluate the expression [...] More on unevaluated expressions here
69,011,431
69,012,109
Building and deploying C++ through docker multistage build vs mount
I am trying to build a custom C++ tool using docker that has a number of custom library dependencies. There are three libraries: libA, libB and libC. libB depends on libA, and libC depends on libA and libB. On my home system, I would usually update the source for libA and then make install everything downstream from it...
You do not typically want to use volumes for your application code or dependencies. A best practice is for a Docker image to be self-contained. You might run across Docker setups for interpreted languages (especially Node) that make heavy use of volumes and bind mounts, but these really just boil down to running Node...
69,011,480
69,011,714
Decompose ligatures (preferably with ICU)
I'm looking for a clean way to decompose ligatures (e.g. œ -> oe) in a Unicode string. Is there a way to do this without enumerating all the rules one by one? Something like this rule for removing diacritical marks but for ligatures instead.
Reading the ICU documentation on transforms, it seems you need this one Latin-ASCII So I suppose passing doing something similar as your linked question should work (code is untested): #include <unicode/utypes.h> #include <unicode/unistr.h> #include <unicode/translit.h> std::string asciiifyUTF8(const std::string& str...
69,011,701
69,023,303
Is there any ways to accept implicit conversion from one element initializer list but not a single value?
The question itself may be confusing, so I'll describe it in detail here. Suppose we have a type S that represents a 1-dimensional vector (the linear algebra one, not the std one). Since it's kind of an array, so it's good if it behaves like std::array<int, 1>. Obviously, we don't want to allow construction with just a...
This isn't possible. Since S is not an aggregate and the initializer-list is not empty, you go straight to considering constructors for return {0};. That's the same overload resolution as for the (non-list) copy-initialization for return 0;, except that explicit constructors are disallowed rather than disregarded. Od...
69,011,767
69,012,737
Handling large http response using boost::beast
The following code use to get http response message: boost::beast::tcp_stream stream_; boost::beast::flat_buffer buffer; boost::beast::http::response<boost::beast::http::dynamic_body> res; boost::beast::http::read(stream_, buffer, res); However, In some cases, based on the preceding request, I can expect that...
In general, you can use the http::buffer_body to handle arbitrarily large request/response messages. If you specifically want to read/write from a filesystem file, you can have the http::file_body instead. Full Demo buffer_body The documentation sample for buffer_body is here https://www.boost.org/doc/libs/1_77_0/libs/...