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
69,926,275
69,926,780
clFFT: Calculating overlapped FFTs
I want to create a batch for clFFT to calculate 3 FFTs of 256 length, where the FFT input values overlap (FFT overlap processing) Input: a 1D array of 276 complex numbers Task: Calculate FFTs for [0..255], [10..265], [20..275] Output: 3x 256 FFTs = 768 values. If I where to write a loop, it would look like this: std:...
Yes, clfftSetPlanDistance is the right API to use. In the example I would have to use cllSetPlanDistance(plan, 10, 256); to calculate FFTs with a step of 10. This will generate OpenCL code where the global offset of the first FFT index is calculated like this: // Inside the generated fft_fwd OpenCL function iO...
69,926,393
69,926,562
How to align the console output to decimal point instead of left or right
I am trying to align the console output in C++ to a decimal point. I have tried the setw, precision options and other flags that aligns to right or left. But none of those has worked satisfactorily. The closest option is to use showpos to print (+) sign for positive numbers, but it disturbs the other formatting such as...
You can do this with a combination of setw, setfill, fixed and setprecesion as follows: #include <iostream> #include <vector> #include <iomanip> int main() { std::vector<std::vector<double>> vec{{10.0233, 122.1, 1203.1},{100.03, 22.15, 3.01},{107.03, 152.1, 0.1},}; for(std::vector<double> tempVec: vec) { ...
69,926,782
69,936,938
how do I initialize rapidjson buffer at each while loop?
I'm currently sending rapidjson::Value of array type called databuf to a websocket from boost library. Here is how I load databuf at each loop. rapidjson::Value databuf(kArrayType); databuf.SetArray(); for (size_t j = 0; j < sizeof(pu8resbuf); j++) { if(databuf.IsNull() == true)...
I've reset the writer and clear the bufferJson as well like below but didn't work. bufferJson.Clear(); bufferJson.Flush(); rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(bufferJson); writer.Reset(bufferJson); jsonDocumentDataSending.Accept(writer); What worked...
69,926,911
69,930,187
Which operators implictly define / generate other operators in C++?
I know that defining certain operators in C++ lets the compiler generate other operators for a class. From what I read in this cppreference article it seems like the following holds true: operator== must be explicitly defined (perhaps as default) to be usable. operator!= is generated from operator== if it is not defin...
Which operators implicitly define / generate other operators in C++? There is only one situation in which one operator defines/generates another, and that is when you default operator<=> you also get a defaulted operator==. That's the complete list. Everything else is not based on declaring operators, it is based on ...
69,927,137
69,927,258
infinite for loops in c++
I am playing around a little with for loops , tried the following code and got an infinite loop. #include<iostream> int main(){ int i {0}; bool condition = i < 5; for ( ; condition ; ){ std::cout << "Hello World!" << std::endl; i++; } } Can someone explain w...
bool condition = i < 5; This line defines a variable named condition which has the value true from this line onwards. It does not bind the expression from the right side, but only copies the result at the time of assignment. What you intended is more complicated: auto condition = [&i](){ return i < 5; }; for ( ; condi...
69,928,394
69,928,455
Are references / pointers guaranteed to be valid after moving std::deque?
Is it safe to assume that any pointers I have to elements inside of an std::deque are still valid after moving the deque to another one with the move constructor? For std::vector I cannot see any reason why they wouldn't be, but I'm not familiar enough with std::deque to be sure I can make the same assumption.
Pointers to elements would remain valid. After move construction: After container move construction (overload (8)), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement i...
69,928,760
69,928,870
unable to get the following part in CRC implementation in c++
So i was referring Geeks For Geeks for the implementation of CRC in Data Communication Here is the code:- #include <bits/stdc++.h> using namespace std; string xor1(string a, string b) { string result = ""; int n = b.length(); for (int i = 1; i < n; i++) { if (a[i] == b[i]) result += "0"; else ...
std::string(pick, '0') is the string constructor creating a string of length pick filled with '0'. In other ways it's the short form of the following code :- string zeroes_to_be_added; zeroes_to_be_added.resize(pick); for (int i = 0; i < pick; i++) zeroes_to_be_added[pick] = '0';
69,928,789
69,943,207
How to pass value to or call a function of AMyPlayerController (APlayerController) from UMenuWidget (UUserWidget) in Unreal, using C++?
My UMenuWidget (derived from UUserWidget) needs to pass a value to AMyPlayerController (derived from APlayerController). I have tried: DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FPassParam,int,intData); But inGameHUD->MenuWidget from AMyPlayerController::BeginPlay() returns NULL, likely because MenuWidget is yet to b...
Link to answer, at UE4 Answer Hub: https://answers.unrealengine.com/questions/1056641/how-to-pass-value-to-or-call-a-function-of-amyplay.html
69,929,010
69,929,358
typeid result in different compilers
I am watching the following video It is mentioned here that g++ will report an error for the following code: #include<vector> #include<typeinfo> #include<iostream> struct S { std::vector<std::string> b ; }; int main() { S s; std::cout << typeid(S::b).name(); } error: invalid use of non-static data member ‘...
Gcc is wrong (Bug 68604). S::b is an id-expression referring to a non-static data member, which could be used only in unevaluated context. Gcc seems failing in taking this as unevaluated expression. As the workaround you could: std::cout << typeid(decltype(S::b)).name(); Note that in typeid(&S::b).name();, &S::b gives...
69,929,238
69,929,353
While loop not breaking?? C++
I'm trying to construct a simple dice game in C++. I do not understand why it's not breaking out of the while loop. You are supposed to ONLY be able to bet 100, 300, or 500€. Even if I enter my bet "100-300-500" which is supposed to be correct. It still loops and says it's an invalid bet. Why doesn't it progress to th...
This loop while ((bet1 <= 99) || (bet1 >= 101) || (bet1 <= 299) || (bet1 >= 301) || (bet1 <= 499) || (bet1 >= 501)) { cout << "Please place a valid bet" << endl; cin >> bet1; } is an infinite loop for any valid entered value 100, 300 or 500. For example if the user will enter 100 then at least this condition (...
69,929,810
69,929,874
"error: duplicate case value" error when using goto in switch statement
I was trying to use the goto statement to travel between different switch-cases. I understand, it's not preferable to use goto as it would make the program tough to understand, but I really need it. Here's the example version of my code: switch(something){ case "c1": //some code break; case "c2"...
In any case the switch statement does not make a sense because you are using string literals as case labels. switch(something){ case "c1": //some code break; case "c2": //some code break; case "c3": if(condition1) goto case "c1"; if(condition2) ...
69,930,155
69,930,873
Initialize members at later point without using pointers possible? C++
Say I have a class A, that consumes messages of a network. Class A has 2 members b and c of corresponding type B and C. The members can only be initialized with information, that comes from the network. Is there a way to initialize the members at a later point, without having the members to be of type B* and C* (initia...
std::optional<T> is a "nullable" wrapper around a type T. It acts a bit like a pointer in syntax, but there is no dynamic allocation. std::optional<int> bob; if (bob) // is there anything in the box? std::cout << *bob; // print what is in the box. You can do: bob = 7; // Assign 7 to what is in `bob`, or construct w...
69,930,162
69,930,413
I have problem in terms of changing integer into character
This the Instruction I add some photo of the instruction. But my prof wanted to change integer into character. how will I do it? this is my code. I use my full potential in programming but this program makes me down. I use all resources i may find but I didn't get the right code #include <stdlib.h> #include <iostream>...
the first really necessary change is to move int array[10]; to char array[10]; in that way we can store characters instead of store integers. since your program is using std::cout and std::cin (and both of them got different overloads getting a char or an integer) you don't really need to change nothing else except the...
69,930,528
69,931,048
Is it allowed to emit a signal trough a pointer to an instance of another class?
Minimal example: class Foo : public QObject { Q_OBJECT signals: void TestSignal(int i) const; }; class Bar : public QObject { Q_OBJECT public: Bar(Foo* foo) : mFoo{ foo } {} void TestEmit(int i) const { emit mFoo->TestSignal(i); } private: Foo* mFoo...
From https://doc.qt.io/qt-5/signalsandslots.html : Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses I understand it is technically allowed and reliable but not recommended in terms of code design. You mig...
69,930,782
69,930,881
c++ read binary data from istream
I have an istream and I have to read it into a buffer. I could not find a way to figure out the read_len once eof is encountered? I cannot use get because my file does not have delimeters. It seems that the only option is to read it character by character, is it really the only option? char buffer[128]; while(is.good()...
You could check istream::gcount() which "Returns the number of characters extracted by the last unformatted input operation". Example: while(is) { is.read(buffer, sizeof buffer); auto read_len = is.gcount(); // <- if(read_len > 0) process(buffer, read_len); else ...
69,931,435
69,931,941
How do I properly set the precision of std::complex<mpf_class> and read it in?
I wanted to have an std::complex<mpf_class> with a specific precision (400), and read in the complex from std::cin. I didn't know how to set the precision in the declaration of the complex, so I tried this first: std::complex<mpf_class > c; c.real().set_prec(400); c.imag().set_prec(400); std::cin >> c; std::cout << std...
Thanks to pasaba por aqui for explaining why the first code segment doesn't work. I have thought about it a little more and decided this might be an appropriate solution: std::complex<mpf_class> c (mpf_class(0,400), mpf_class(0,400)); std::cin >> c; std::cout << std::setprecision(400) << c; This code segment properly ...
69,931,451
70,185,995
How to play avi video using GStreamer
I am trying to play my first video in GSTreamer, by using GstElement, without pre-configured things like gst_parse_launch etc I dont understand why my pipeline cant be linked and I get an error "unable to set the pipeline to playing state" ? How can I fix it? What is missed? #include <iostream> #include <gst/gst.h> ...
Here is an answer First of all, here is github link to my solution with comments. Explanation: If you want to play video file, without predefined pipelines, like playbin, gst_parse_launch etc, you have two options Dynamically link uridecodebin with 2 pipeline sleeves (one for audio and second for video) Dynamically l...
69,931,678
69,932,122
C++ Iterate over template variable instantiations
Take a look at this: #include <vector> #include <iostream> template<class T> std::vector<T> vec{}; int main() { vec<short>.push_back(5); vec<int>.push_back(10); vec<long int>.push_back(15); } The vec variable is templated, but there is no telling what possible instantiations occurred. In this case it is ...
You might be able to do something if you wrap vec in a function, and have a type-erased "do things to vec<T>" interface. You will need to specify all the things you want to do to the various vec<T>()s up front. template <typename T> concept printable = requires (T t) { std::cout << t; } template <printable T> std::vec...
69,931,685
69,932,099
2 questions about cppreference.com's explanation of decltype
When I was reading this online c++ reference page about decltype I was wondering about this paragraph: If expression is a function call which returns a prvalue of class type or is a comma expression whose right operand is such a function call, a temporary object is not introduced for that prvalue. (until C++17) My qu...
Introducing or not introducing a temporary, does that matter? This makes a bit more sense if you look at an expression that uses the result of a function: // given template<typename T> struct Foo {}; template<typename T> Foo<T> foo(); template<typename T> void bar(const Foo<T>&); // This: bar(foo<int>()); // Is equ...
69,931,864
69,935,936
Concept to keep track of class instantiations in C++
I am trying to write a code that keeps track of instances of my class. Each instance is uniquely identified by a type (int). I would like to have some kind a map which links a type to a instantiation of my class. My idea was to use a static map for this, and every instantiation registers itself when the constructor is ...
Your problem is that the static map is filled inside the constructor, but outside of the constructor, the entry is gone. It seems like there are two different instances of the static map. You see one instance inside the constructor, and another instance outside of the constructor. It looks like, you define your static ...
69,931,954
70,075,669
c++ read map in binary file which created in python
I created a Python script which creates the following map (illustration): map<uint32_t, string> tempMap = {{2,"xx"}, {200, "yy"}}; and saved it as map.out file (a binary file). When I try to read the binary file from C++, it doesn't copy the map, why? map<uint32_t, string> tempMap; ifstream readFile; std::...
It's not possible to read in raw bytes and have it construct a map (or most containers, for that matter)[1]; and so you will have to write some code to perform proper serialization instead. If the data being stored/loaded is simple, as per your example, then you can easily devise a scheme for how this might be serializ...
69,932,096
69,932,257
Attempting to delete an initializer list constructor does not always take effect
Sorry for the generic title, but it's a mindfu*k situation, which I can't easily describe. Suppose the following code: struct S { S() = default; int x; int y; }; S f() { return { 1, 2 }; } This compiles and works perfectly fine. I want to forbid it, as it's bug prone (the actual code is far more comp...
In C++17, S is considered an aggregate, and because of that you are not calling any constructor, you are basically directly initializing the members. If you change to using C++20, S is no longer considered an aggregate as the rules were changes and the code will work as expected. The reason changing the access specifi...
69,932,590
69,932,820
Default reference parameters and lifetimes in coroutines
I'm confused about the lifetime of parameters passed to C++ coroutines. Answering to a previous question, smart people stated that The lifetime of a parameter is [...] part of the caller's scope Now, to follow up, what happens when passing default arguments like generator my_coroutine(string&& s = string()) {...} So...
As pointed out in said "previous question", the first thing that happens in a coroutine is that parameters are "copied" into storage owned by the coroutine. However, the "copy" is ultimately initialized based on the type declared in the signature. That is, if a parameter is a reference, then the "copy" of that paramete...
69,932,704
69,932,891
how to use find_if to find element in given vector of pairs
For example consider vector<pair<string,int>> And it contains: ABC 1 BCD 2 CDE 3 XHZ 4 string s; cin>>s; if(find_if(vec.begin(),vec.begin()+3,cmp)!=vec.begin()+3) // I want to check only first 3 values I need cmp to find given string is present or not using find_if EDIT: How to pass the string s with the comparator ...
The simplest way is to use a lambda expression. For example #include <string> #include <utility> #include <vector> #include <iterator> #include <algorithm> //... std::string s; std::cin >> s; auto cmp = [&s]( const auto &p ) { return p.first == s; }; if ( std::find_if( std::begin( vec ), std::next( std::begin( ve...
69,932,934
69,933,068
Why is GLM Perspective projection acting like Orthographic Projection
I Have a projection matrix in my C++ OpenGL Application. glm::mat4 projection = glm::perspective(45.0f, 16.0f / 9.0f, 1.0f, 100.0f); This Matrix is later sent as uniform to the Vertex Shader -> Nade::Shader::SetMat4(app.shader->GetProgram(), "p", app.projection); And Utilized inside the Vertex Shader gl_Position = m ...
gl_Position = m * p * vec4(pos,1.0); is equivalent to gl_Position = m * (p * vec4(pos,1.0));, which means that the position is transformed by p before being transformed by m. Assuming p means "projection" and m means "modelview", then it should be: gl_Position = p * m * vec4(pos,1.0); You might be wondering: Why didn't...
69,933,305
69,933,423
Convert decimal to binary and let binary length always eight using C++
I need a way to convert a decimal number into a binary number in c++, but the problem is, that the length of the binary number always has to be 8bit. Is there a way to do this? I already did a conversion like this, but the length is not always 8bits: int DecimalToBinary(int decimal) { int binary = 0; int count ...
Note that you're not converting decimal to binary, you're converting to another decimal number of which the output mimics a binary number. (for value five you're really outputting value one-hundered-and-one) But you can use std::bitset to get the output you want : #include <bitset> #include <iostream> int main() { ...
69,933,653
69,938,519
I don't have the proper gstreamer dll loaded for C++ opencv camera capture
I have successfully capture the webcam using Python and opencv but now I am getting back into C++ and trying to do the same simple functionality. Here's my (trimmed down) code: #include <iostream> #include <opencv2\opencv.hpp> #include <opencv2\imgcodecs.hpp> using namespace cv; using std::cout; using std::endl; using ...
You may try adding cam.open(0, CAP_DSHOW); #include <iostream> #include <opencv2\opencv.hpp> #include <opencv2\imgcodecs.hpp> using namespace cv; using std::cout; using std::endl; using std::string; int main() { Mat img; VideoCapture cam; cam.open(0, CAP_DSHOW); if (cam.isOpened()) { cout << "Ca...
69,933,894
69,941,311
Function to invert Eigen matrix without branching statements for auto differentiation
I need to invert an Eigen matrix (9x9 in my particular case) as a part of code that I want to automatically differentiate using CppAD. For this to succeed the code executing the inversion can not contain any branching like for example if or switch statements. Unfortunately, the inverse function of Eigen contains branch...
There is a mechanical conversion from branch to no-branch for arithmetic functions. Duplicate all the variables you use in each branch, and calculate both halves. At the end of the block, multiply the if branch by condition, and the else branch by !condition, then sum them. Similarly for a switch, calculate all the cas...
69,934,052
69,934,227
Implementing Matrix operations in C++
I am trying to write a simple C++ header-only library that implements some basic numerical algorithms. It's a hobbyist project, that I wish to do in my personal time. I created a C++ MatrixX class that represents dynamic-size matrices, that is its dimensions can be supplied at run-time. Say, we create a MatrixX object ...
A common approach for this type of situation is to have the row() method return a proxy object that represents the row without being the row itself. You are then free to implement how this RowProxy behaves by having its operations inspect and maninupulate the matrix it was created from. Here's a rough starting point: t...
69,935,036
69,935,213
include file 'string' not found
Learning C++, day 1, lesson 2 My simple string concatenation test works on the online c++ compiler #include <stdio.h> #include <string> #include <iostream> int main() { // Declare and initialize string std::string mystr = "bananas"; std::cout << "Gwen Stefani is " << mystr << "\n"; return 0; } ...
Tiny CC is a C compiler, it does not support C++. Since <string> is a C++ standard header, it is not supported by Tiny CC.
69,935,181
69,935,404
Segmentation Fault in C++ With for Loop
I am making an Ant simulation with SDL2 and when I run my code it soon crashed giving me a segmentation fault. I believe this is from trying to access negative values in an array. I tried to make it so the Ant can't do this by giving an if statement checking its value on the "grid" I made out of squares. I added an if ...
You should include all the headers you need. You are missing #include <ctime>. You have undefined behavior because of indices running out of bounds, as can be seen when running your program compiled with -g -fsanitize=address,undefined: ant.cpp:350:34: runtime error: index -199 out of bounds for type 'Wall [572397]' a...
69,935,403
69,935,522
Extracting an username from the database
I'm relatively new to the pqxx library and so I can't seem to figure out how to get data out of the database. I have my header file for the DBUser class #pragma once #include <string> class DBUser { private: std::string m_user, m_password; public: void CreateUser(std::string const& user, std::string const& pw);...
Okay, you're not going to want to do it that way. You should use positional arguments and prepared statements. Look at this page: https://libpqxx.readthedocs.io/en/6.4/a01480.html For instance, here's some code of mine: static constexpr char const * INSERT_LIST { "author_id, series_id" }; void DB_AuthorSeries_Base::do...
69,935,772
69,936,298
Weird value and overriding text on variadics
I'm trying to create a logging system where you push a log string into a vector and then print all the logs by looping through the vector, but there seems to be an issue where the strings inside my vector are getting replaced by the most recent string pushed, as well as weird characters being added. struct color { ...
your struct struct info { const char* text; float time; color col; info(const char* ntext, float ntime, color ncol) : text(ntext), time(ntime), col(ncol) { } }; is copying an address to a local variable fmsg. The life time of fmsg is circumscribed in the scope of add_log_messasge (you got a typo). Stor...
69,935,919
69,936,230
C++ - why isn't size/ssize defined for tuple (or wherever tuple_size_v is)?
I'm trying to imagine a scenario where std::size is inappropriate for std::tuple and I'm coming up blank. It supports std::array, but that has its own size() method, so there's no need to specialize. But it also supports T[N], presumably because it's statically sized even if it doesn't have a size() method (it doesn't ...
First, some background to understand what the purpose of std::size even is: Similar to how iterators are generalisations of what pointers are, the standard containers are generalisations of what arrays are (pointers being iterators of arrays). They all contain elements of homogeneous types i.e. all elements have the sa...
69,936,383
69,936,434
How to design a class with const, non const member function and it can take over const raw pointer?
I have a class, it can define some operations on a raw pointer. For example, the class is called Vector. class Vector { public: explicit Vector(double *ptr_, int size_) :ptr(ptr_), size(size_) { } // some operation change data in ptr void notConstOperation() { ptr[0]=ptr[...
Any suggestion is I looking forward Inheritance. class ConstVector { const double *ptr; protected: double *_ptr() { return const_cast<double *>(ptr); } void _set_ptr(double *new_ptr) { ptr = new_ptr; } friend Vector; }; class Vector : ConstVector { // some operation chang...
69,936,613
69,936,657
Cuda number of elements is larger than assigned threads
I am new to CUDA programming. I am curious that what happens if the number of elements is larger than the number of threads? In this simple vector_add example __global__ void add(int n, float *x, float *y) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = x[i] + y[i]; } Say the number...
what would happen to the rest of the array elements? Nothing at all. They wouldn't be touched and would remain unchanged. Of course, your x array elements don't change anyway. So we are referring to y here. The values of y[0..16383] would reflect the result of the vector add. The values of y[16384..9999999] woul...
69,937,130
69,937,958
How can I make sure a type only appear once in a template parameter?
Let's say I have an alias: using bar = foo<string, string, int>; How can I make sure that "string" only appear once in the parameter? If it appears more than once then throw an error. I have made a function to count how many times a type appeared in the parameter but failed to implement the idea. template <class T> c...
For a simple compile time error if any type in the variadic parameter pack is duplicated, it's pretty simple: template <typename T> struct Base{}; template <typename... Ts> struct NoDuplicates : Base<Ts>... { constexpr operator bool() const { return true; } }; That's it, and if it's what you need it will compile ...
69,937,136
69,943,669
Binary Tree with parent pointer in node keeps crashing on Deletion with error 0xDDDDDDDD
I was experimenting a little bit with C++ and decided to try and create whole tree deletion method for Binary Tree. For some reason I keep getting pointer error because pointer is 0xDDDDDDDD. If someone can explain me why it does not work I would appreciate it so I can learn more about pointers. struct Node { Node*...
When I run your code I get this output, and it throws "read access violation": Found left ptr with value: -572662307 -572662307 is same as 0xDDDDDDDD This is specific for Visual Studio in debug mode. Sometimes you may not get this value. The problem is you never allocated memory for parent (which you don't even need, ...
69,937,151
69,947,939
Calling a custom function on each node during DFS traversal
I am wondering what would be the most elegant way to code a DFS traversal that can be adapted to solve different problems (in C++). I was thinking to pass a function pointer and a void * to my function and let the user pass a callback that would be used on every node. This is what I have: traversals.hpp typedef std::sh...
Correct me if I am wrong but I suspect the problem was due to the static variable defined inside DFS. I omitted to mention in my question that DFS was called with a different callback that did not increment the count variable before being called with the callback that did. I though it was not relevant to my question. C...
69,937,425
69,937,650
How to calculate a rorate ellipse point's tangent?
I got a rotate ellipse by using fitEllipse, and i want calculate the tangent of the points on this ellipse, i tried this: static Line getTangent(const RotatedRect & ell, const Point & p) { // double rad = ell.angle*CV_PI/180; // double a = ell.size.width/2; // double b = ell.size.height/2; // if(fabs(ra...
A picture is worth a thousand words: You need to check whether point lies outside of ellipse (with opencv function if exists or with ellipse equation)
69,937,956
69,938,053
Why do 1ll << i does give us correct answer but not long long i ; 1<<i?
Since 1 operand in << operator is of long long type, and the answer should be stored as long long, I am a little surprised by this behavior can anyone explain why this happens? For Example: #include<bits/stdc++.h> using namespace std; int main(){ long long p=33; long long a = 1<<p; cout<<...
C++11 (N3690) 5.8 Shift operators [expr.shift] p1: The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. So the type of 1 << i is int, whereas 1LL << i has type long long, which can usually represent a greater...
69,937,999
69,938,029
Running an object call within an object call
I have a struct struct Stuff { float something (int& prereq) { float s = prereq+2; return s; } double something_else(int& prereq_ref, float& thing_ref, float& s_ref ){ s2 = s + thing + h; return s2; } }; Then I run a call in my main loop float thing = 4; int prereq = 2; int main() { Stuff item; double n ...
float& is an lvalue reference type. It can only take values that can be assigned to, such as variables. float s = item.something(prereq); double n = item.something_else(prereq, thing, s); Here, s is a variable. It has a place in memory and the expression s = ... would be meaningful. On the other hand, double n = item...
69,938,045
69,938,725
How to convert this JavaScript code to C++
Problem is to return any one combination from given array that sums up to the target. I'm new to C++. How can I complete the function howSum() below? I can't return null here since the return type is vector. Also I'm having trouble passing the vectors. JavaScript: const howSum = (targetSum, numbers) => { if (target...
You can use C++17 std::optional and return std::nullopt when it does not contain value. #include <optional> #include <vector> std::optional<std::vector<int>> howSum(int targetSum, const std::vector<int>& numbers) { if (targetSum == 0) return std::vector<int>{}; if (targetSum < 0) return std::nullopt; ...
69,939,017
69,939,092
What is the best way to get user appdata folder location on windows?
I'm writing an application for windows, and I need to find the location of the appdata folder, to save, well, appdata to it. I'm using C++. When I did some research on this, I found some answers like, for example "getenv("APPDATA")". I could use that but that question was answered in like 2012 so there might be better ...
you can use Windows API alternatively: TCHAR appdata[MAX_PATH] = {0}; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, appdata); https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderpatha
69,939,946
69,945,233
How to determine if an argment was provided to boost::program_options, or if the default is used instead?
Using boost::program_options, I need to set the default_value for having that default visible in the help message. However, it is still needed to know if the default was applied or if an argument was provided. (The logic will, in certain cases override an existing configuration if the argument pas provided). Possible s...
Your options descriptions are broken. Let's fix them. I opted against the ip_arg/port_arg variables (note how you had them copy pasted wrong anyways). po::options_description options("Options"); options.add_options() ("ip", po::value<std::string>(&ip)->default_value("127.0.0.1"), "IP") // ("port", po::value<std...
69,940,027
69,940,735
Why is converting constructor of std::packaged_task explicit?
Why is the converting constructor of std::packaged_task explicit, while the same constructor of std::function is not? I cannot find any reasoning for it. This, for example, forces casting when passing a lambda as an argument for a function that has a packaged_task (or a reference to it) as a parameter: void f1(std::fun...
Consider following example. Lets create a template class that emulates class with non-explicit templated converting constructor. #include <iostream> // Hypothetical overloaded constructor template <class T> struct Foo { template <class F> Foo(F&& f ) { std::cout << "Initialization of Foo \n"; } Foo(const F...
69,940,116
69,940,196
error: std::string was not declared in this scope, in for loop C++
I was trying to implement code making use of the GMP library for a class, and haven't been able to figure out the source of this issue. I've run similar code before on an unordered_map so this error is confusing me. From what I can tell the std::string should be declared in the scope by the call to the for loop. Could ...
for (std::string name : names_file >> name >> num){ number_names[num] = name; } This is not how range-based for loop works in C++, so this is a syntax error. By the looks of it, you have a typo. Maybe what you want is: std::string name; while(names_file >> name >> num){ number_names[num] = name; } Or: for (std:...
69,940,204
69,940,262
Overriding non-virtual function from abstract grandparent class
I am learning and playing around with inheritance and abstract classes. I've run into a predicament that I would appreciate some clarifications on. I am trying to override a non-virtual function from an abstract grandparent class. I am getting an error saying that 'member function declared with 'override' does not over...
You cannot override a non-virtual function. It is as simple as that. Methods in child classes can hide methods of parent classes when they have the same name, for example: struct A { void foo(){} }; struct B : A { void foo() {} }; But thats not overriding. To override the method must be virtual. Thats one of t...
69,940,329
69,940,397
STL algorithm function with reverse iterators doesn't work
I need to find minimum element in my array, but if amount of minimum elements more than 1, I need to use the most right one. Consider this code: #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int& x : a) cin ...
You're passing reverse_iterator to min_element, then it returns reverse_iterator too. Change the code to vector<int>::reverse_iterator it_min = min_element(a.rbegin(), a.rend()); Or auto it_min = min_element(a.rbegin(), a.rend()); You can get the vector<int>::iterator from the returned reverse_iterator later by it_mi...
69,940,527
69,945,180
Random Occupancy values returned by the "cudaOccupancyMaxActiveBlocksPerMultiprocessor"
I am trying to understand the usage and benefit of the “cudaOccupancyMaxActiveBlocksPerMultiprocessor” method. I am using a slightly modified version of the sample program present on NVIDIA developer forum. Basically, I am asking the user to provide the size of the array. My GPU: NVIDIA GeForce GTX 1070 QUESTIONS: Th...
Before asking others for help with a CUDA code that is not working the way you expect, I strongly encourage you to: Use proper CUDA error checking run your code with a sanitizer, such as cuda-memcheck or compute-sanitizer Even if you don't understand the results, the information reported will be useful for those tryi...
69,940,833
69,941,266
Implicit type conversion for operator==
I'd like to have a way to compare different data types that are internally represented by an array (e.g. a string and a vector of chars) using a common array reference type. Consider the following code: template <typename T> struct ArrayConstRef { const T *data; size_t length; }; template <typename T> bool ope...
This can be solved using SFINAE and little changes in code of your classes. #include <cstddef> #include <cstdio> #include <type_traits> template <typename T> struct ArrayConstRef { const T *data; size_t length; }; // This is needed to override other template below // using argument depended lookup template <t...
69,941,533
69,941,748
C++ Recursive Function
I am student who just learned c++ not long ago. I have a doubt in mind, for the linked list code below, I don't quite understand the logics behind it, why does the function when it reaches return, it will continue to execute the func1() and cout command ? Isn't it whenever a the programs reaches return it will automati...
Let's see what is happening behind the scenes. Example; Linked List: head -> A -> B -> C -> NULL; void func1(Node* head) { if (head == NULL) { return; } cout << " " << head->value; func1(head->next); } Iteration 1: Head is Not NULL, So it its prints A, now it called func1(head->next) recurs...
69,941,557
69,941,962
C++ template function to check if a vector of contains the value?
I had planned to implement a kind of INDEX function for all types similar as in FORTRAN. Would this be a correct solution? A little EDIT after comments. template <typename T> bool contains(std::vector<T>& vec, T value){ if (std::any_of(vec.begin(), vec.end(), [value](T j) { return value == j; }))return true; return f...
Yes, that is a valid implementation, however I'd write it differently template <std::ranges::input_range R, typename T> requires std::indirect_binary_predicate<ranges::equal_to, ranges::iterator_t<R>, const T*> bool index(R&& range, const T & value){ return std::ranges::find(range, value) != std::ranges::end(range)...
69,941,946
69,942,149
no viable conversion from 'lambda' to 'void ...'
I need to give a function another function or lambda as a parameter, and this works, more or less. There is an error as soon as I try to define a capture for a lambda in c++14. You can see the sample code here: // this is part of a library (I cannot change it) class SVGElement { //... public: v...
Functions can't have captures. Lambdas can, which means they aren't functions. A lambda with no captures can be converted to a function pointer but a lambda with captures cannot. This code: int angle = 15; mySvgElement.onclick([angle](SVGElement* clicked){clicked->rotateBy(angle);}); is effectively equivalent to: int ...
69,941,950
69,942,482
OpenGL Application crashes when accessing Assimp Texture Coordinate Data
I am trying to access the Texture Coordinate of a Cube model made in blender. for (int i = 0; i < mMesh->mNumVertices; i++) { std::cout << mMesh->mTextureCoords[i][0].x << " " << mMesh->mTextureCoords[i][0].y << std::endl; } Why is this happening. The application window launches but the red color background doesn...
This should be: for (int i = 0; i < mMesh->mNumVertices; i++) { std::cout << mMesh->mTextureCoords[0][i].x << " " << mMesh->mTextureCoords[0][i].y << std::endl; } Looks like you messed up the first and second array arguments. Also, it is good practice to check if the mesh has texture coordinates or not. Then the c...
69,942,040
69,942,104
Extract first template parameter type from any object
Suppose I had a templated object in C++ Test<T> and I wanted to find out what the T value is so that when I pass Test<T> as a template argument to TestWrapper<Test<T>>, I can declare a variable called T extradata in the object TestWrapper that is the same as Test's T type. How can I achieve this by only modifying TestW...
You can use partial template specialization to do that. template<typename T> struct Test { T value; }; template <typename T> struct TestWrapper; template <template <typename> typename Outer, typename T> struct TestWrapper<Outer<T>> { T extradata; }; int main() { TestWrapper<Test<int>> temp; temp....
69,942,076
69,942,201
What template parameter do I use? (C++ conceptual question)
I am going through the book C++ Crash Course by Josh Lospinoso and have been compiling the code in the lessons along the way. I'm having trouble with the following code (which is a simplified version of one of the examples in the book). struct SmallStruct {}; template <typename T> struct BigStruct { BigStruct(cons...
In the "old" days the way was to use a make_... helper function to get the template parameter deduced from a function parameter: struct SmallStruct {}; template <typename T> struct BigStruct { BigStruct(const T& arg) : arg{arg} {}; private: const T& arg; }; template <typename T> BigStruct<T> make_big_struct(c...
69,942,288
69,942,536
How to use a const pair from one cpp file in another
I have 2 structs: S and R. R has an instance of type S. In S there is defined a const pair that I want to use also in R but I get the following errors. S.hpp:11:12: error: redefinition of ‘const conf n1::n2::def1’ 11 | const conf def1 = std::make_pair(10, 2); | ^~~~ These are the structs and main function #i...
I have made 3 changes in your program and it compiles: Change 1 Added header guards. This is my habit(and advice) to add the header guards whenever i don't see in headers. So now your headers look like: S.hpp #ifndef S_H #define S_H #include <string> #include <iostream> #include <utility> #include <memo...
69,942,685
69,942,977
How to get any additional info about the occurred error in Bison?
I'm just starting with Flex/Bison and I'm trying to translate pascal-look-alike variables declarations like this: VAR V1: INT; V2: INT; END_VAR into C variables declarations like this: int main () { int V1; int V2; } I wrote lex- and yacc-files describing needed grammar, then compiled it with flex, bi...
For more informative error strings you need %error-verbose in yacc file. Perhaps like that in your file: %{ #include <stdio.h> extern FILE * yyout; extern char * yylex (); void yyerror (char *s); %} %error-verbose %union { int number; char var [10]; } ... More information on error analysis a...
69,943,142
69,945,058
Cyclic Reference issue with includes for friend class
I have 2 classes: S and R. R has an intance of type S. I want to have R as friend class to have acces to S private methods. Unfortunately I couldn't build it. Please help me how can I solve this. I tried forward declaration in more ways but it didn't work. I get the following error R.hpp:12:15: error: ‘n1::n2’ has not...
You can get the program to work(compile) by using the following modifications in your files: S.hpp #ifndef S_H #define S_H #include <memory> namespace n1 { namespace c1 { class R; } } namespace n1 { namespace n2 { class S { friend class c1::R; int x; void print...
69,943,562
69,943,913
Passing const char* in variadic template argument list results in linker errors
I have following template class constructor for an exception class: MyCustomException.h: template<typename ... Args> MyCustomException(const Message& msg, const char* fileName, int line, Args&& ... args); MyCustomException.cpp: template<typename ... Args> MyCustomException(const Message& msg, const char* fileName, int...
The problem was with defining the template constructor inside a separate .cpp file. As G.M. linked to this post in the comments, template members should be implemented in the header file or, when defined in the .cpp file, at least be defined explicitly for each instance.
69,943,708
69,943,896
return 2D array in C++
I am kind of new to C++ and I was doing a physics simulation in python which was taking forever to finish so I decided to switch to C++, and I don t understand how to make a function which will return a 2D array (or 3D array) #include <iostream> #include <cmath> // #include <complex> // using namespace std; double** ...
If you're new to c++ you should read about the concepts of heap and stack, and about stack frames. There are a ton of good resources for that. In short, when you declare a C-style array (such as yj), it is created in the stack frame of the function, and therefore there are no guarantees about it once you exit the frame...
69,943,854
69,944,428
Factory for threads in C++
I am currently trying to create a sort of "factory" pattern in a class, whose instances should be Threads that have their own certain operation procedure. I have currently declared a global variable isFinished in order to end the operation of the worker thread, however, somehow the operation does not stop after the var...
The problem is that you are using a static variable in the global scope. static in a namespace scope is used to hide the variable or function in the object file so that the linker can't see it while linking another object file for another cpp file. In practice static is used only inside the cpp file itself. Since you d...
69,945,027
69,945,313
Running the same code, old computers are as fast as new ones, is that true?
I've been learning about parallel programming in c++ and I came across materials from a university. In the lecture they stated : "With old code, a computer from 2021 is not any faster than a computer from 2000. In this course, we will learn how to write new code that is designed with modern computers in mind." LINK Wai...
Is that true? and in what conditions ? It is true that the clock speed of processors hasn't increased since ~2005 (and went down in the mean time). That isn't to say that single core wall-clock performance hasn't improved. It hasn't been the case for long before then that each instruction took a single clock to proce...
69,945,245
69,947,968
Understanding Makefile rule
I have been debugging a linking error for specific target (android), for all other targets, build is successful. Error is something like Test.cpp:29:57: fatal error: linux/ethtool.h: No such file or directory compilation terminated. make: *** [../../../makefiles/rules.makefile:1012: android-arm-r/Test.o] Error 1 and b...
What is @$ for? @$ is not a unit. The @ is a prefix that suppresses the command's output from being forwarded to make's output. The $ is the beginning of a variable reference ($(cpp_PRECOMPILE)) which expands to a command to run. $< is automatic variable holding prerequisite name. But overall what action this r...
69,945,844
69,946,626
Why passing `printf` as template function argument succeeds but `cos` failed (msvc 19)?
I am playing with online c++ compilers a little bit on link. But the code snippet below got failed when compiled with msvc v19.latest. #include <iostream> #include <cmath> #include <cstdio> template<class F, class...L> void test(F f, L...args) { std::cout<< "res = " << f(args...) << '\n'; } int main() { tes...
It is failing because cos is an overloaded function in msvc. This means that there are at least 3 different versions of cos: float cos(float arg); double cos(double arg); long double cos(long double arg); The compiler has no way of guessing which one you are trying to use, but you can give it a hand by using static_c...
69,946,062
69,947,643
How to duplicate the vowels between two consonants in a string?
I want to duplicate the vowels between two consonants in a string. Input : informatics Output : infoormaatiics I have made an attempt below: #include<bits/stdc++.h> #define ios ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; void solution(){ string i; cin >> i; int n = i.size(); ...
Here's what I'd write using a regular expression: #include <iostream> #include <regex> std::string solution(std::string i){ std::regex re( "([bcdfghjklmnpqrstvxz])" "([aeiouy])" "([bcdfghjklmnpqrstvxz])"); return std::regex_replace(i, re, "$1$2$2$3"); } int main(){ for (std::string ...
69,946,460
69,946,565
Making a simple guessing game between 0 and 100, but game ends after 2 guesses
the code is in swedish btw. int nyttal(int n){ int nyttal = rand() % 100 + 1; return rand() % nyttal; } //Lak Lägg void utforEnSpelomgang(){ const int n =100; const int datornstal = nyttal(n); int antalUtfardaGissningar = 0; //number of guesses made by user cout << "Datorn tänker på ett ...
You can use/add a while loop as shown void utforEnSpelomgang(){ const int n =100; const int datornstal = nyttal(n); int antalUtfardaGissningar = 0; cout << "Datorn tänker på ett tal mellan noll och " << n << ". Gissa vilket!" << endl; int g; cin >> g; while(g!= datornstal)//added this ...
69,946,646
69,946,827
Adding library dependencies to interface libraries in cmake
I have the following cmake file cmake_minimum_required(VERSION 3.16) find_package(fmt) add_library(mylib INTERFACE ) add_dependencies(mylib fmt::fmt-header-only) target_compile_features(mylib INTERFACE cxx_std_20) target_include_directories(mylib INTERFACE .) add_executable(test_exe test_exe.cpp) target_link_librar...
add_dependencies(mylib fmt::fmt-header-only) simply makes sure that the target fmt::fmt-header-only is up to date before mylib is built. It doesn't link fmt::fmt-header-only regardless of the target type of mylib. Linking is done via target_link_libraries target_link_libraries(mylib INTERFACE fmt::fmt-header-only)
69,946,860
70,732,246
How to memory-map a PCI BAR using PCIDriverKit?
How to memory-map a PCI Base Address Register (BAR) from a PCIDriverKit driver (DEXT) to a userspace application? Memory-mapping from a driver extension to an application can be accomplished by implementing the IOUserClient::CopyClientMemoryForType in the user client subclass (on the driver side) and then calling IOCon...
Turns out IOPCIDevice::_CopyDeviceMemoryWithIndex was indeed the function needed to implement this (but the fact that it's private is still an inconvenient). Sample code Bellow is some sample code showing how this could be implemented (the code uses MyDriver for the driver class name and MyDriverUserClient for the user...
69,946,945
69,947,428
Malloc space for a pointer of array in C++
I need to work upon a variable number of fixed-size arrays. More specifically, N points in a K-dimensional space, where I know K beforehand, but I don't know N at compile time. So I want to use a pointer to the fixed-size array, and allocate space for N K-dimensional points at runtime. In C, I can allocate the said poi...
You need to cast the result of malloc as PointKDimensions* not as a float*: typedef float PointKDimensions[DIMENSIONS]; void do_stuff( int num_points){ PointKDimensions *points; points = (PointKDimensions*)malloc(num_points * sizeof(PointKDimensions)); points[5][0] = 0; // set value to 6th point, first dimens...
69,946,976
69,947,120
sqrt() c++ and math.sqrt() python
i am new at python and i had this precision problem with python which i did not have before with c++, the code is for python import math def f(x): return math.sqrt(x) print((38 / (math.sqrt(38) * math.sqrt(38)))) print(38 / (f(38) * f(38))) print(math.acos(38 / (math.sqrt(38) * math.sqrt(38)))) print(math.acos...
Different programming languages may behave differently when it comes to float arithmetics. It may come to optimisations, internal implementations of functions like acos etc. First, notice that in C++, acos returns the special value nan for values out of range, while in Python it throws the ValueError exception. You can...
69,947,404
69,947,506
C++ function inside function
/*I need to use the result from the (delta) function inside the (sol_ec_II) function for a school assignment.*/ #include <iostream> #include <ctgmath> using namespace std; double delta(double a, double b, double c) { return (b * b) - (4 * a * c);/* so I need to take this value [(b * b) - (4 * a * c)] ...
The result "comes out" of the function call at the time you call it. Look, you already know how sqrt works. sqrt is a function! You write sqrt(something) and that calls the function sqrt and it calls the function sqrt with the argument something and then the return value from sqrt gets used in the place where you wrote...
69,947,545
69,947,822
Seperating C++ Nested Classes into their Own Header Files
new to this site and also C++ but hoping to see some guidance from everyone. I had a pretty fun project idea to learn C++ digging deeper with APIs, classes, references, etc. and currently I have a working example of code where everything exist within the main.cpp file. The issue I am facing is that when i move the clas...
In OuterAPI* you have declared people as a member of type InnerAPI*. You can either call your API using api.people->get() or make the member a InnerAPI instead. EDIT: It seems the error, besides the pointer thing, comes from how you handle file includes. I managed to get a working version on REPL.it. I made slight adju...
69,947,598
69,947,821
Convert a function pointer to another having more arguments
Suppose I am trying to use a function which accepts a binary function and calls it with some arguments: typedef double (*BinaryFunction)(double a, double b); typedef double (*UnaryFunction)(double a); // Can't change this double ExternalFunction(BinaryFunction binaryFunction) { return binaryFunction(1, 2); } Now ...
Use an external variable to hold the unary function. Include standard disclaimers about how inelegant and non-thread safe this is, etc. but at least this is a hack consistent with the stated requirements: #include <iostream> typedef double (*BinaryFunction)(double a, double b); typedef double (*UnaryFunction)(double a...
69,947,908
69,948,121
Why can't lvalue references bind to const "forwarding references"?
"forwarding references" is in quotes because const-qualified forwarding references aren't actually forwarding references, but I wanted to make it clear that I am specifically referring to function templates. Take the following test functions (code is duplicated to avoid : #include <iostream> #include <type_traits> #inc...
Actual forwarding references are indeed special-cased to deduce a reference type. See [temp.deduct.call]/3: If P is a cv-qualified type, the top-level cv-qualifiers of P's type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction. ... If P is a forwarding refer...
69,948,322
69,969,005
Visual Studio 2019: Auto Indent
Apologies for the triviality of this problem - I can't seem to find an answer anywhere. Suppose I have the following block: int plus(int x, int y) { int z = x + y;% Cursor is here } After pressing return, I want the cursor to land here: int plus(int x, int y) { int z = x + y; % Cursor is here } But right ...
You can set Tools -> Options -> Text editor -> C/C++-> Tabs -> Indenting:Smart in Visual Studio.
69,948,501
69,948,700
How do I write this pseudocode in C++? Function returns two arrays to two initialized arrays
I am trying to implement a bottom up approach function to the rod cutting problem and I need to use this particular pseudo-code from the CLRS textbook. In it there two functions and one calls the other in this fashion (r,s) = EXTENDED-BOTTOM-UP-CUT-ROD(p,n) Where r and s are two different arrays. The function also retu...
You can use tuples and "structured binding" in C++17 to return multiple values efficiently as below: #include <tuple> #invlude <vector> std::tuple<std::vector<int>,std::vector<int>> func_that_returns_two_vectors() { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = {4, 5, 6}; return {std::move(v1), std...
69,949,097
69,960,720
Unable to use CA2CT and CW2T in Visual Studio 2022 when C++20 is specified
I am having a problem trying to use C++20 with Visual Studio 2022: For example: CA2CT CW2T CA2W error C2440: 'initializing': cannot convert from ATL::CA2W to ATL::CStringT<wchar_t,StrTraitMFC<wchar_t,ATL::ChTraitsCRT<wchar_t>>> If I revert to C++17 it is fine. Why is this? Here is an example: CLSID AppCLSID ; if ...
The issue evidently relates to /permissive- compiler option. If c++20 is selected, the compiler forces /permissive- option. /permissive- (Standards conformance) The /permissive- option is implicitly set by the /std:c++latest option starting in Visual Studio 2019 version 16.8, and in version 16.11 by the /std:c++20 opt...
69,949,194
69,951,995
OpenGL 2D Circle - Rotated AABB Collision
I have trouble figuring out a way to detect collision between a circle and a rotated rectangle. My approach was to first rotate the circle and the rectangle by -angle, where angle is the amount of radians the rectangle is rotated. Therefore, the rectangle and the circle are aligned with the axes, so I can perform the b...
Let rectangle center is rcx, rcy. Set coordinate origin in this point and rotate circle center about this point (cx, cy are coordinates relative to rectangle center): cx = (circleX - rcx) * cos(-angle) - (circleY - rcy) * sin(-angle); cy = (circleX - rcx) * sin(-angle) + (circleY - rcy) * cos(-angle); Now get squared ...
69,950,385
69,950,522
How to solve the VS code error includePath in C++?
In C++ when I run the program it shows the error "no such directory found" and reflects "edit include path" when we right-click on the bulb which is appearing on the header file.
Well, I'm just a beginner. I tried many solutions for this problem but found nothing and finally realized there is this one teeny tiny error. that being, I wrote the wrong extension which was".c", while the extension used for C++ is ".cpp" // and this worked for me.
69,950,551
69,957,000
How to build and use an external library with CMake
I am trying to build a portable sound synthesiser using the cross-platform library portaudio. The library has it's own CMake file to be built with. I think I have managed to build it as part of my project (build finishes with exit code 0) but I can't figure how to actually use it's imports. Any #include I try to use re...
I had to also link the executable with the library with target_link_libraries(sound-synth PortAudio). Then on windows I had the problem that the .dll was placed in a separate folder from the .exe. So I just added a copy file command and that fixed it.
69,950,658
69,952,705
Setting maximum static alignment in Eigen from CMake
I'm working in a general CMake script that provides a grateful fallback strategy regarding activation of vectorization capabilities while compiling a project with Eigen. Using Eigen 3.4 with C++17 standard and compiled with an updated compiler (ex. gcc > 7), there is no code requirements for the developer to comply reg...
While fabian idea is great it has one huge drawback - you have to run the executable. Not always can you run the executable. The goal is to get the value of alignof(std::max_align_t) without running anything, only with compilation. And we can do it. As always, learn from the best. From CMake modules inspect files: CMak...
69,950,750
69,950,772
How do I avoid checking everything with a different If using for loops?
In C++, how do I avoid walls of ifs using for loops? stackoverflow is requesting more text soo... Code Example: if(masiv[0][0] == 'X'){ masiv[0][0] = '1'; } if(masiv[0][1] == 'X'){ masiv[0][1] = '2'; } if(masiv[0][2] == 'X'){ masiv[0][2] = '3'; } if(masiv[1][0] == 'X'){ masiv[1][0] = '4'; } if(masiv[1][...
for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { if (masiv[y][x] == 'X') { masiv[y][x] = '1' + 3 * y + x; } } } Some explanation follows. The following pattern is repeating: if (masiv[...][...] == 'X') { masiv[...][...] = '...'; } Because it is repeating, we put it to the body of the fo...
69,950,981
69,951,073
How to check if a member function or free function is for the exact given type(not any of its base)?
A way to check if a member function/free function can be invoked on an object would be to: #include <type_traits> #include <utility> template <class T, class = void> struct HasMember : std::false_type {}; template <class T> struct HasMember<T, std::void_t<decltype(std::declval<T>().Foo())>> : std::true_type {}; templ...
The implementation of HasMember and HasFreeFoo is reasonable since C can indeed obtain Foo() through inheritance. What you need is to implement another trait to choose whether to invoke through the member function or the free function. For example: template <class T, class = void> struct UseMemberFoo : std::false_type ...
69,951,144
69,951,246
Why doesn't std::tie work with const class methods?
#include <string> #include <tuple> #include <stdexcept> using namespace std; class Date { public: Date() {}; Date(int new_year, int new_month, int new_day) { year = new_year; if ((new_month < 1) || (new_month > 12)) { throw runtime_error("Month value is invalid:...
Your member functions return copy of the members(aka temprory rvalue), and std::tie has argument list, which try to bind by non-cost lvalue ref. template< class... Types > constexpr std::tuple<Types&...> tie( Types&... args ) noexcept; // ^^^^^^^^^^^^^^^^ This is simply not possible as...
69,951,242
69,951,393
Diamond Problem C++: Derived class of diamond calls default constructor
So as part of the public API of my program I expose class D, such that the user inherits from class D to create their own classes. However class D is the tip of the deadly diamond and I have run into an issue where the user's classes are calling the default constructor of class A, instead of the parametrized constructo...
When constructing a class that has any virtual bases, initializers that name a virtual base class are only called for the most derived class. If your class has any virtual base classes, and you want to use the non-default constructor of that virtual base, then you must specify that constructor in the derived class. 1 "...
69,951,402
69,951,522
How do I get weighted sum of 2 vectors in C++?
I saw the post here to sum 2 vectors. I wanted to do a weighted sum. std::vector<int> a;//looks like this: 2,0,1,5,0 std::vector<int> b;//looks like this: 0,0,1,3,5 I want to do a * 0.25 + b * 0.75 and store in some vector. I saw this function std::transform but wanted to know how do I write a custom operation for tha...
Version 1: Using std::transform and a lambda #include <iostream> #include <vector> #include<algorithm> int main() { std::vector<int> a{2,0,1,5,0}; std::vector<int> b{0,0,1,3,5}; //create a new vector that will contain the resulting values std::vector<double> result(a.size()); std::transform (a.be...
69,951,456
69,952,404
std::this_thread::sleep_for doesn't exist - Windows 10 g++
I am currently running a test program which executes perfectly well online (replit.com), but when I run it locally (on Windows 10 with gcc and g++) I get an error: test.cpp: In function 'int main()': test.cpp:18:8: error: 'std::this_thread' has not been declared std::this_thread::sleep_for(std::chrono::milliseconds(...
I went back to replit.com to see what they were doing to compile the program. Apparently they used the -pthreads switch: g++ -pthread -std=c++17 -o main main.cpp Which now works for me.
69,952,077
69,953,068
MSCV give an error about "unrecognized source file type..." although I didn't specify any arguments
I'm having a problem about MSVC. When I try run Developer command prompt and type cl, it give me this error: Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30137 for x86 Copyright (C) Microsoft Corporation. All rights reserved. cl : Command line warning D9024 : unrecognized source file type 'C:\Program', objec...
Check if you have a user or system environment variable called either CL or _CL_ defined. Assuming Windows 10, go to Start → Settings → System → About → click on the Advanced system settings link, then in the System Properties dialog, on the Advanced tab, click the Environment Variables… button to see and check in both...
69,952,644
69,952,694
printing content of an array into .txt file
the ifstream part(reading .csv file into array) works perfectly but the ofstream part(printing array into .txt file) gives error. got error no match for 'operator<<' #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <iomanip> using namespace std; int main() { ...
There is no operator overloaded for the std::vector<std::vector<std::string>> in the std::ofstream, so you can't do that. One way you could do this is: std::ofstream myfile("test1.txt"); if (myfile) { //https://www.cplusplus.com/reference/ostream/ostream/write/ for (auto& elem : array) { for (auto& ...
69,952,780
69,954,585
Regex to replace single occurrence of character in C++ with another character
I am trying to replace a single occurrence of a character '1' in a String with a different character. This same character can occur multiple times in the String which I am not interested in. For example, in the below string I want to replace the single occurrence of 1 with 2. input:-0001011101 output:-0002011102 I ...
If you used boost::regex, Boost regex library, you could simply use a lookaround-based solution like (?<!1)1(?!1) And then replace with 2. With std::regex, you cannot use lookbehinds, but you can use a regex that captures either start of string or any one char other than your char, then matches your char, and then mak...
69,952,790
69,952,884
why i can't pass a char pointer to lambda. C++ Primer ex13.44
I am writing a simplified version of std::string. When i'm writing the free function, i use the for_each function like this: void String::free() { std::for_each(element, end, [this](char *c){ alloc.destroy(c); }); alloc.deallocate(element, end-element); } This function will destory the char memory, and delete ...
From std::for_each documentation: template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); Applies the given function object f to the result of dereferencing every iterator in the range [first, last), in order. Note the emphasis on result of dereferencing...
69,952,992
69,953,057
Subtract each elements of an array consecutively
I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5. But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size. Then, to get the inputs, I use the...
You can/should use a dynamic sized container like std::vector as shown below: #include <iostream> #include <vector> int main() { int n = 0; //ask user how many input he/she wants to give std::cout << "How many elements do you want to enter: "; std::cin >> n; std::vector<int> vec(n)...
69,953,378
69,953,486
Figuring out why capturing by reference in a nested lambda produces a weird result
When the outer variable x is captured by value return [=](int y){ return x * y; }; foo(2)(3) produces 6. However if I capture x by reference return [&](int y){ return x * y; }; foo(2)(3) produces 9. Minimal Code #include <iostream> #include <functional> int main() { using namespace std; function<function<int...
x is local to the outer function, so it's destroyed as soon as that function returns. Consider a simpler example. #include <iostream> #include <functional> int& foo(int x) { return x; } int main() { using namespace std; int& b = foo(5); return 0; } Here it's easier to see that b is a dangling referen...
69,953,667
69,954,097
Why is array of characters(char type) working with unicode characters (c++)?
When i wrte this code : using namespace std; int main(){ char x[] = "γεια σας"; cout << x; return 0; } I noticed that compiler gave me output which i excepted γεια σας Although the type of array is char, That is, it should just accept ASCII characters. So why compiler didn't give error?
Here's some code showing what C++ really does: #include <iostream> #include <iomanip> using namespace std; int main(){ char x[] = "γεια σας"; cout << x << endl; auto len = strlen(x); cout << "Length (in bytes): " << len << endl; for (int i = 0; i < len; i++) cout << "0x" << setw(2) <<...
69,953,687
69,954,347
C++ - Calculate the millisecond from ptime in total seconds
How do i calculate the millisecond difference from the following Ptime ,I am using boost::ptime I'm trying to calculate the time_duration in milliseconds to find the difference. i get value like 999975 but expected value is 975 ptime PreviousgpsTime = Mon Jun 28 17:07:10.054 2021 ptime NextgpsTime = Mon Jun 28 17:0...
Live On Coliru: #include <boost/date_time/posix_time/posix_time.hpp> int main() { using namespace boost::posix_time; ptime PreviousgpsTime = time_from_string("2021-Jun-28 17:07:10.054"); ptime NextgpsTime = time_from_string("2021-Jun-28 17:07:11.025"); long totalDiff = (NextgpsTime - PreviousgpsT...
69,954,329
69,965,184
How do you save a setquery count to a string in Qt
QSqlQueryModel * model=new QSqlQueryModel (); int i,id; QString count; model->setQuery("SET '"+count+"' =(SELECT COUNT(*) from COLLABORATEUR)"); qInfo() << count; i tried this code but count is still clear i always get "" i tried it like this too: model->setQuery("SELECT '"+count+"'=COUNT(*) from COLL...
If you just need to count the number of records, then use directly rowCount(). QString count = QString::number(model->rowCount()); qInfo() << count;
69,954,361
69,954,489
Game Engine: Class parameter
I am doing university work for a game engine and we needed to do an agnostic code. They told us to do the rest on our own and I am on the right track however, when I try and pass the parameters for the function it says it doesn't pass for the arguments? This I believe is due to the class parameter that I have on there....
The call to "new OpenGLVertexBuffer" expects three arguments a void* an uint32_t a BufferLayout You pass vertices, a void* (okay) sizeof(size) - wrong. It calculates the size of the variable(!) size, which is 4 (uint32 is always 32 bits/4 bytes). So you pass the constant 4 as the second parameter. Not what you want....
69,954,723
69,955,692
Remove focus from SAVE button in OPENFILENAME win32?
Problem: If the user holds the "enter" keyboard button and opens OPENFILENAME Save As Dialog, it will automatically save the file - dialog only blinks. Desired result: The user holds the "enter" keyboard button, opens OPENFILENAME Save As Dialog, nothing happens. He needs to click on the Save button or click again the ...
The easy solution to prevent data loss is to add the OFN_OVERWRITEPROMPT flag. This does not prevent the issue from happening if the suggested name does not already exist as a file. To actually interact with the dialog you need OFN_ENABLEHOOK and a hook function. When you receive WM_NOTIFY, you can handle CDN_FILEOK to...