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,932,872
68,933,013
How do sort operator works?
(Here a is an array, asize is the size of array.) My question is that can someone explain why sort requires 'a' and 'a + asize' in it and what it does with it?
a is an array. In various contexts, when an array is referring to by just its name, it will decay into a pointer to its 1st element. Adding asize to such a pointer will perform pointer arithmetic to advance the pointer by asize number of elements. std::sort() takes 2 iterators as input, denoting a range of values [star...
68,933,036
68,933,514
How to define a multidimensional array in C++ with 'n' rows and 'm' columns and iterate values using For Loop?
I want a program that asks the number of rows and columns of the multidimensional array and then using For loop iterate values in the array. #include<bits/stdc++.h> using namespace std; int main() { int n, m, x; int a[n][m]; cin>>n>>m; for(int i; i<n ; i++) { for(int j; j<m ; j++) {...
You can't declare the array unknown size. You must do it dynamically. #include <iostream> using namespace std; int main() { int n = 0, m = 0; //. Get the matrix's size while (true) { cout << "Input the row count: "; cin >> n; cout << "Input the column count: "; cin >> m; if (n...
68,933,128
68,943,585
Best Design Practices for Passing Around Multithread Data?
I'm trying to create a clean and efficient design for passing off events to a background thread for evaluation, then return a selected result to the game thread. This is my initial design //Occurrence object passed from director on game thread to background thread OccurrenceQueue //Execute BackgroundThread::Evalua...
I found a perfect solution. As these events aren't particularly time sensitive, I just use Unreal Engine's AsyncTask() to schedule an async task on the game thread from my background thread. As @Pepjin Kramer pointed out is the same as std::async. So simple it's basically a slap in the face.
68,933,615
68,933,656
Define array in c++ and use it in struct
I want to define array of char in header file: #define name char[5] and after to use in this define in struct like this: struct dog{ name nameOfDog; int ageOfDog; }; but it makes me the following error: "Brackets are not allowed here; to declare an array, place the brackets after the name" Is there another ...
You want a type-alias, not a macro. This should work fine in C and C++: typedef char name[5]; struct dog { name nameOfDog; int ageOfDog; };
68,933,880
68,951,646
Get a tuple element in runtime
Reading for how to access a tuple element in runtime, I fell on the following implementation getting-tuple-elements-with-runtime-index I tried this myself using gcc 11.2 . I called the API for retrieving the tuple but I get the following error : In instantiation of 'constexpr std::tuple_element >::type& (* const runt...
The example codes can be rewritten. Since multiple return types are not possible in C++, so that you will have to get it via a lambda function passed as an argument. The same approach was also mentioned by the guy in the comment #include <tuple> #include <utility> #include <type_traits> #include <stdexcept> template<...
68,933,980
68,934,100
Issue in reinterpret_cast
struct A { uint8_t hello[3]; }; struct B { const struct C* hello; }; struct C { uint8_t hi[3]; }; B.hello = &reinterpret_cast<C &>(A); Assume that I have filled the structure A with values 1, 2, 3. If I print B.hello.hi[0], I get 0. Instead, I should have got 1. Am I doing casting wrong? I have checked ...
Casts work on instances not classes, so you need to cast an instance of A not A itself #include <cstdint> #include <cassert> struct A { uint8_t hello[3]; }; struct B { const struct C* hello; }; struct C { uint8_t hi[3]; }; int main() { A a{}; a.hello[0] = 1; a.hello[1] = 2; a.hello[2] ...
68,934,546
68,945,944
Why it is impossible to make qobject_cast for QPropertyAnimation
Here is the QPropertyAnimation' creation code: void CustomGraphicsScene::addAnimation(AnimatedPixmapItem* item) { auto propertyAnimation = new QPropertyAnimation { item, "SpriteFrame" }; connect(propertyAnimation, &QPropertyAnimation::destroyed, this, &CustomGraphicsScene::deleteAnimation); ...
qobject_cast not only does a casting but also verifies that the QObject is still alive using the QMetaObject, for example if you print propertyAnimation->metaObject()->className(); at the time of building the object it will return QPropertyAnimation, but in the slot associated with destroyed sender()->metaObject()->cla...
68,934,560
68,935,979
228A codeforces getting wrong answer code 19
this is a problem on code forces: Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color...
Just a slight modification to your code to count the number of distinct numbers and output 4 - count. #include <iostream> using namespace std; int main() { //input int input[4]; int i, j, count = 1; for (i = 0; i < 4; i++) { cin >> input[i]; } for (i = 1; i < 4; i++) { ...
68,935,018
68,936,090
gcc option std=gnu++17 vs std=c++17
I encountered a compilation error when using g++ (I tried versions 8 to 11) with -std=gnu++17 but the same code can be compiled using the option -std=c++17. #include <complex.h> int main() { int I=0; return I; } With the option -std=gnu++17, this leads to the following error: error: invalid cast from type '__c...
The C++ standard says: (C++17 C.6.1/3): The C++ headers <ccomplex> (D.4.1) and <ctgmath> (D.4.4), as well as their corresponding C headers <complex.h> and <tgmath.h>, do not contain any of the content from the C standard library and instead merely include other headers from the C++ standard library. So C's complex.h ...
68,935,447
68,943,341
Dependency injection tradeoff between constructor and template parameters in C++?
I would like to know when to use dependency injection via constructor and when to use template parameters. Example I have the following class definitions: Interface: /// Interface class class Interface { public: virtual void Method() = 0; virtual ~Interface() = default; }; Concrete: /// Concrete class class C...
It is the same trade off that using templates versus inheritance-based polymorphism always has: template instantiation happens at compile time and thus allows compile time polymorphic behavior. Inheritance-based polymorphism happens at runtime. You can therefore, for example, store a collection of pointers to objects t...
68,935,683
68,936,001
Is it possible to queue a function to a specific thread by its thread id using boost::asio?
I'm trying to queue a simple function on a specific thread by its thread id. I don't need to stop the thread, just post a function to it. The function only needs to be executed by a specific time frame. I've been thinking of using asio::post to send the function, but not sure how to find and bind the thread. Is there...
Why would you want to assign the task to a specific thread using the ID? You let asio do that for you. You can make the threads wait at a certain point by calling asio::io_context::run for example. Then as you will post the tasks, a random free thread will be picked from those waiting threads and it will execute the po...
68,935,996
68,936,198
Does C++ offer a thread-safe reference counter?
Is there a thread-safe reference counter class in the standard C++ library, (or as an extension in Visual Studio), or would I need to write this kind of object from scratch? I'm hoping for an object that purely performs reference counting as shared_ptr might, with the exception that it does so across multiple threads a...
The warnings about thread safety w.r.t. std::shared_ptr are If you have multiple threads that can access the same pointer object, then you can have a data race if one of those threads modifies the pointer. If each thread has it's own instance, pointing to the same shared state, there are no data races on the shared st...
68,936,587
68,936,730
what do upper_bound() do?
I am begineer and I dont understand the following. In the code I got the output Now my question is since the upper_bound() operator gives the index of greater value how did the output gave the answer of upperbound as 7 and not 1.
Both the upper_bound and lower_bound functions require the range to be partitioned according to the value you are looking for, essentially being sorted. Since your vector does not meet this criterion, you cannot expect logical results.
68,936,592
68,937,037
Class seems to be movable with user defined destructor
I'm trying to figure out why this code does not compile? I've created user defined destructor, so the move ctor and move assignment operator should not be created. So why complication fails, saying that my class does not fulfill the requirements? #include <iostream> #include <concepts> #include <type_traits> template<...
There is no move constructor in either example. But that's not what std::movable checks. It defers the check you are intesteded in to std::move_constructible. That concept merely checks that an object can be both direct-initialized and copy-initialized from an rvalue. And a copy constructor was able to initialize from ...
68,936,627
68,936,692
Add element in list inside function body, then return
Given the following: #include<iostream> #include<list> class test{ public: int t = 34; }; std::list<test> list; void func(){ test t; list.push_back(t); } int main(){ func(); std::cout<<list.front().t<<std::endl; } It prints 34. Given that list.push_back(test &ref) is called (so the paramete...
list.push_back(test &ref) doesn't mean that the reference is stored. For containers, all elements are copied/moved, or construct in place. Why does the object remain even after the exit of the function? The remained value is a copy. See the reference: void push_back( const T& value ); (1) void push_back( T&& value )...
68,936,666
68,936,731
Avoid crash from std::upper_bound
Whenever I do this: auto itr = ranges::upper_bound(vector, value); If the value is greater than any value in the vector, then it will give me an error/crash (debug assertion failed). I want to avoid this somehow. The only solution I might think of is this: ranges::sort(vector); // or any code which can find the maximu...
From cppreference: Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found. This means that it may return the end iterator. In that case, you are not allowed to dereference it.
68,936,986
68,945,150
Unreal C++ / GetActorOfClass
I’m fairly new to Unreal C++ and I have a bit of trouble finding how to correctly write a GetActorOfClass (singular, not GetAllActorsOfClass) in C++ in order to set a reference to another AActor at BeginPlay. I have included GameplayStatics in the include in the header and cpp of AActor A and also the AActorB.h . Now, ...
Simple answer, just use GetAllActorOfClass and dynamic cast it to your actor subtype if necessary: // be sure to use #include "Containers/Array.h" // as well as #include "Kismet/GameplayStatics.h" // Assuming GameManager is of type AMyGameManagerActor* void ALocalMaster::BeginPlay() { Super::BeginPlay(); AA...
68,937,197
68,942,969
pass multiple class function pointer as function parameter in c++
I am newly learning function pointer and able to pass function pointer between classes. Now i am looking to receive function pointer parameter of all the other classes. fncptr2.h #ifndef FNCPTR2 #define FNCPTR2 class fncptr1; class fncptr2 { public: int implfncptr(int (fncptr1::*add)(int,int)); }; ...
Okay, your question doesn't quite make sense, but it sounds like what you want is a more generic solution. First, I don't use function pointers the way you've got them. This is very C-style, and there are better ways. My definition of "better" means "fits more solutions". There might be a very slight performance hit fo...
68,937,276
68,937,408
Qt Creator giving me [debug:/moc_scheduled.cpp] Error 1, and I have no idea why
My whole code seems to work and to my knowledge I've #included everything. Really really lost on this, and stressing about what to do! Someone please save me in my time of need! :)) Here's my scheduled.h file: #ifndef SCHEDULED_H #define SCHEDULED_H class Scheduled { Q_OBJECT public: Scheduled(strin...
Any object that uses Q_OBJECT in it's declaration should inherit from QObject class. Remove the Q_OBJECT macro call. Or change your header into something like: #ifndef SCHEDULED_H #define SCHEDULED_H #include <QObject> class Scheduled : public QObject { Q_OBJECT public: Scheduled(string *start, string *end, i...
68,937,369
68,937,551
Installing FTP Client (Library) in C++ Ubuntu
I have found this library https://github.com/embeddedmz/ftpclient-cpp on GitHub but how to install it on Linux(Ubuntu) is quite obscure. You will need CMake to generate a makefile for the static library or to build the tests/code coverage program. Also make sure you have libcurl and Google Test installed. You can foll...
After you build the library, there will be a libftpclient.a generated in your build tree. You can install it to your system as follows: In this case, copy libftpclient.a to /usr/local/lib and the two header files in FTP to /usr/local/include. You should then be able to include the header files by adding the -I/usr/loca...
68,937,389
68,945,765
How is my solution slower than given sample solution?
This was the Leet Codeproblem for Aug 26 2021. I submitted several solutions of which this one was the best. However, it took 7 ms and when I saw sample 0 ms solution, I was shocked to find how complex the solution was and how many condition checkings were there. The Question (Editted) Given a string of comma-separate...
Leetcode can run different solutions on different machines in different states - hence you get different results even submitting same code. Sometimes +100ms, thought c++ time is less variative than interpreted languages. Compiler flags are given in faq. Discussions on time measurements inconsistency on leetcode: one, t...
68,937,433
68,940,849
Return std::tuple containing const-reference in C++11
I have something like this (C++11) std::tuple<const MyType&, bool> func() { return std::make_tuple(some_internal_reference, true); } the problem is that in the caller I cannot declare: const MyType& obj; // this does not compile of course bool b; std::tie(obj, b) = func(); An idea is to return the boolean as an o...
Use std::get. It returns reference to stored element. #include <iostream> #include <tuple> using MyType = int; MyType some_internal_reference = 42; std::tuple<const MyType&, bool> func() { return { some_internal_reference, true }; } int main() { auto ret = func(); const MyType& obj = std::get<0>(ret);...
68,937,577
68,939,374
Maintaining a selected object in C++
I wanted to know the best approach to store the reference to an object selected, for more clarity: #include <iostream> using namespace std; class A{ public: int a; A(int b) { a=b; } }; class B{ public: int b; B(int a) { b=a; } }; int main() { A a(1); B b(...
The described use case sounds to me like an Abstract Factory pattern. You parse something, and then return the appropriate type with some set parameters. And the decision of the type will be made at runtime. By Uuing polymorphism, you can create output as you wish. Standard problem of abstract factory is that the signa...
68,937,811
68,937,957
QT : operator after class declaration
Recently I started working on a QT project, but there are more syntax rules than regular C++. While declaring class and its constructor, in header file, we simply write class MyObj : public QObject { Q_OBJECT public: explicit MyObj(QObject* parent = nullptr, <params>, ...) . . <some more declaration...
That's not an operator. That's a standard c++ feature called member initializer list. For example class Test { private: int test_val; some_type some_test; public: Test() : test_val(7), some_test() {} . . //whatever } In this example, when an instance of Test is constructed, the mem...
68,937,958
68,938,257
Gaussian draws in C++ using bind gives different result than drawing from distribution explicitly
I am studying the issue of generating Gaussian draws in C++. As the title says, I seem to get a different result from using bind instead of just drawing from the distribution. That is to say the following code default_random_engine ran{1}; auto normal_draw = bind(normal_distribution<double>{0, 1}, ran); for (int i = 0...
You are instancing a temporary distribution object every loop iteration. This will create a new state every time. When you don't, they are the same (given the random generator is always initialized with the same state): #include <random> #include <iostream> #include <functional> int main() { std::default_random_en...
68,938,175
68,938,551
What happens if "-ffast-math" is enabled when linking?
I use both gcc10 and clang12 in Ubuntu. I just found that if I enable the -ffast-math flag, in my C++ project, there will be an about 4 times performance improvement. However, if I only enable -ffast-math at compile time and not at link time, there will be no performance improvement. What does it mean to use -ffast-mat...
However, if I only enable -ffast-math at compile time and not at link time, there will be no performance improvement. What does it mean to use -ffast-math when linking, and will it link to any special ffast-math libraries in the system? Turns out gcc does link in crtfastmath.o when -ffast-math is specified for linker...
68,938,645
68,945,041
Computing physics and displaying it with GPU only
So basically, I've learnt OpenCL recently and with this new found power I made a physics simulation about 10 times faster. The issue is, I'm only using 10% of my GPU. I'm assuming this is because I'm sending data back to the CPU/Ram before sending it back to the GPU so it can be displayed. Anyone got ideas on how to av...
If you only observe 10% GPU usage, the problem is not sending the frame buffer around. I've done a similar thing, physical simulations on the GPU and real time rendering right in OpenCL, then send the bitmap to the CPU via PCIe and to the display via <Windows.h> SetBitmapBits, back over the GPU. This works very efficie...
68,939,000
68,939,161
Why does insertion sort break down when I remove Key variable
recently, I learned how to use insertion sort. So, i started tinkering with its code. #include<bits/stdc++.h> using namespace std; int main(void) { int arr[] = {4,3,2,10,12,1,5,6}; int n = sizeof(arr)/sizeof(arr[0]); for(int i=1; i<n; i++) { int key = arr[i]; // line a int j = i-1; ...
When you do int key = arr[i];, the value of the key is saved in the variable key. When you do while(j>=0 && arr[j]>arr[i]) instead, you use the current value of arr[i]. At first it is the same, but as the while loop runs, you start modifying arr: arr[j+1] = arr[j]; This will modify arr[i] eventually, when j+1 equals i...
68,939,105
72,546,544
Octave-C++-API and Boost Unit Tests result in Segmentation Fault
I try to unit test my C++ code where I use the octave-C++-API. If I use anything from octave in the boost unit test I get the error: Segmentation fault (core dumped) The compilation works just fine and if use both octave and boost separately it works fine. Does anyone know what I did wrong? Here is my minimal example:...
The solution was to switch to different software versions. With this setup it works: OS: ubuntu 2204 Boost: version 1_74 Octave: version 6.4
68,939,529
68,939,717
How to determine if a variable is a pointer?
I was reading the Wolfenstein 3D code, and I encountered ISPOINTER macro: #define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0) I know we have std::is_pointer, but how does this macro work? I tried and failed with strange behavior which I couldn't explained why it's happend: #define ISPOINTER(x) ((((uintptr_t)(x)) ...
Let's do this in steps: ((uintptr_t)(x)) is simply a cast from whatever x is into a uintptr_t (an unsigned integer type capable of storing pointer values) ~0xffff is a bit-wise complement of 0xffff (which is 16 bits of all 1s). The result of that is a number that is all 1s except the last 16 bits. ((uintptr_t)(x)) & ~0...
68,939,532
68,940,874
no match for ‘operator=’ (operand types are ‘Object’ and ‘<brace-enclosed initializer list>’)
I am trying to create an array of card objects however I keep getting an error: "no match for ‘operator=’ (operand types are ‘Object’ and ‘’)". I feel that I'm making an easy mistake but I'm unclear as to what I am doing wrong. Can someone give me any advice? Deck.cpp Deck::Deck(int maxSize) { //Set Size this->...
#include <iostream> #include <algorithm> #include <vector> #include <string_view> using namespace std; const string_view suits[] = { "diamond", "heart", "spade", "club" }; struct Card { int number; string_view suit; friend ostream& operator<<(ostream& o, const Card& c) { return o << c.number << '.' << c...
68,939,543
68,939,873
Replacing the data in a specific row in the txt file
I'm building a TCP Server application. Two different types of requests come from the client. In the first request type, the client requests a certain number of line information starting from a certain line. For example, the client throws a request like I want to read 3 lines starting at line 5.It's okay so far, I've co...
First read the complete file into memory. Then close the file. Make the modifications in memory. Then, after modifications have been done, write the complete vector to the file. E.g.: #include <iostream> #include <fstream> #include <vector> #include <iterator> int main() { // Open the file and check, if it could b...
68,939,893
68,942,808
My program is breaking before completing all execution
I am trying to find the Multiplication of Matrix with its transpose using Vectors. While Running program is not executing after printing my inputted matrix and breaking without doing any loops and athematic operations. Why does my program ended after 2nd for loop? Where I am wrong? // Multiplication of Matrix by its T...
Okay, first... There are ways to find out where your program is crashing. At the very least, you can add more cout statements, and it will tell you. But it's sort of obvious: vector<vector<int>> vec(row, vector<int> (row,col)); vector<vector<int>> tran(row, vector<int> (row,col)); for(int i=0;i<row;i++) // tran...
68,939,899
68,940,106
Remember a randomly chosen value
I am creating a game where the user plays against the computer. The computer's name is chosen from an array with five values. I created a random number between 1 & 5 and then use it to choose one of the five names at random. I am attempting to save that name as a function so that I can continue to reuse the value throu...
opponent return the memory address of the function. You forgot to just call the function and execute its code, and you re-coded it in your main. Also your function should return the name. This is how you main.cpp should look like : #include <iostream> #include <time.h> #include <cstdlib> #include "constants.h" std::s...
68,940,148
68,940,731
Builder pattern with struct
I'm trying to implement a builder patter in C++. That what i got by now: struct Person { std::string name; uint32_t age; std::vector<std::string> pet_names; }; class PersonBuilder { public: PersonBuilder& SetName(std::string name) { person_.name = std::move(name); return *this; } PersonBuilder& S...
I'm a little worried about unitilized uint32 You initialise it before you use it, so there is no problem in the example. It is however easy for a user of the builder to forget calling one of the setters leaving it with indeterminate value resulting in undefined behaviour. You give it a default member initialiser to a...
68,940,371
68,941,719
Deleters for unique_ptr
There is an array holding unique pointers: std::array<std::unique_ptr<T, deleter<allocator<T>>>> storage; where template<typename ALLOC> class deleter { void operator()( void ) { ... } }; does the deletion as required by unique_ptr. Effectively, it calls the destructor and then deallocates the memory occupied. So...
As @Nicol Bolas points out, "object owned by such unique_ptr<T, empty_deleter<T>>" is nonsensical. I will answer "how to make a smart pointer that sometimes owns and sometimes doesn't own it's pointee". None of std::unique_ptr<T, empty_deleter<T>>, std::unique_ptr<T, deleter<allocator<T>>>, nor std::unique_ptr<T, delet...
68,940,377
68,940,446
returning local struct in a function
im trying to return a local variable from a function. typedef struct _s{ int a; } Somestruct; Somestruct func(){ Somestruct RET; RET.a = 10; } int main(){ Somestruct var = func(); std::cout << var.a(); } will this work? if i doesnt, what do i need to do to make it return the value i want? i have tried to ...
what do i need to do to make it return the value i want? You need to literally ask the program to do that using return RET; typedef struct _s{ int a; } Somestruct; Somestruct func(){ Somestruct RET; RET.a = 10; return RET; // <==== } when i return classes it just returns the pointer that points to the mem...
68,940,602
68,940,764
No operator "<<" matches these operands error between an object and a string literal
The code: catch (test& t) { cout << t /*error here*/<</*to here*/ " is not a positive number"; } causes an error: No operator "<<" matches these operands The compiler (c++ 20) says that the error is the << between t and " is not a positive number". It might be caused because I overloaded the operator wrong? Here...
You have declared one operator<<, and defined a different one. And the wrongly-formed one turns out to be the best match. Replace* this, which you have declared in your class: test & operator << (ostream & , test & ) With this, which you have defined: ostream & operator << (ostream & os, const test & t) Edit: *An as...
68,940,798
68,946,740
vscode shortcut or easier method to add a functions to class
I went up and down of the vscode documentation to find a way to automatically create functions inside the class, every time I am adding a method to a class I need to copy the definition and scroll to the bottom of the page to implement the method. Clion had a great set of tools for this https://www.jetbrains.com/help/r...
https://marketplace.visualstudio.com/items?itemName=amiralizadeh9480.cpp-helper I'm not the creator and just found it. A side note is that it creates implementation for prototype but it doesn't check if it's duplicated which is described in the Known ISSUE section. You need to set CppHelper.SourcePattern to let plugin ...
68,941,019
68,941,094
affect of constexpr on Parameter pack
Why is this code invalid without constexpr: template<typename ...Tpack> auto CalculateSum(Tpack ...pack) { if constexpr (sizeof...(Tpack) > 0) return (pack + ...); else return 0; } int main() { std::cout << CalculateSum(2, 3, 4, 5, 7.5, 6) << '\n'; } whereas if there are only int in the argume...
The reason you need the if constexpr instead of a plain if is that you are trying to return two different types, which is not allowed with automatic return type deduction. With return (pack + ...); the return type is going to be double because one of your parameters is a double. On the other hand, return 0; is going t...
68,941,097
68,963,119
Inner shadow effect for QWidget
I'm trying to add an inner shadow effect to some of my widgets: I've found the QGraphicsDropShadowEffect Class, but it doesn't seem to exist for inner shadow. I've seen InnerShadow QML Type too, but I'm not using QML. Is it actually possible to do without using QML? Maybe using stylesheets?
1. Stylesheet Unfortunately, in the meanwhile Qt style sheets doesn't support something like "box-shadow" in css. One way to workaround is to use a top and left gradient border to mimic the effect. border-left: 20px solid black; border-top: 20px solid black; border-left-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, st...
68,941,451
68,941,920
Shall structured binding be returned from a function as rvalue in C++20?
Consider a C++20 program where in function foo there is a structured binding auto [y]. The function returns y, which is converted in object of type A. A can be constructed either from const reference of from rvalue-reference. #include <tuple> #include <iostream> struct A { A(const int &) { std::cout << "A(const in...
I believe that Clang is correct. TL;DR: some lvalues can be implicitly moved, but a structured binding is not such a lvalue. The name of a structured binding is an lvalue: [dcl.struct.bind]/1: A structured binding declaration introduces the identifiers v0, v1, v2,… of the identifier-list as names of structured bindi...
68,941,727
68,944,608
How to get all file path from C:/ drive?
I'm trying to retrieve all files from the root (C:/) in C++ First of all, I retrieve all logical drives in the computer, then I use the std::filesystem library (specifically the recursive_directory_iterator function in order to loop in directories) DWORD dwSize = MAX_PATH; char szLogicalDrives[MAX_PATH] = { 0 }...
In order to resolve the issue I had to launch VS 2019 in admin (or launch the .exe in admin) + disable Windows Defender. To avoid UAC exception, I also added skip_permission_denied in filesystem option. However, my program still encounter "Sharing Violation error"
68,943,445
68,943,586
Can one function have two different return types?
So today on a test, we had a code, and we had output of the code, and we needed to write the function. std::vector<double> v; auto z = first(v); std::cout << z << std::endl; // OUTPUT: No value! v.push_back(3.14); z = first(v); std::cout << z << std::endl; // OUTPUT: 3.14 Function that we needed to write was first()...
Have first() return a std::optional<T>, where if ve is empty then return std::nullopt, otherwise return v.front(). And then overload operator<< to print the std::optional<T>. For example: #include <optional> template <typename T> std::optional<T> first(const std::vector<T>& ve){ if (ve.empty()) return std:...
68,944,476
68,944,772
What happens if the same static member variable has different values
1.cc struct foo{ const static int bar = 5; }; int main(){ return foo::bar; } 2.cc struct foo{ const static int bar = 6; }; g++ 1.cc 2.cc doesn't give a link error. Does this go against the one definition rule and cause undefined behaviour? Additionally i'm not sure why const int foo::bar; was not even needed as...
You are breaking the One Definition Rule: Class definitions in multiple translation units have to be the same. This makes your program ill-formed, but compiler's don't have to warn you about it. If you had multiple definitions (const int foo::bar;), you would probably run into a linker error. But without any definition...
68,944,672
68,944,798
C++: Can I change a vector type?
Let's assume I have the following code: typedef struct foo{ int x; }foo; typedef struct bar{ int y }bar; struct foobar{ std::vector<foo> foo1; std::vector<bar> bar1; }; Is there any way to change std::vector<bar> bar1; into std::vector<foo> bar1; and erase any data inside? And if so, could this be do...
The way to "change" a variable's type (which is not really possible in C++) from one type to another is to use std::variant to indicate the possible types it is allowed to hold (or, use std::any to hold all types), eg: std::variant<std::vector<bar>, std::vector<foo>> bar1; You could then have bar1 hold a std::vector<b...
68,944,785
68,945,233
OpenGL: How do i control the rendering to make it idle?
Say, my application has a 3D window rendering a tin model of millions of triangles using OpenGL. Goal: For some operations of users, there is no need to update the 3D window. The 3D view can just stay idle with previously rendered content, without repeatly calulate the rotation/translation/scaling/texture things. I ass...
Instead of having a continuous rendering loop, you can use OpenGL only to render your window when the system sends you an event to repaint the window. Additionally you invalidate your own window if you know that the contents of it changed (e.g. due to a reaction to a mouse click). In fact this is the proper way to draw...
68,945,568
68,945,831
NgHttp2 invokes request data handler twice, for one single request
I am running a HTTP2 server by using nghttp2. I am trying to figure out why the on_data handler in the server.cpp is called twice. I know it's called twice because when I send a request that contains data, I get the following log output for a single request in the server. 1 2 But if I don't send data in the request. T...
If you print out also the length of the data frames, there would be more information to reason about. My guess is that the client sends a first DATA frame with length 10 for aaaaaaaaaa and end_stream=false, and a second DATA frame with length 0 and end_stream=true, to signal the end of the stream on the request side. F...
68,945,727
68,945,930
Are you supposed to prototype IAsyncAction/IAsyncOperation coroutines (functions) in the header files?
I am new to C++/WinRT and the concurrency/thread topics for c++. I have an odd issue because I've usually create header files for my .cpp files. I ran into an error when trying to prototype my IAsyncAction coroutines in my .h file. I've reproduced the same error in a new test project. Error: E0311 cannot overload fun...
In the h-file you didn't provide the namespace winrt::Windows::Foundation where the IAsyncAction is defined. You have two options here: (1) move the using namespace winrt; using namespace Windows::Foundation; to the header file or (2) use the full scope: winrt::Windows::Foundation::IAsyncAction DoWorkOnThreadPoolAsync...
68,945,794
68,976,162
Magick++ API: Get PDF page count?
I'm struggling to write a function to get the number of pages from a PDF without using external/additional (ie, other-than-Magick++) libraries for this purpose -- yet, when I execute something like this: #include <Magick++.h> using namespace Magick; int main(int argc,char **argv) { InitializeMagick(*argv); ...
The best I can come up with, if anyone's facing the same problem working with ImageMagick/GraphicsMagick, without including an entire extra library for this one function (PoDoFo, which is unstable, can do this, and poppler can also do it) is to use this based on the code written in the question: #include <Magick++.h> ...
68,945,953
68,946,292
Difference in running C++ program in command prompt and PowerShell
In C and C++ command-line programs, is there any differences between running your programs within command prompt or within PowerShell? (e.g.: exception handling, I/O speed, etc.)
The main difference: cmd.exe provides true binary (byte-stream) conduits, so that >, the redirection operator, can capture an external program's raw byte output. PowerShell, as of version 7.2, only ever uses text (strings) to communicate with external programs, both on in- and output, which means that external-progra...
68,946,264
68,954,141
How to create a variadic struct that takes a "variadic invocable" of the same arity as the ctor parameter?
I am trying to generalize this COM object auto management class, but I am not even sure if it is possible. Currently, I have defined it for 1, 2 and 3 pointers, but I'd like to make it a single implementation for all cases. Manual implementation: #include <concepts> #include <type_traits> #include <Unknwn.h> template...
std::tuple (with std::apply) might help: template <std::derived_from<IUnknown>... Ts> struct AutoManagedCOMObj { std::tuple<Ts*...> tuple_ptrs; template<std::invocable<Ts**...> Invocable> AutoManagedCOMObj(Invocable initializer) { HRESULT hr = std::apply([&](auto*&... ptrs){ return initializer(...
68,946,631
68,947,433
Initialize vector of strings from text files at compile time
I'm working on a project that has a directory of files: myFiles. I need something like: const vector<string> configs = { contents_of_file0, contents_of_file1, ... }; It is desired that the contents of these files be part of the binary, as opposed to being read at runtime. Is there a clean way to do this? Today, there ...
Is there a clean way to do this? There is proposed feature for this purpose that may end up in a future standard. Until then, you can use meta programming: Generate source code from the input file. The generated source should contain the initialiser based on the file. An open source program exists that can do this: x...
68,947,130
68,947,585
uint8_t values issues with vectors
I am trying to create a 10 by 10 grid with uint8_t values. using some coordinates I am trying to place 255 values at those indexes. When I substitute 255 at those coordinates it works fine but as soon as I try to print out the values at those indexes it doesn't seem to be the values I wanted. float grid_width = 10; flo...
I was able to find the solution. the old logic was too complex and not working with different resolutions. So I made a simpler one that does need to take care of rounding up issues. first took each point and tried to go replace values index by index. for(auto i: landmarks) { for(int m = (i[0]/grid_resolution)-2; m ...
68,947,177
68,947,182
When an exception is thrown out of a (create/copy/move) constructor when throwing a previous exception, why is not std::terminate() called?
When an exception is thrown out of a (create/copy/move) constructor when throwing a previous exception, why is not std::terminate() called? Isn’t it disruption of handling the previous exception before the previous exception is caught, which must cause std::terminate()?
No, an exception is considered to be uncaught only after completing the initialization of the exception object (and until completing the activation of a handler for the exception). If an exception is rethrown, it is considered to be uncaught from the point of rethrown.
68,947,529
68,947,574
How to read an array then return it through pointer
I was trying to read an input like this: 5 1 2 3 4 5 The first one is the size of an array, and the other is the array, and the output is just the read array. But using this code, I keep getting this output: 1 2 3 4 5 0 1871824307 62958 7346864 0 7340368 0 I can't really figuring out why. #include<iostream> using na...
by writing while(*p != -1){...; p++;} you are incrementing p until the value p points to is -1. If you want to end the array with -1, you should do some changes to your code #include<iostream> using namespace std; int* readArray() { int n; cin>>n; int *arr = new int[n+1]; //note here the extra 1 for (i...
68,947,828
68,947,852
Why is it not standardized that an exception object is moved to a catch-clause object when catching the exception by value in case it is not elided?
In a throw-expression if the compiler cannot perform copy elision but the conditions for copy elision are met or would be met, except that the source is a function parameter, the compiler will attempt to use the move constructor even if the object is designated by an lvalue; In a catch clause, the following is permitte...
Copy elision in a throw-expression, as any other feature, needs to be implemented before it is available. Moving itself (regardless exceptions) is a must feature of the language, the cost of not supporting this feature would be unforgivable. Applying this already existing feature, moving, in the specified way in the th...
68,947,981
69,023,274
How to setup VS Code project for LLVM building
I want to use VS Code for building & debugging LLVM source code. Is there a good document which explains how to setup project in VS Code for LLVM ? Thanks in advance.
I found the below blog useful : https://developers.redhat.com/blog/2021/04/22/remote-llvm-development-with-visual-studio-code# This talks about remote SSH setup, but all these things can be easily replicated with native vscode install.
68,948,053
68,948,130
Equivalent of srand() and rand() using post-C++11 std library
I have old code that predates C++11 and it uses rand() for generating random ints. However, there is shortcoming in rand(): you can't save and then restore the state of the random device; since there is not an object I can save, nor can I extract the state. Therefore, I want to refactor to use C++11's solution <random>...
You can't even assure that you get the same sequence if you use rand() on another compiler. And no, you can't get random to produce the same sequence as whoever's rand() it was you were using. (Thank goodness. rand() is notorious for being one of the worst pseudo-random number generators of all time.) It is possible fo...
68,948,091
68,948,128
How to define a preprocessor macro name
#ifdef _DEBUG cout<<"key_str"<<key_str<<endl; cout<<"val_str"<<val_str<<endl; #endif I am reading others' code with a _DEBUG macro. I want to print these cout's content to screen. Is there an option to turn it on either in compiling or running the program? I am new to c++.
You can pass definitions with the -D flag to g++: $ g++ -D_DEBUG -g -O0 main.cpp -o main
68,948,432
68,948,458
how to keep insert values from a istringstream to a vector?
I want to take input from the user in a string and insert those values into a vector using stringstream my code looks like this : #include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; int main (){ string s; getline(cin ,s); vector<int>vec; istringstream iss{s}...
It's inserting twice because you don't check if extraction from the stream works. Do this instead: int temp; while(iss >> temp) { vec.push_back(temp); } You could use a for loop if you want to keep the scope of temp to a minimum: for(int temp; iss >> temp;) { vec.push_back(temp); } Lets pretend that there is ...
68,948,522
68,948,905
Is it possible to compile from Windows to Linux with gcc/g++?
Apologies for the beginner question. In short I'm trying to compile a very simple C++ program for Linux from Windows 10. A few answers say "install cygwin" but I'm not sure it's the optimal solution. Would it be simpler to just install Linux and build for Linux from Linux and for Windows from Windows, or do cross-comp...
You have several choices: WSL. WSL(Windows Subsystem for Linux) its linux termanal in windows, so you can compile linux code in windows. This solution is the simpliest and I would recommend to use it. Visual studio. Visual studio has a package that allows you to compile programs for Linux. More details here
68,949,224
68,951,368
Is it possible to have boost multi_index container index one element with 2 key values?
I want to have my boost multi_index container index one element with multiple key values on the same index. Is that possible? struct Student { int Id; std::unordred_set<std::string> Clubs; }; Suppose this student belongs to Technology and Movie clubs, and I have unique hashed index on Id and non_unique hashed ...
You can't do it with a multi_index containing your Student type, but you can use (something based on it) with a different type. using Id_t = int; using Club_t = std::string; using StudentClubs = boost::bimap<boost::bimap::multiset_of<Id_t>, boost::bimap::multiset_of<Club_t>>; StudentClubs student_clubs = /* some data ...
68,949,281
68,949,356
What will a "single variable as a statement" do?
Below is the C++ function in a project I took over lately. Each of the last two statements is just a variable, containing no assignment. What will such kind of statement do? Lately, I saw such kinds of statements usually. __fastcall TCardActionArea::TCardActionArea(TComponent* Owner) :TArea(Owner,"CardActionArea") { ...
Normally, these statements do not do anything, and it is definitely not a common practice to write them. Maybe the author just wanted to explicitly note that they do not need to assign any values to these members (although a comment would do better). Maybe this is some hack for a particular compiler to prevent some opt...
68,949,303
68,950,821
Which is the most specialized function template in the context of taking the address?
Consider this example #include <iostream> template<class T> void fun(T&){ //#1 std::cout<<"selected\n"; } template<class T> void fun(T&&){} //#2 int main() { void(*ptr)(int&) = &fun; //#3 } Both GCC and Clang report an error with the diagnosis "ambiguous". According to [temp.deduct.funcaddr#1], such two f...
GCC and Clang are wrong to yield and ambiguity in overload resolution, as per your own analysis. This arguably relates to CWG 1164, albeit not being in the context of a function call, the intent should arguably be similar as for the case of functions calls as per CWG 1164 [emphasis mine]: 1164. Partial ordering of f(T...
68,949,357
68,949,559
C++ masking all characters of a string except for the last n characters with <algorithm>
In C++, how to mask all characters of string except last in character using <algorithm>? ie; I have a string std::string barcode = "300001629197835714"; I would like to get output as **************5714 This program can be easily done in a conventional way, std::string barcode = "300001629197835714"; std::stri...
Here's a solution using the algorithm library and iterators. I'm using std::prev to get an iterator 4 characters before end(), then std::fill to replace the digits in the range [begin, end - 4) with '*'. #include <algorithm> #include <string> #include <iterator> #include <iostream> int main() { std::string barcode...
68,949,471
68,952,185
Can #undef affect member functions in C++?
I have an Unreal Engine 4 project with several plugins. On of these plugins contains a FileHelper class with a method CreateFile. This has worked fine for months, but in a recent commit, a different plugin added a call to FileHelper::CreateFile and now sometimes I get a linker error saying that CreateFileW is not a mem...
Following shows a problematic case: #define CreateFile CreateFileW struct S { void CreateFile(); // Actually void CreateFileW(); }; And then #undef CreateFile void foo() { S s; s.CreateFile(); // Error, "expect" s.CreateFileW() } As #define might modify meaning of code (locally), #undef "cancels" that mod...
68,949,685
68,950,025
Kth missing positive integer
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Find the kth positive integer that is missing from this array. Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer ...
There are at least two problems in your code. First, the flag is not reset to 0 for each loop leading to infinite loop Second, when a number is found in the array, the code will be stuck in the while loop too because there is no break statement. Here is a code that works. I've move the flag declaration inside the loop ...
68,949,838
68,950,069
googletest can't link to DUT
When I try to link the code that shall be tested to my tests I get undefined refrence. When I use the same function in the same sourcefile there is no problem. Here the linker error g++ -o "VW_Test" ./tests/scaleSignalTests.o ./src/gtest-death-test.o ./src/gtest-filepath.o ./src/gtest-matchers.o ./src/gtest-port.o ....
You define the function in a C file, that has default extern "C" naming convention. The function in .h must be extern "C" int multiplyInteger(int, int, int*); Or the entire header file declarations must be enclosed in #ifdef __cpluplus extern "C" { #endif ... #ifdef __cpluplus } #endif
68,949,906
68,952,693
How can I insert into vector with a class including condition variable?
I try to insert into vector with a class including condition variable,my code as follow: class LockRequest { public: LockRequest( ) : granted_(false) {} bool granted_; }; class LockRequestQueue { public: std::list<LockRequest> request_queue_; std::condition_variable cv_; // for notifying blo...
std::condition_variable is not copy constructible, move constructible, copy assignable or move assignable. So adding it directly to any class as a member would also add those qualifications to that class too. In order to avoid that, we use an extra level of indirection, for example, a std::unique_ptr to hold a pointe...
68,950,071
68,950,103
Can I do in c++ something more than just 'x++', or 'x--'?
I made here a program to do 3x+1 math problem. So I am asking, if I could write in a c++ code something like x/2;, or x*3+1. These stuff what i put here are with mistakes. Then, is it possible in c++ to do that? If yes, how? Here's the code: #include <iostream> using namespace std; int main() { cout << "Write an in...
Give value to the same variable with assignment operator ('='): x = x*3+1; or x = x/2;
68,950,406
68,950,579
What is pointer() in unique_ptr?
I read now unique_ptr source code in libstdc++. public: typedef _Tp* pointer; typedef _Tp element_type; typedef _Tp_Deleter deleter_type; // Constructors. unique_ptr() : _M_t(pointer(), deleter_type()) { static_assert(!std::is_pointer<deleter_type>::value...
This expression pointer() zero-initializes the data member pointer of the class that has a pointer type. For pointer types it means setting a pointer to a null pointer. From the C++ 14 Standard (8.5 Initializers) 11 An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized and ...
68,950,748
68,950,800
Instantiate typename object inside class template with any set of parameters
Consider next example: template<typename T> class A { public: A(int p1, int p2, //any arguments needed for T constructor); private: std::vector<T> vec; }; template<typename T> A<T>::A(int p1, int p2, //any arguments needed for T constructor) { for(size_t i = 0; i < 10; ++i) { vec.push_back(T(//...
Yes. You don't need the loop, either template<typename T> class A { public: template<typename... Args> A(Args&&... args) : vec(10, T(std::forward<Args>(args)...)) {} private: std::vector<T> vec; };
68,950,868
68,951,102
overriding the what function in std::exception in c++
I'm trying to override the what function in order to print customized error messages of my own. all messages have the same beginning and therefore I thought that it would be best if I could do the following : class Exception : public std::exception { public: virtual const char* what() const throw() noexcept ...
You can pass the name of the class to Exception constructor and store the name: class Exception : public std::exception { public: virtual const char *what() const noexcept { return m_.c_str(); } protected: Exception(std::string const& name) : m_{"A game related error has occurred: " + name} {} pri...
68,951,342
68,951,592
Does a const getter returning a modifiable reference in C++ make sense?
is the following getter make sense? MyType& MyClass::getMyType() const { return mMyType; } I don't modify this but I give access to someone else to modify it. Is it something to avoid? My IDE generate getter the following way: MyType & MyClass::getMyType() { return mMyType; } MyType const & MyClass::getMyT...
const is transitive. If it were any other way it would be meaningless. The general case for your version isn't legal C++, because in a const method all the data members are treaded as const. To be able to hand out mMyType like that it would have to be qualified as mutable. I don't need the const version You need it i...
68,951,600
68,951,761
Core Dumped due to delting an array
I'm trying to make a copy constructor with low level arrays and I'm getting a core dumped error when using delete, can't find out a solution because I'm not able to use std::vector to make this. Can you guys help me ?? =) #include<iostream> #include<string> #include<initializer_list> class Vector{ size_t n; dou...
Vector::Vector(const Vector&v){ delete[]datos; //CORE DUMPED You didn't initialise datos, so its value is indeterminate. When you delete an indeterminate pointer, then the behaviour of the program is undefined. "CORE DUMPED" is one possible behaviour that you may observe.
68,952,099
68,952,336
why std::function that store a call to member function can have two different callable type
struct Foo { Foo(int num) : num_(num) {} void print_add(int i) const { std::cout << num_+i << '\n'; } int num_; }; int main () { function<void(const Foo*, int)> func = &Foo::print_add; function<void(const Foo&, int)> func2 = &Foo::print_add; Foo f(1), f2(2); func(&f, 2); func2(f2, 3); ...
std::function stores and can "invoke any CopyConstructible Callable target". The Callable named requirement is defined as follows: if f is a pointer to member function of class T: If std::is_base_of<T, std::remove_reference_t<decltype(t1)>>::value is true, then INVOKE(f, t1, t2, ..., tN) is equivalent to ...
68,952,355
68,952,661
`cout<<nullptr` giving error though `nullptr` has type `nullptr_t` from C++17
Code-1 #include <iostream> int main() { std::cout << nullptr; return 0; } Output Error: Use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and 'nullptr_t') Even there is specific type for nullptr why it is showing error. But Code-2 #include <iostream> ...
std::cout << nullptr; works in C++17. If it doesn't work for you, then either you're not using C++17 or your language implementation's support for C++17 is incomplete. Prior to C++17, std::cout << nullptr; didn't work because the overload std::ostream::operator<<(std::nullptr_t) didn't exist and there were no unambiguo...
68,952,377
68,952,627
Msgpack::object to JSON string C++
My code looks like following: msgpack::unpacked msg; msgpack::unpack(msg, args.data(), args.size()); msgpack::object obj = msg.get(); // How to convert "obj" to JSON string format here? And I want to convert that object to a JSON string. How can I perform that? I don't know the type of the elements of the object by ...
The operator<< of msgpack::object outputs MessagePack objects in a human-readable format that happens to match JSON. You can use std::stringstream to store that output in a string. #include <iostream> #include <msgpack.hpp> #include <sstream> unsigned char a[] = {0x82,0xa7,'c','o','m','p','a','c','t',0xc3,0xa6,'s','c'...
68,952,789
68,952,790
Wrapping lambda as std::function produces wrong results (was The dangers of template argument deduction)
Returning a certain lambda wrapped as an std::function produces wrong results: #include <functional> #include <iostream> #include <tuple> template <typename T> std::function<const T&()> constant(const T& c) { return [c]() noexcept -> const T&{ return c; }; } template <typename T> std::function<std::tuple<T>()> zip(...
The reason is the following: the tuple created inside zip is automatically deduced to be a std::tuple<double>, but zip returns a std::function<std::tuple<const double&>()>. The returned tuple contains a reference to a temporary, which is undefined behaviour. The fix is simply explicitly adding the type of the tuple ele...
68,953,023
68,953,108
static cast working and dynamic cast segfaults
The following code compiles and works fine: #include<iostream> class Base { protected: int _a; public: virtual ~Base()=default; Base(int a) : _a{a} {}; int getit() const { return _a; } }; class Derived : public Base { public: Derived(int a) : Base{a} {}; ...
Is it safe to use static_cast to cast down to derived classes Only if the dynamic type of the object is the derived class (or the derived class is a base of the dynamic type that is even further derived). Casting upwards is also safe, but such conversion also works implicitly. If you don't know whether that's the cas...
68,953,155
68,954,258
Lifetime of promise and set_value_at_thread_exit
Suppose we have the following code: std::promise<int> promise; auto future = promise.get_future(); const auto task = [](auto promise) { try { promise.set_value_at_thread_exit(int_generator_that_can_throw()); } catch (...) { promise.set_exception_at_thread_exit(std::current_exception...
Why does your code generate problems? Let's start with ansewer to 'when _at_thread_exit writes to shared state of std::future and std::promise?'. It happens after destruction of all thread local variables. Your lambda is called within the thread and after its scope is left, the promise is already destroyed. But what ha...
68,953,829
68,954,472
Writing to a memory mapped file shows read accesses in htop
I would like to use a memory mapped file to write data. I am using the following test code on a ubuntu machine. The code is compiled with g++ -std=c++14 -O3 . #include <sys/mman.h> #include <unistd.h> #include <fcntl.h> #include <cstdlib> #include <cstdio> #include <cassert> int main(){ constexpr size_t GB1 = 1 <<...
The read access occurs because as the pages are accessed for the first time they need to be read in from disk. The OS is not clarvoyant and doesn't know that the reads will be thrown out. To avoid the issue, don't use mmap(). Build the blocks in buffer and write them out the old fashioned way.
68,953,898
68,955,212
Pushing to a vector and iterating on it from different threads
Is such a piece of code safe? vector<int> v; void thread_1() { v.push_back(100); } void thread_2() { for (int i : v) { // some actions } } Does for (int i : v) compile into something like: for ( ; __begin != __end; ++__begin) { int i = *__begin; } Is it possible that push_back in first t...
Simply put, On some architectures, Fundamental types are inherently atomic, while on others they are not. On those architectures, writing and reading from and to vector<int> v is thread safe as long as no reallocation occurs and ints are properly aligned; but it depends on various factors. BUT: you may want to avoid w...
68,954,044
68,954,197
Why can't I create a std::string_view from std::string iterators?
It is possible to create a std::string_view from a std::string easily. But if I want to create a string view of a range of std::string using the iterators of the std::string does not work. Here is the code that I tried: https://gcc.godbolt.org/z/xrodd8PMq #include <iostream> #include <string> #include <string_view> #in...
That constructor is added in C++20. If you are compiling with a C++17 compiler then it isn't present. You can write a function that does the same thing std::string_view range_to_view(std::string::iterator first, std::string::iterator last) { return first != last ? { first.operator->(), last - first } : { nullptr, 0...
68,954,578
68,999,436
Visual Studio 2019 error on build C++ MySQL connector
I downloaded libraries and headers from Connector/C++ 8.0.26 and tried all of them one by one, But always get error on building point. I used Visual Studio 2019 (Version 16.10.0) and created a simple console app based on example from MySQL website. The original example is like this: #include "mysql_connection.h" #incl...
After checking all solution around the internet finally the problem solved by copying all .dll files to the c:/windows !
68,954,837
68,973,972
std::cout printing nan or zeros for float or double variables in armv7l
I'm writing a C++ program for a Raspberry PI 3B+ doing cross compilation using conan.io Docker container conanio/gcc7-armv7 for cross compilation. Everything was working fine until I started printing double values, and getting "nan" or wrong values in the output. I simplified my code to this minimal example that shows ...
This solved by changing the Docker image I'm using for cross compilation from conanio/gcc7-armv7 to conanio/gcc10-armv7hf. Besides the gcc version (7.2.0 vs 10.3.0), the main difference between them is in ~/.conan/profiles/default, the former uses arch=armv7 while the latter uses arch=armv7hf, which according to dpkg ...
68,955,567
68,956,607
There is any way to do a partial specialization?
Just for fun I'm trying to implement a compile-time pow2 function with templates. Actually, I'm able to do it, this way: template <std::size_t n, typename type_t> struct custom { static type_t pow(type_t b) { return b * custom<n - 1, type_t>::pow(b); } }; template <typename type_t> struct custom<0, type_t> { /...
You cannot partially specialize function/method. You can use if constexpr (C++17) to avoid repetition though: static type_t pow([[maybe_unused]]type_t b) { if constexpr (n == 0) { return static_cast<type_t>(1); } } else { return b * custom<n - 1, type_t>::pow(b); } } No extra runtime branch...
68,956,136
68,956,410
Problem with the 0th harmonic of the Power Spectrum of an array
this is my first question! The problem I'm trying to solve is: I'm creating a fingerprint pattern recognition program using OpenCV in C++. Following the paper I'm studying, I'm stuck on this part where it's said: Compute the X-Signature array of values -> xSig[0, ..., w-1] (I've already done this part) Compute the Po...
abs is the wrong operation. You need split followed by magnitude to get the norm of the packed complex numbers you got from dft. Also your input vector may be far too short if you don't get any higher order harmonics.
68,956,318
68,956,679
`fin.get(ch);` reads last character twice while `ch=fin.get();` not inside `while(!fin.eof())` loop why?
vicky.txt file I was born in Hupari. Code -1 #include <iostream> #include<fstream> int main() { char ch; std::ifstream fin; fin.open("vicky.txt", std::ios::in); while (!fin.eof()) { fin.get(ch); std::cout<<ch; } fin.close(); return 0; } Output I was born in Hupari.. C...
Both versions are wrong. See Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong? for more details on how to correctly code reading loops. Now, to the explanation what happens. The first version uses second overload of get(). This method leaves its argument unchanged if read fail...
68,956,437
68,957,716
want to replace a word by other word in file using c++
I want to replace a string aka word "maaza" with word "fanta" . I actually tried but the replacement goes wrong and replace other string with it so here is my code and i am attaching a ss of file #include<iostream> #include<fstream> using namespace std; int main(){ fstream file; string filename="stockk.txt"; ...
As I can see, in your code you tried to remember the position of file, but you did it after receiving string from stream. In your file it looks like "maaza\nCost", thats why it writes right after it. So i suggest it must look smth like this: fstream file("stockk.txt"); int pos; string s1, s2 = "fanta"; // While file ...
68,956,451
68,956,742
QChart initialization causes an EXCEPTION VIOLATION
When I initialize a QChart, it causes an Unhandled exception EXCEPTION_ACCESS_VIOLATION. I have seen this same exception violation error on Qt Forums when others try to initialize a QChart, however their suggestions do not resolve the issue for me. Their suggestions are to make sure that within Visual Studio's project ...
Your problem is you created the QChart before you created your QApplication instance. The documentation for QApplication states: Since the QApplication object does so much initialization, it must be created before any other objects related to the user interface are created. https://doc.qt.io/qt-5/qapplication.html#deta...
68,956,801
68,957,092
c++: dummy argument for output parameter to create optional parameter
Is there a compact way of skipping an out-parameter from a function call by passing some dummy? In the example below I would like to write something like calc_multiples(myNum, NULL, myNumTimes3), because I do not need the second parameter and hence do not want to define a variable for that. In python one would use _ fo...
There's no direct alternative to Python's _. The function should be rewritten to take pointers instead of references, and it should check that the pointers are not null before writing to them. Then you would pass nullptr to the parameters you want to skip. Comment by the author of the question (Markus Dutschke) Code wo...
68,956,856
68,957,056
How to use std::sqrt as std::function?
Here's the code: #include <iostream> #include <cmath> #include <functional> #include <complex> int main() { // This works. std::function<float(float)> f = [](auto const& x) {return std::sqrt(x);}; // This also works. Why this works?! using Complex = std::complex<double>; std::function<Compl...
Considering the std::sqrt reference, You're looking the wrong std::sqrt page: it's the page of the non-template version. If you use std::sqrt<double> and std::sqrt<float> functions, you're using the template version of std::sqtr, that is referenced in this page. As you can see, std::sqrt<T> template< class T > comple...
68,957,010
68,957,134
How can I display an integer variable as thier intended ASCII letters in `cout` when parsing a binary file?
When I use hexdump -C on the command line to examine this MIDI file, we can see that some bytes of this binary file are ASCII letters that are meant to be human readable text. 00000000 4d 54 68 64 00 00 00 06 00 01 00 08 00 78 4d 54 |MThd.........xMT| 000024f0 2f 00 4d 54 72 6b 00 00 00 19 00 ff 21 01 00 00 |/.MT...
There is no formatting spec like std::ascii but there is a string constructor you can use: std::string int2str((char*)&n32Bits, 4); std::cout << "n32Bits: " << int2str << std::endl; This constructor takes a char buffer and length.
68,957,312
68,957,564
How to store the original indices of array after sorting the array in ascending ordering
Assume that I have a array_dist, and I sorted this array in ascending order successfully. But I need also to store the indices of the original array in new array called index_arr. Example: array [5,4,3,2,1] has indices [0,1,2,3,4]. what I need after sorting the array [1,2,3,4,5]. is these indices [4,3,2,1,0] I try the ...
The issue is that you are sorting the original array_dist when you shouldn't be sorting this at all. You should only sort the index_array based on the comparison of the array_dist values : // Compare values at `array_dist`, using the index array if (array_dist[index_array[i]] > array_dist[index_array[j]]) { // the ...
68,957,411
68,959,127
Winsock connect is slow
I have a program that uses Boost.Asio to connect to a server on localhost. Here is the relevant part of the code: TcpClient::TcpClient(uint16_t port_number) : socket_(service_) { boost::asio::ip::tcp::resolver resolver(service_); boost::asio::ip::tcp::resolver::query resolver_query("localhost", std::to_string(p...
If you have IPv6 enabled then resolver_query("localhost", std::to_string(port_number)); will return an IPv4 and IPv6 address (from experience with the IPv6 listed first). If your server isn't listening on IPv6 then boost::asio::connect will try IPv6 first, wait for it to fail and only then try IPv4. Either get your ser...
68,959,850
68,959,985
Is it possible to replace C++ standard library with C standard library when linking C++ programs?
I have two related questions, one more theoretical for curiosity and another one asking for a possible use case. (1) Would it be possible to compile a C++ program (using e.g., g++) but link the program with the C standard library (e.g., libc) instead of the C++ standard library (e.g., libstdc++) ? I know the C++ standa...
Is it possible to replace C++ standard library with C standard library when linking C++ programs? No, it is not possible. Typically, C++ standard library is implemented on top of C interface. You have to link with both. Would it be possible to compile the program as a C++ program (using e.g., g++) but link the progr...
68,960,109
68,963,352
ffmpeg decode video to YUV and damaged pixels
I use this example to decode a mpeg1 video when decode starts log (every 3 to 10 frames) : [mpeg1video @ 0x5626caf74e40] ac-tex damaged at 39 15 [mpeg1video @ 0x5626caf74e40] Warning MVs not available [mpeg1video @ 0x5626caf74e40] concealing 405 DC, 405 AC, 405 MV errors in P frame and the result is : I tried make rg...
problem solved by using mpeg2 video and AV_CODEC_ID_MPEG2VIDEO codec = avcodec_find_decoder(AV_CODEC_ID_MPEG2VIDEO);
68,960,263
68,960,900
wchar parameters using boost or the Standard Library
How can I make this code use the boost C++ string library or the Standard Library, to avoid wchar_t size definition, and to have a more dynamic string which can be processed much easier? This code uses MFC's CString, but I would prefer to use the Standard Library or boost instead. TCHAR drive[_MAX_DRIVE]; TCHAR ...
You should have a look at the C++ standard <filesystem> library, specifically its path class, which has a replace_filename() method, eg: #include <filesystem> #include <windows.h> WCHAR szFileName[MAX_PATH] = {}; GetModuleFileNameW(NULL, szFileName, MAX_PATH); std:wstring str = std::filesystem::path(szFileName).replac...