question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
67,680,789 | 67,680,799 | scope of const auto variables | I have a simple function
void simpleFunction(){
const auto img= getImageSomehow();
// do something with img
}
it works ok. However I want to modify this function to include a boolean there as:
void simpleFunction(bool isGPU){
if(isGPU){
const auto img= getImagefromGPU();
}
else{
const auto img= getImage... | One option is to refactor the code that "does something with img" into a template
template<typename ImageType>
void do_something(ImageType const img) // img is const here as desired
{
// do something with img
}
and then your original function becomes
void simpleFunction(bool isGPU)
{
if(isGPU)
do_something(g... |
67,680,812 | 67,680,980 | C++: Accepting user input until *two* blank lines are received | I am writing code concerned with the user's input. I would like to keep on receiving the user's input until the user enters two blank lines (the user consecutively hits the 'return' button twice for the two blank lines and on the third 'return' the user input terminates.)
The code I have so far is:
int number_of_empty_... | Try this:
int main() {
int number_of_empty_res = 0;
string data;
vector<string> myvec;
while (getline(cin, data))
{
if (data.empty()) {
number_of_empty_res += 1;
if (number_of_empty_res > 2)
{
break;
}
}
else
... |
67,680,829 | 67,683,559 | Enabling ADL for distance within a non-std:: namespace, with a fallback to std::distance | My use-case is as follows - within a non-std:: namespace, a class has a templated member function which takes in 2 (templated) iterators as parameters, and part of the function call involves calling distance() on those iterators.
The problem is, some containers have their own overload for distance() for their iterators... | The idiomatic way of doing so (commonly done with swap):
namespace derp
{
template <class iterator_t>
int a_function(iterator_t t1, iterator_t t2)
{
using std::distance;
int a = distance(t1, t2); // want to resolve to std::distance if, for example, iterator is from std::vector
// Do stuff wit... |
67,681,060 | 67,681,084 | How to return an object in a vector of pointers | My Local class is like this
I have this class on my program where I store the pointes of objects that I'm creating in this vector called insumos.
My problem is, how do I return a specific pointer of an object of this vector on a method that looks like this.
Methods
On the first method I'm able to return the vector, but... | You use a subscript:
Insumo *Local::getIn()
{
return insumos[0];
}
Subscript 0 means element #1, 1 means element #2, etc.
You can also do this:
Insumo *Local::getIn()
{
return insumos.at(0);
}
which is equivalent to the first use case.
begin() returns an iterator, which is a more advanced topic.
More info on ... |
67,681,281 | 67,681,505 | Cannot call objects c++ | I'm new to c++ and stack overflow so excuse me if I don't completely understand what your saying, my goal is to convert my tic tac toe code from using functions into classes and objects using header files.
After creating an object that returns a string to be used in the outcome by int main, I declare it in main.cpp and... | Firstly, the member function rps will be inaccessible, if you want it to be called by class users (i.e. in the main, not internally by class instances), you need to put it in public.
class Game {
public:
std::string rps(std::string p1, std::string p2);
};
Then you'll need to create an instance of the Game in main.... |
67,681,302 | 67,681,946 | Im having a trouble at subtracting a number that contains 3 in a c++ loop | so i am having a trouble in subtracting a number that contains 3 in c++
i just couldnt get it right maybe you can help me in analyzing
here is my
code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int integer, sum = 0;
cout << "Enter an integer: ";
cin >> integer;
for (int i ... | Here's your existing source code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int integer, sum = 0;
cout << "Enter an integer: ";
cin >> integer;
for (int i = 1; i <= integer; ++i) {
sum += i;
if (i == 33 || i % 10 == 3) {
i = sum - i;
}
}
... |
67,682,335 | 67,684,928 | semaphore header not found on visual studio 2017 | I'm trying to use :
#include <semaphore>
on a a cpp dynamic library project created on vs2017.
The file is not found by the preprocessor. (mutex header is found..)
What am I missing?
Yigal.
| Standard library header <semaphore> was added in C++20. If you look at the Compiler Support page for C++20, you can see that it is supported by MSVC from version 14.28/1928. MSVC 14.28/1928 was introduced in Visual Studio 2019 v16.8, so older verions will not know the library.
|
67,682,423 | 67,712,831 | Overcoming the copy overhead in CUDA | I want to parallelize an image operation on the GPU using CUDA, using a thread for each pixel (or group of pixels) of an image. The operation is quite simple: each pixel is multiplied for a value.
However, if I understand it correctly, in order to put the image on the GPU and have it processed in parallel, I have to co... |
However, if I understand it correctly, in order to put the image on the GPU and have it processed in parallel, I have to copy it to unified memory or some other GPU-accessible memory
You understand correctly.
I am wondering whether there is a more efficient way to copy an image (i.e. a 1D or 2D array) on the GPU tha... |
67,682,689 | 67,682,856 | Declaring 2D Vector in Global Scope gives segmentation fault | #include <bits/stdc++.h>
using namespace std;
int n;
std::vector<bool> visited(n,false);
std::vector<std::vector<int>> g(n,std::vector<int>(n));
int main() {
cin>>n;
//std::vector<std::vector<int>> g(n,std::vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
... | When visited and g get initialized, the value of n is 0. (n is declared in global namespace and will be zero-initialized.) So the vectors are empty and contain no elements. Then access to them like g[0][0] leads to UB.
On the other hand, for the vector g declared in main(), n is set to some value and then used to initi... |
67,682,807 | 67,682,915 | the declare scope of loop | Can anyone explain to me, why the below codes have different output?
void GenerateMatrix(int mat[][MaxSize],int ran[],const int rows,const int cols)
{
int i,k=0;
while (i<rows)
{
int j=0;
while (j<cols)
{
mat[i][j]=ran[k];
j,k++;
}
... | You seem to be following a "spoken English" approach to using the ,, like "do something to this list of variables". In this reading, the initialisation failure (where it does create a list other than you mean; spotted by CherryDT) and the incrementation failure (caused by misuse as comma operator; spotted by two commen... |
67,683,047 | 67,683,226 | Can we stop a std::list from tidying up memory? | I defined this list:
using SpecialEventList = list<SPECIAL_EVENT_S*>;
The items are added to this list like this:
m_listNewSpecialEvents.push_back(psEvent);
The original list of SPECIAL_EVENT_S pointers is owned and managed by another list help in the app class.
My concern is that when this dialog closes that m_listN... | It won't delete pointers unless you explicitly delete them. raw pointers don't get deleted automatically. link
|
67,684,063 | 67,684,138 | How to static_cast a pointer to const member function? | Surprisingly (embarrassingly?) I cannot get the syntax of the static_const of a const member function right. In short (details below) if the member function is not marked const I use:
static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&)>(&mymodule::Foo::bar)
but marking the member function Fo... | You should add const at last as:
static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&) const>(&mymodule::Foo::bar),
// ^^^^^
|
67,684,224 | 67,684,322 | integar array palindrome checker | i made this program to make a function to check if integar array is palindrome or not.it is always giving output that it is not a palidrome on every input. can you plz help me out?
code:
#include<iostream>
using namespace std;
void palindrome(int[],int[],int);
int main()
{
int size=5;
int array1[size];
int... | You can't compare two arrays with ==, it will only compare if the array's address are equals, so different arrays never equals, we can switch it to std::equal
There is one memory issue with array2[i]=array1[size-i];, you will get a buffer overflow.
This is a slighly modified version of your code:
#include <iostream>
us... |
67,684,274 | 67,684,361 | How can I cancel a thread using C++? | POSIX provides the function pthread_cancel to cancel thread execution but seems C++ does not provide a such function
Also is it possible to use a mix std::thread and pthread_cancel ?? I also see on linux system , std::thread is a wrapper of POSIX thread
| Although there is no exact replacement for pthread_cancel, you can come close with jthread.
The class jthread represents a single thread of execution. It has the same general behavior as std::thread, except that jthread automatically rejoins on destruction, and can be cancelled/stopped in certain situations.
This wil... |
67,684,297 | 67,685,539 | How to read a number from a file and use it as a variable in C++? | Let's say I have a file I'm reading that goes something like this :
#character posX posY //commentary line: explains what it represents
CharacterName1 50.0 0.0
CharacterName2 32.0 50.0
The goal here is to be able to read the posX et posY and convert them in my C++ program into 2 doub... | Hope this piece of code will help.
#include <bits/stdc++.h>
using namespace std; //change headers and namespaces; included for ease of use;
vector<string> split(const string &text, const char sep) {
vector<string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) not_eq ... |
67,684,306 | 67,684,368 | why is destructor called earlier? | I wrote this code to learn the shared_ptr object creation inside my own class.
Why is A object shared_ptr destroyed even before A's print (obj->print() inside B's print) is called?
#include <iostream>
#include <memory>
using namespace std;
class A {
private: string str;
public:
A(string s){
str... | In B::B(string), shared_ptr<A> obj = make_shared<A>(s); is constructing a local object which gets destroyed immediately when the constructor ends; it has nothing to do with the data member obj, which points to nothing as the result.
I think you want:
B(string s) {
cout << "shared_ptr creation" <<endl;
obj = mak... |
67,685,121 | 67,689,550 | Does "used as non-type template parameter" make a function template implicitly instantiated? | I want to write a class template M that accepts incomplete type C as template parameter.
But I also want C has some traits when it is eventually defined.
Is this code guaranteed
to compile if defined(FLAG),
and to fail the compiling if !defined(FLAG)?
template <auto> struct Dummy {};
template <typename C>
void check... | From a n4713,
Point of instantiation [temp.point] (17.7.4.1/8)
A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation des... |
67,685,406 | 67,685,450 | Set modification date to February the 30th | It may sound bizzare but I have to set programmatically file modification date to 30th February. Is it possible to do so? Programming language doesn't matter.
| File modification is epoch timestamp (number of milliseconds since midnight 01.01.1970), it is the calendar in the locale that is giving that timestamp a meaning of year/month/day. All you need to do is create your own calendar with 30 days in February (it is probably not a easy task).
|
67,685,744 | 67,687,528 | Fix Android Studio C/C++ project compile issues | I have an Android Studio project which has C/C++ functions, when I try to build apk, I get this errors, I have searched online for possible fix but could not ix this particular problem.
Error:
C/C++ debug|x86 : CMake Error in C:/Projects/codecanyon-oxoo-android-live-tv-movie-portal-app-with-powerful-admin-panel-v1.3.4/... | Windows paths are limited to 260 characters by default. The path to CMakeCCompiler.cmake is 272 characters long so will cause problems for some Windows APIs and applications. Use a shorter path to fix the problem.
|
67,686,102 | 67,739,136 | How to get the IDWriteFont object from the font file downloaded in windows OS and not installed yet | Hi I am using DWrite APIs to get the system fonts metadata using DWrite APIs. I am doing the following.
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown **>(&factory)));
// Get the system font collection.
IDWriteFontCollection *... | I found a work around for this problem
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory3),
reinterpret_cast<IUnknown **>(&factory)));
HR(factory->CreateFontSetBuilder(&fontSetBuilder));
HR(factory->CreateFontFileReference(utf8ToUtf16(fontFilePath.c_str()), NUL... |
67,686,263 | 67,690,678 | Why doesn't the compute shader do the calculation? | I'm experimenting with compute shaders. What I want to do is sending the data of arr1 to compute shader variable shader_arr1[], make all of its elements 1 and read that result back to the CPU side in arr2[] variable. However, running the following program I get the same initial value of arr1[]{1,2,3,4,5,6,7} in arr2[],... | I fixed the code. This is the working version of the program
GLuint program = glCreateProgram();
GLuint computeShader = glCreateShader(GL_COMPUTE_SHADER);
const GLchar* const shaderSrc = {
"#version 310 es\n"
"\n"
"layout (local_size_x = 1) in;\n"
... |
67,686,373 | 67,686,492 | Object oriented programming get function doesn't return correct array | This is the code that i have problem with. It reads pin codes from text file and it should save them into array with object oriented programming. when I try to display the values in while loop it works fine, but when i try to do it outside while loop, it doesn't work. As for example in the second to last line cout does... | You have a loop inside a loop...
With the first iteration of
for (int i = 0; i <= 100; i++) { ... }
you will read all of the contents of the file because of the inner loop
while (getline(myfile, line))
The second iteration of the outer for loop will not read anything at all, and neither will the next 99 iterations.
T... |
67,686,677 | 67,686,727 | How is while loop working without a block of code, shouldn't it work only for curly braces? | I know that while loops have a body part with two curly braces { }. And I know that how while loops work. But when I was reading a book on C++, I found this code:
#include <iostream>
int main()
{
int sum = 0, value = 0;
// read until end-of-file, calculating a running total of all values read
while (std::ci... | The while's syntax is of the following form (simplified, check the link for more info):
while ( condition ) statement
Therefore, we need to supply it a statement after the condition part.
Curly braces denote a compound statement (a.k.a block, block statement). It is a group of zero or more statements that is treated b... |
67,686,816 | 67,686,961 | How can I declare an attribute with the same class of it? | I'd like to build a Fraction class and to do that I want to use the class to declare the attributes inside of it like this.
class Function {
private:
Fraction num;
Fraction den;
public:
// Methods...
}
How can I do it? Thank you in advance for your time.
P.S.: sorry for my bad en... | you cannot use class itself as member.
but you can do something like that with pointers:
class A
{
public:
A* first;
A* something_else;
}
most data structure like linked list or list or tree used this approach.
|
67,687,042 | 70,083,182 | Building multiple projects in MS visual studio 2013 | I have a MS Visual Studio 13 solution that has many (ca 20) projects inside.
Projects share some source code files.
I didn't figure out how to build all projects at once. When I select them and do Build > Build selection, or just Build > Build solution, visual studio throws such errors:
Error 249 error C1083: Cannot o... | Problem was that many of my projects shared the same namespace.
After making the RootNamespace unique for all the projects everything works fine.
This is where to find it in *.vcxproj file
<PropertyGroup Label="Globals">
<ProjectGuid>{85936F95-D218-4D69-B8F2-684C2A86F850}</ProjectGuid>
<RootNamespace>THIS_MUS... |
67,687,239 | 67,962,749 | Dynamic change of style from combobox value qml | Everyone, I have made my own style and add this to qml.qrc then I calling it in main.cpp:
engine.addImportPath("qrc:/Styles");
QQuickStyle::setStyle(Modern style);
Everything is working, but I've to make it dynamically changing from C++ code, and taking value from combobox
I've tried to add:
char str1[] = "Basic";
en... | i've founded solution:
It is not possible to change the style on the fly, because QQC2 styling is based on QML type registration time file selection, but it is possible to:
unload all QML,
destroy any existing QQmlEngine instance(s),
call qmlClearTypeRegistrations(),
call QQuickStyle::setStyle(),
and then re-load the Q... |
67,688,023 | 67,733,641 | SCOPE_IDENTITY() always return NULL if used with SQLBindParameter | I try to insert a data to database via ODBC sql server.
And I want to get the Id of this row back, so I use SELECT SCOPE_IDENTITY();
Since this table has id as primary key and auto increment.
Insert function works fine, the data get inserted into database.
But when I use SELECT SCOPE_IDENTITY(); They return NULL.
so I ... | The solution for this problem is to use "OUTPUT" clause in order to return member of inserted item instead of calling SELECT SCOPE_IDENTITY();
so the completely sql command is INSERT INTO [dbo].[Test] ([Name], [Position]) OUTPUT INSERTED.[Id] VALUES (?,1);
|
67,688,064 | 67,688,518 | C++ creating a std::vector from std::string array | I am learning about c++ and was following a course. A final exercise involves making a program for deck of cards. I have thought of an approach:
I initially tried to do everything with string arrays but realised that it would make more sense to use vectors since. I am now trying to create a std::vector std::string out ... | Easy way:
std::vector<std::string> cards {
"As","2s","3s","4s","5s","6s","7s","8s","9s","Ts","Js","Qs","Ks",
"Ah","2h","3h","4h","5h","6h","7h","8h","9h","Th","Jh","Qh","Kh",
"Ad","2d","3d","4d","5d","6d","7d","8d","9d","Td","Jd","Qd","Kd",
"Ac","2c","3c","4c","5c","6c","7c","8c","9c","Tc","Jc","Qc","Kc... |
67,688,099 | 67,717,789 | Parallel-hashmap: determining C++ version | I build a program using parallel-hashmap package taken from the latest vcpkg in Visual Studio 2019 with stdcpplatest flag (activating C++20 standard) and get an error
>C:\vcpkg\installed\x64-windows\include\parallel_hashmap\phmap_base.h(335,39): error C2039: 'result_of': is not a member of 'std'
In the code as follows... | As n. 'pronouns' m. suggested in the comment above, one has to add command line option /Zc:__cplusplus to Visual Studio compiler, which will set proper value to __cplusplus macro.
The other option is to write the check as follows:
#if (defined(_MSVC_LANG) && _MSVC_LANG >= 201703) || __cplusplus >= 201703
which will be... |
67,688,801 | 67,688,857 | Dont understand why i have problem like this: '{': no matching token found | template<class T>
class Matrix
{
private:
T** m_iArr;
int size_row;
int size_col;
public:
Matrix();
Matrix(int size_row_BuUser, int size_col_BuUser);
int count();
};
template <class T>
Matrix<T>::Matrix()
{
size_col = 0;
size_row = 0;
m_iArr = new T * [size_row];
for (int i = 0; ... | You are missing a closing parenthesis
if (m_iArr[i][j] < (m_iArr[i][j - 1])
Should be:
if (m_iArr[i][j] < (m_iArr[i][j - 1]) )
|
67,688,814 | 67,690,228 | "xtime: ambiguous symbol" error, when including <boost/asio.hpp> | As said in the title, when I'm trying to include asio.hpp from boost I get this error:
'xtime': ambiguous symbol (compiling source file FILEPATH)
note: could be 'xtime' (compiling source file FILEPATH)
or 'boost::xtime' (compiling source file FILEPATH)
I have read that this issue can be linked with "using n... | As sehe mentioned in comments, reordering include statements in FILEPATH have resolved the problem.
|
67,689,282 | 67,690,962 | How to draw an image from a 2d array in modern openGL | I want to draw points with openGL, I have a 32x32 screen size and I want to fill it with the color red, however I don't understand how the parameters of glVertex2f(-1, 0.5) are working
My first instinct was to do something like this:
glutInit(&argc, argv); // Initialize GLUT
glutCreateWindow("OpenGL Set... | I recommend to use an Orthographic projection. In Orthographic Projection, the view space coordinates are linearly mapped to the clip space coordinates and normalized device coordinates. The viewing volume is defined by 6 distances (left, right, bottom, top, near, far). The values for left, right, bottom, top, near and... |
67,689,290 | 67,690,821 | Find the Narcissistic value among below numbers | #include<iostream>
#include<stack>
#include<cmath>
using namespace std;
int Narsic(stack<int> stk)
{
int x=0;
int temp=0;
int val=0;
int power_count = stk.size();
while(! stk.empty())
{
x = stk.top();
stk.pop();
temp = pow(x,power_count);
val... | It looks like you're largely asking about style. I'm going to take your code and edit it to be more in keeping with what I would do, then I'll comment below.
#include <iostream>
#include <stack>
#include <cmath>
using std::cout;
using std::endl;
using std::stack;
/**
* Return the Narcissistic value of the digits sto... |
67,689,388 | 67,689,620 | Member variables initialization | Is there any difference regarding the initialization of the x member variable in these cases:
struct A {
int x;
A() {}
};
struct B {
int x;
B() : x(0) {}
};
struct C {
int x;
C() : x() {}
};
For all these cases, in the tests I did, x is always set to the initial value of 0. Is this a guarante... | For B::B(), x is direct-initialized as 0 explicitly in member initializer list.
For C::C(), x is value-initialized, as the result zero-initialized as 0 in member initializer list.
On the other hand, A::A() does nothing. Then for objects of type A with automatic and dynamic storage duration, x will be default-initialize... |
67,690,257 | 67,690,399 | Does passing new int(71) as an argument of type int* cause memory leaks as well? | The third parameter of createTrackbar() is of type int*. When I have global variable int globalKSize, I can pass it as the third argument. However, I want to avoid defining many global variables. So I want to replace globalKSize with localKSize as shown in the following code.
Unfortunately, localKSize is now inaccessib... |
Does passing new int(71) as an argument of type int* cause memory leaks as well?
If it is deleted, then there is no leak. If it is not deleted, then there is a leak. Did you delete it?
Could give me smarter solutions?
No. Your solution A seems fine.
I cannot pass nullptr as the 3rd argument as well.
Why not? Acc... |
67,690,531 | 67,691,527 | how to pass values for the base class constructor in the inherited constructor | I have to classes car and vehicle I am trying to use parametrized constructor to set values for the Car object members but it gives errors
#include <iostream>
#include <string>
class vehicle {
int wheels ;
double price ;
std::string color ;
public:
vehicle(int , double , std::string ) ;
void in... | You have to explicitly call your base constructor and with constructor initializer list you can greatly simplify your code:
#include <string>
class vehicle {
int wheels ;
double price ;
std::string color ;
public:
vehicle(int wheels, double price, std::string color) :
wheels(wheels), price... |
67,691,007 | 67,691,434 | Compiler discrepancy with simple meta function | When I try to use the following meta function to retrieve the first type of a tuple, the code can be compiled with GCC but not with Clang. I have two questions regarding the little snippet.
Is this legal C++ code? And why? Or why not?
Is there a workaround (or correct alternative) which works for both compilers?
#inc... | Temporarily changing your struct declaration to (thus getting rid of the incomplete type):
template<typename>
struct first_type {};
Changes the error you get to:
no type named 'type' in 'first_type<std::tuple<int, int, double>>'
This gives us valuable information: the compiler chose the generic version of the templat... |
67,691,055 | 67,692,508 | What happens when an rvalue reference is captured by copy? | If I have
std::function<int()> &&x = [] { return 1; };
auto lambda = [y = x(), x] {
return y * x();
};
What is the type of x inside lambda: std::function<int()>, std::function<int()>& or std::function<int()>&&? And if the first, is the captured x initialized by the move constructor, or by the copy one (and I need... |
What is the type of x inside lambda
x is captured by-copy, and the type of data member declared in the closure type would be std::function<int()>. [expr.prim.lambda.capture]/10
(emphasis mine)
For each entity captured by copy, an unnamed non-static data member is
declared in the closure type. ... The type of such a ... |
67,691,154 | 67,887,023 | c++: AWS S3 Object Lambda | AWS recently introduced S3 Object Lambda, however looking at the online documentation:
Writing and debugging Lambda functions for S3 Object Lambda Access Points
Introducing Amazon S3 Object Lambda – Use Your Code to Process Data as It Is Being Retrieved from S3
How to use Amazon S3 Object Lambda to generate thumbnails... | Answering my own post after a couple of weeks of struggle.
Basic point is summarized at Introduction to Amazon S3 Object Lambda
The JSON payload of interest is simply:
{ "xAmzRequestId": "1a5ed718-5f53-471d-b6fe-5cf62d88d02a",
"getObjectContext": {
"inputS3Url": "https://transform-424432388155.s3-accessp... |
67,691,252 | 67,693,485 | ROS node subscription not connected | I am using a rosbag to publish on various topics and i am trying to get my sample program to allow one node to subscribe to those topics via class method functions. But nothing is being printed out on console for the subscribers. I tried roswtf and i got
WARNING The following node subscriptions are unconnected:
* /ro... | One thing that immediately jumps to my eye is that you have actually put std_msgs::String::ConstPtr as the topic type but have topics /ecu_pcl and /velodyne_points which should not be of type std_msgs::String but instead should have a different data types, point clouds I assume, so something like sensor_msgs::PointClou... |
67,691,440 | 67,693,167 | How to store a bi-directional graph using map in C++? | I am trying to store a bi-directional graph as an adjacency list using std::map<int,vector<int>>. The idea here is to store n nodes, from 1 to n in this map.
The input is given as u v, which denotes an edge between node u and node v. We get n such inputs on n lines.
My code for storing the graph:
int u,v;
map<i... | Your bug is that you are trying to make a function named graph() remove the parenthesis then all will be fine.
|
67,691,472 | 67,700,948 | Cartesian product of multiple templates | I have a few classes:
template <int,char>
class Foo{};
template <int,char>
class Bar{};
And I want to get all combinations with a few arguments, like this:
// {1, 2}, {'a', 'b'}
using CartesianProduct = mp_list<Foo<1,'a'>, Foo<1,'b'>,...,Bar<2,'b'>>;
I can change template parameters to types and use std::integral_con... | Finally, I figured it out by myself.
using namespace boost::mp11;
template <typename C1, typename C2>
struct Foo{};
template <typename C1, typename C2>
struct Bar{};
template <template <typename...> typename... F>
using mp_list_q = mp_list<mp_quote<F>...>;
using TypeList = mp_product<mp_invoke_q,
mp_list_q<Foo... |
67,691,510 | 67,693,539 | reading from a text file into a vector - newline described as an empty vector what gives? | C++ primer has the following description and example (p. 110):
assume we have a vector<string> named text that holds the
data from a text file. Each element in the vector is either a sentence or an empty
string representing a paragraph break. If we want to print the contents of the first
paragraph from text, we’d write... | You need getline() if you want to keep the whitespace:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> text;
std::string s;
while (std::getline(std::cin, s))
{
text.push_back(s);
}
// output first paragraph
for (auto it = text.b... |
67,691,738 | 67,691,854 | How do I get a specific string from a text file in C++ | Lets say I have a text file with this input:
Caroline went to the sea, and she forgot her boat.
Patrick went to the sea, and he drowned.
How do I get the word sea and the whole line with the word sea?
So basically when I type sea the output needs to be:
Caroline went to the sea, and she forgot her boat.
Patrick went... | Well, what you just need is to iterate the lines of your file and see if the line contains the word you want. If it does, just print the line. Here is the core of what you need:
while (getline (MyReadFile, myText)) {
if(myText.find(yourString)!=std::string::npos){
cout<<myText<<\n;
}
}
The if statement ... |
67,692,827 | 67,697,226 | Same function outputs different results when calculating difference between two timestamps | I'm currently facing a weird issue where the same function outputs a different result. The function is supposed to calculate the time difference between a provided date and the current time. Since this function is supposed to work with milliseconds, my function currently looks like this:
int calcDelay(std::string dropT... | In C++20 your calcDelay can be greatly simplified. And there exists a preview of this functionality in a free, open-source, header-only library1 which works with C++11/14/17.
#include "date/date.h"
#include <chrono>
#include <sstream>
int calcDelay(std::string dropTime) {
using std::chrono::milliseconds;
da... |
67,692,877 | 67,693,620 | Why is the other solution 10 times efficient despite having the same algorithm and data structures? | I found a piece of code over leetcode and I compared the same to my solution.
Problem link: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii
Leetcode solution: (16 ms & 10.2 MB)
string removeDuplicates1(string s, int k) {
vector<pair<char, short>> st;
string res;
for (auto ch : s) {
i... | Expanding @Johannes Schaub's comment into an answer, the issue is likely with this bit right here:
for(auto& i : S) {
result = result + string(i.second, i.first);
}
The expression inside the for loop says to do the following:
Evaluate the right-hand side of the assignment statement. To do so, create a brand-new s... |
67,693,051 | 67,693,261 | Why can't I use std::iterator<>::reference with templates? | I tried to do this
template <class V>
class myiterator: std::iterator<std::random_access_iterator_tag, V>{
reference a;
};
Like in this example
class myiterator: std::iterator<std::random_access_iterator_tag, int>{
reference a;
};
But I got an error "‘reference’ does not name a type". How can I use std::itera... | The name reference is declared in the base class, and the base class is a dependent type (its type depends on V). There are special rules that apply to this situation: when the compiler sees the name reference, it does not search the dependent base class scope, and therefore, does not find the name. In order to force t... |
67,693,280 | 67,693,420 | I found this bug in my code that i created to get the highest value from 2 integers and the variable is assigning itself a value | I'm starting out to learn C++ and I'm a bit clueless as to what might be happening here. when I run the program and enter 2 equal inputs the int variable-result, automatically assigns itself the value, when it should not because none of the if statements are fulfilled.
#include <iostream>
#include <cmath>
using namesp... | When you define a variable, it will always have some value. This value, if you do not assign one, can be anything - just whatever value happens to be in the memory where it is defined. So you might see the number you inputted here, but that can be just a coincidence, or caused by some more complicated reasons on how pr... |
67,693,416 | 67,694,113 | How to store different objects, that are of the same parent, in one array? C++ | I have a Vheicle class and it's child classes Bus, Helicopter, Train.
Is there a way to store all the Bus, Helicopter, Train objects in one array together?
I have looked on internet and didn't find any working solution.
This is my code:
Class declaration:
class Vehicle {
private:
string vehicleID;
string man;
p... | In order to achieve what you're trying to do is to cast that Vehicle* to Bus*
vehicleData bus = getBus(s1);
Vehicle* arrVehicle[2];
arrVehicle[0] = new Bus(bus.vehicleID, bus.man, bus.curMileage);
// First method
printf("%i\n", dynamic_cast<Bus*>(arrVehicle[0])->currentMileage);
printf("%c\n", dynamic_cast<Bus*>(arrV... |
67,693,687 | 67,694,152 | Possible orderings with memory_order_seq_cst and memory_order_release | With reference to the following code
auto x = std::atomic<std::uint64_t>{0};
auto y = std::atomic<std::uint64_t>{0};
// thread 1
x.store(1, std::memory_order_release);
auto one = y.load(std::memory_order_seq_cst);
// thread 2
y.fetch_add(1, std::memory_order_seq_cst);
auto two = x.load(std::memory_order_seq_cst);
Is... | Yes, it's possible for both loads to get 0.
Within thread 1, y.load can "pass" x.store(mo_release) because they're not both seq_cst. The global total order of seq_cst operations that ISO C++ guarantees must exist only includes seq_cst operations.
(In terms of hardware / cpu-architecture for a normal CPU, the load can ... |
67,694,704 | 67,694,763 | Changing the value of the variable which a pointer holds the address of | I have a very simple program:
int main() {
int a = 10;
int* b = &a;
*b = 100;
return 0;
}
I understand what a pointer does, it holds the address of a variable. So in my example, the pointer b holds the address of the variable a.
This is all fine.
My issue is with how dereferencing works. From my unders... | This:
*b = 100
Can be read as "store the value 100 at the location that b points to". And because b contains the address of a, the above is effectively the same as:
a = 100;
Formally speaking, the result of the dereference operator * is an lvalue, which basically means it is an object that can be assigned to just li... |
67,695,084 | 67,695,699 | Do C++20 ranges have value(not predicate) version of filter or any_of? | Classic C++ sometimes picks the _if suffix for predicate algorithms(versus the ones that take value) e.g. find_if/find count_if/count and sometimes it does not(for example any_of does not have _if suffix although it takes predicate, and there is no any_of value version of algorithm).
As far as I can see C++20 filter or... |
Do C++20 ranges have value(not predicate) version of filter or any_of?
No.
But it is very easy to write:
std::ranges::any_of(r, [&](auto const& e){ return e == value; })
Or, if that is considered too long, you could add a helper:
inline constexpr auto equals = [](auto const& value){
return [=](auto const& e){ r... |
67,695,426 | 67,695,793 | How to use Yasnippet printf | I recently watched this fantastic video on how to use Yasnippet in Emacs.
Can someone explain how to use this snippet?
Specifically, what are the if and string-match elisp conditionals/functions doing in regards to the intended use of this snippet?
This snippet is found in Yasnippet c++-mode > printf.
# -*- mode: snipp... | So it should work if you can load it into the mode properly (there are a few yasnippet modes that failed to load properly for me -- if all else fails, in the snippet file itself use M-x yas-load-snippet-buffer and see if that works.)
As for the macro, the second argument is basically conditional on the first one contai... |
67,695,951 | 67,695,966 | C++ on VScode is not working when I run my code | So, I just recently started learning C++ and my cousin said that a good IDE was VScode. So, I installed VScode, downloaded the extensions that supported C++, and wrote my programs and got this:
"g++" is not recognized as an internal or external command.
what do I do here? I have looked at other questions that ask the ... | Based on the OS, you need to add path to g++ to PATH variable.
Check ~/.profile file?
Also check:
https://github.com/microsoft/vscode-cmake-tools/issues/576
|
67,696,054 | 67,696,113 | Implicit Conversion of Class | #include <iostream>
using namespace std;
class temp
{
public:
temp()
{
std::cout << "Constructor created." << std::endl;
}
~temp()
{
std::cout << "Deconstructor called." << std::endl;
}
};
class scopedptr
{
private:
temp* ptr;
public:
scopedptr(temp* p)
{
p... | In the line
scopedptr a = new temp();
type of a is explicitly specified as scopedptr. Any usage of a must correspond to the type scopedptr.
When in doubt, simplify.
temp* temp_ptr = new temp();
scopedptr a{temp_ptr};
Then, there is less scope for confusion.
|
67,696,232 | 67,696,544 | C++: constexpr implying implicit const to variables does not apply to reference | There has been lots of questions/answers pertaining questions to constexpr expression but i have a question which is pretty close to other question but slightly different in another sense. Anyway here it goes.
#include <iostream>
using namespace std;
constexpr int x = 1; // TAG A
int main() {
... |
Is there a difference in the word "reference to a const" and "const reference"
Yes, conceptually, but "const reference" logically collapses to just "reference" because technically all references are constant. This is also why the language doesn't let you declare references as explicitly const. That said, there are st... |
67,696,408 | 67,696,500 | glad.c unable to find glad/glad.h, but main.cpp can | I've been trying to set up a build environment for OpenGL using glfw3 and GLAD. I'm currently using WSL2 Ubuntu with an X Server for compilation and a makefile.
However, when I run my make I receive the following error:
src/glad.c:25:10: fatal error: glad/glad.h: No such file or directory
25 | #include <glad/glad.h>
... | You seem to set the CXXFLAGS (for the C++ compiler), but your glad.c is compiled with the C-compiler (which checks CFLAGS)
|
67,697,097 | 67,697,436 | How to cast v8::value to LPCSTR | I am trying to make a node add on and copying some C++ code over. One line is giving me an error
void Attach(const FunctionCallbackInfo <Value> &args) {
Isolate *isolate = args.GetIsolate();
HWND target = FindWindowA(NULL, args[0]);
...
The javascript usage is
const title = window.getTitl... | I found the solution on a forum in French https://zestedesavoir.com/forums/sujet/13978/c-probleme-de-conversion-de-type-stringchar/.
Isolate *isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<String> appName = args[0].As<String>();
CHAR* charApp... |
67,697,102 | 67,697,148 | Is there a way to pass different structs to a single class constructor | I have my own FIFO class that works OK, but I'd like to extend its flexibility.
Right now, the data struct that goes in the FIFO is defined in the FIFO class, so every FIFO object has the same data struct.
It would be nice if every object could define its own FIFO struct and pass it to the FIFO class. The FIFO class s... |
Is there a way to pass different structs to a single class constructor
No, it isn't possible to pass a type as a function argument (and constructors are (special member-) functions).
However, it is possible to pass types as template arguments, and a constructor can be an instance of a function template... Or the clas... |
67,698,523 | 67,698,585 | Error in LLVM STLExtras: expected unqualified-id before 'const' with GCC11 | I just upgraded my compiler to GCC 11.1.0 and having trouble trying to compile my program that uses LLVM.
The error that occurs is the following:
In file included from /usr/include/llvm/IR/DebugInfo.h:19,
from /home/<redacted>/src/sword/format/llvm.hpp:12,
from /home/<redacted>/src/mai... | You mention you're using C++20. This is indeed an error as of C++20: the use of simple-template-ids for constructors was deemed error-prone and redundant, and removed. See [diff.cpp17.class]/2.
As you mentioned, you can fix the error by using an injected class name instead:
template <typename R>
struct result_pair {
... |
67,698,661 | 67,708,156 | How to find a memory leak that isn;t a memory leak? | I have large program, I am noticing that memory steadily grows until my machine cannot handle it and I have to restart it.
Normally this would be a memory leak, however I have used libasan and valgrind and neither can find a leak.
What I suspect is happening is that somewhere inside the code a dynamic structure is grow... | Try https://github.com/vmware/chap
It will help you because it calculates the graph of references between allocations and also recognizes many of the various kinds of allocations used by std containers.
Run your process, uninstrumented, until it is significantly larger than you would expect then use gcore to gather a l... |
67,698,784 | 67,698,861 | C++ Abstraction OOP (Inherit only some method to derived class) | Suppose i have a socket class:
class Socket{
public:
... Some Code ...
Socket(int type){
isServer = type;
//some code
}
virtual void Send(string s);
virtual void Send(string s, int clientID);
... Some Code ...
private:
int isServer;
};
This is to be used both as a server an... | There is not absoulte way to doing such thing.
But here my idea:
create two class(like interface):
first class is server socket sender:
Class ServerSocketSender {
public:
virtual void Send(string s, int clientID);
}
second class is client socket sender:
Class ClientSocketSender {
public:
virtual void Send(... |
67,699,276 | 67,699,318 | What does 'operator sockaddr *()'mean here? | What does 'operator sockaddr *()'mean here ?
The class Raw is an inner class, sockaddr is a struct.
struct sockaddr
{
__SOCKADDR_COMMON (sa_); /* Common data: address family and length. */
char sa_data[14]; /* Address data. */
};
class Address {
public:
//! \brief Wrapper around [sockadd... | This is a user defined conversion function. An object of type Raw can implicitly be converted to a sockaddr pointer. For example the following will compile:
void fun(sockaddr *p); // function that takes a sockaddr pointer
Address::Raw r;
fun(r); // implicit conversion occurs from Raw in order to use function `fun`
|
67,699,542 | 67,707,616 | GDB show current compiled binary file for function address on call stack | In visual studio you can see where the function is located, i.e. within which compiled binary file. For example:
Is there a command for GDB?
Several versions of one symbol can be loaded twice in case you load a dll. And it is essential to know whether the code is being executed within the .exe or one of loaded .dll l... | Disclaimer: this is for GDB on GNU/Linux, working with ELF files. The GDB manual doesn't say that the commands I show here are Linux-specific, but I don't know whether they'll produce similar results on Windows.
GDB's info symbol command, given an address, will output the closest symbol (and offset), filename and secti... |
67,699,655 | 67,700,300 | clarification regarding std::random_shuffle to shuffle the vector | I am begginer at C++ and would like to clarify something. I have a vector of strings and must shuffle it randomly.
I am trying to understand what are the differences between
std::random_shuffle(vector.begin(), vector.end());
int myrandom(int i) {
return std::rand() % i;
}
std::random_shuffle(cards_vector.begin()... | The function std::random_shuffle has two overloads. In short, that means you can call the same function with a different number of parameters.
The version std::random_shuffle(vector.begin(), vector.end()); calls an internal random generator which is defined by the implementation (compiler, operative system, standard l... |
67,700,340 | 67,703,860 | Why sscanf is not handling or ignoring spaces in c++? | I have the following line to be put up in sscanf but its not accepting white spaces
char store_string[25],store_string1[10];
std::tm t={};
int store_integer,store_integer1,store_integer2;
int total_read;
char* buff1 = "Demo to dispay (Appname,App usage) with date (03/11/2005) with test id (87773) data added... |
Why sscanf is not handling or ignoring spaces in c++?
How else should sscanf seperate words/tokens?
From its documentation:
["%s"] matches a sequence of non-whitespace characters (a string)
I don't think you can handle this with sscanf or in a one-liner at all.
You could do this with std::string::find_first_of and ... |
67,700,541 | 67,700,819 | How many maximum depedent types are supported? | This is just my curiosity to understand more about C++ behavior. It's somehow not realistic.
As I know for template it could be declared with a type which depends on another type
For example vector<T> T can be any type and so T can continue depending on something else. So when will it end up with a limit such as an err... | The C++ standard does not set a limit for template recursion depth, but it does recommend a minimum limit of 1024.
Some code (e.g. Boost Spirit, PyBind) can approach this limit with complicated grammars or Python bindings. You could also attain it trivially with some metaprogramming.
With GCC, you can control the recur... |
67,700,713 | 67,703,070 | Why does this template argument deduction fail on GCC but not Clang? | I'm using Clang and GCC trunk with -std=c++20 and the following code compiles fine on Clang but fails on GCC.
#include <cstdint>
#include <climits>
#include <type_traits>
#include <concepts>
#include <immintrin.h>
#define VECTOR_SIZE 32
template <typename T> requires std::is_arithmetic_v<T>
using vec __attribute__((_... | I suspect it to be a GCC bug in the template-argument-deducation resulting from your alias in combination with the vector intrinsics attribute as:
It compiles if you specify the template argument of rotr manually.
A simplified example without concepts in C++17 also compiles on Clang and Intel compiler but yet again fa... |
67,700,967 | 67,702,542 | How to apply gamma correction for cv::mat? | I am new to opencv. There is such a question: I have an image that I get and save this way
Decoder decoder;
decoder.HandleRequest_GetFrame(nullptr, filename, 1, image);
cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
bool isOk = cv::imwrite(save_location, image);
I need to apply gamma correction to the ... | Eventually, I found the way to do it (according to this tutorial https://docs.opencv.org/3.4/d3/dc1/tutorial_basic_linear_transform.html):
//>>>Get Frame
Decoder decoder;
decoder.HandleRequest_GetFrame(nullptr, filename, 1, image);
//<<<
//>>> Collor conversion from BGR to RGB
cv::cvtColor(imag... |
67,701,013 | 67,705,463 | Why do I get "is not a constant expression" error in this case ? (templates) | I am trying to implement some kind of numpy.where() for my ITK images in C++. ITK's way seems to be with Functors. I am not very experienced with templates, so my whole approach might be flawed, but here is my go:
using MASK_IMAGE_TYPE = itk::Image<unsigned short, 3>;
template<class T, T value, T if_equal, T if_n_equa... | You have needlessly many template parameters. You could follow the way it is done in a corresponding test. Define your function, set it via filter->SetFunctor() and call Update().
|
67,701,579 | 67,704,101 | ‘binary_semaphore’ has not been declared in ‘std’ | I want to use c++20 features more exactly std::binary_semaphore. I have installed g++-10 but it does not recognize binary_semaphore as an std type. I typed the following command g++ -std=c++2a main.cpp -o main.
The error message is:
error: ‘binary_semaphore’ has not been declared in ‘std’
6 | using std::binary_semaph... | According to cppreference's compiler support sheet, things such as Atomic waiting and notifying, std::counting_semaphore, std::latch and std::barrier are supported from GCC 11 onwards. You claim to have GCC 10 installed, which does not support aforementioned features.
|
67,701,612 | 67,702,145 | error C2660: 'std::allocator<char>::allocate': function does not take 2 arguments | Code:
#include <string>
#include <boost/format.hpp>
int main() {
boost::format fmt;
auto str = fmt % L"";
}
Errors:
1>D:.conan\a9fe50\1\include\boost\format\alt_sstream_impl.hpp(261,1):
error C2660: 'std::allocator::allocate': function does not take
2 arguments 1>C:\Program Files (x86)\Microsoft Visual
Stud... | The library lacks c++20 support (see https://en.cppreference.com/w/cpp/memory/allocator/allocate)
You can, for now, opt for c++17 compilation. Also, see whether they know about this issue, and if not report it to the developers.
Side Notes
I take it the sample is reduced, but it seems to me the literal ought to be nar... |
67,703,272 | 67,703,589 | SQL - How to find the correct parent id by knowing the children' conditions? | How to find the correct BundleId if the input is:
struct Cart {
int ProductId;
int Quantity;
};
// the input is 3 grapes and 4 oranges
std::vector<Cart> input = {
{3, 3},
{2, 4},
};
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_... | SELECT BundleId
FROM BundleProduct
WHERE (ProductId, Quantity) IN ((3, 3), (2, 4)) -- source criteria pairs
GROUP BY BundleId
HAVING COUNT(*) = 2 -- the amount of pairs
|
67,703,646 | 67,703,737 | C++ why can't classes with const reference member variables be created using constexpr? | In the following code, I try to store a const reference to another class:
struct A {
};
struct B {
constexpr B(A const & _a) : a(_a) {}
A const & a;
};
int main() {
constexpr A s1;
constexpr B s2{s1};
}
however, the compiler (gcc 11.1) complains with:
cctest.cpp: In function ‘int main()’:
c... | Clang 12.0.0+ gives a descriptive note about the issue:
note: address of non-static constexpr variable 's1' may differ on each invocation of the enclosing function; add 'static' to give it a constant address
So you need to add a static here:
struct A {
};
struct B {
constexpr B(A const & _a) : a(_a) {}
... |
67,703,701 | 67,703,803 | Inserting elements of vector into set, while printing set elements gets compilation issue c++98 | I am inserting vector values into set. After that i am trying to print set values where i get compilation issues. please help me to understand what i am doing wrong.
code:
#include<iostream>
#include<set>
#include<vector>
using namespace std;
int main()
{
set<string> s1;
vector<string> v1;
v1.push_back("Hel... | You use the iterator interface:
for (std::set<std::string>::const_iterator it = s1.begin(), end = s1.end();
it != end; ++it) {
std::cout << *it << '\n';
}
You could also use std::copy:
std::copy(s1.begin(), s1.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
|
67,703,727 | 67,703,950 | C++ class not found when running OMNET++ project | Please someone could help me to fix my issue? I will be very grateful.
I try to implement LEACH PROTOCOL. So I added a simple module named Leach to the INET compound module SensorNode. Now I'm implementing my protocol in C++ by creating the Leach.h and Leach.cc files. My Leach class is well registered with OMNET++ via ... | a) make sure that your new code is inside the src folder. Anything outside of the src folder is NOT compiled and linked.
b) if you are building from the command line, re-run make makefiles after adding any new .cc files
|
67,703,988 | 67,704,320 | Overloading istream>> and ostream<< in a templated class | I want to overload >> and << in a templated class and I'm getting some errors.
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std... | Problem is that you have declared a friendship to something what is not a template!
So compiler tries to find:
std::istream& operator>>(std::istream& is, MatricePatratica<int>& obj)
Which doesn't exists, when in fact it should use:
// note extra template parameter:
std::istream& operator>><int>(std::istream& is, Matri... |
67,704,032 | 67,705,010 | Classes and Constructor | using namespace std;
#include <iostream>
class Person {
public:
int age;
Person(int initialAge);
void amIOld();
void yearPasses();
};
Person::Person(int initialAge)
{
if (initialAge > 0) {
initialAge = age;
}
else if (initialAge < 0) {
cout << "Age is not valid, setting age... | In Your Constructor function of class change
initialAge = age;
to
age = initialAge;
because you have to set value of initialAge to age
|
67,704,135 | 67,704,596 | How can I add Clang toolchain in my CLion IDE? | I have installed LLVM 12.0.0 win-64 in my Win-10 machine.
The following is my CLion 2019.3 configuration window for the compiler toolchain:
I don't see Clang or LLVM option here.
How can I add Clang in my CLion IDE?
P.S. Are MinGW and Clang the same or different toolchains?
| Most common setups are handled in this section: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
On Windows you use MinGW if you want to use Clang.
|
67,704,150 | 67,978,333 | how to validate map items with custom key using gtest? | I've written a custom key for my map
struct custom_key {
string id;
string sector;
bool operator==(const custom_key& other) {
// I'm needed by gtest
return id == other.id && sector == other.sector;
}
};
to that I've added the less then overload
namespace std
{
template<> struct less<custom_key>
{... | First issue I see here is that your operator== has no const qualifier. You need something like this:
bool operator==(const custom_key& other) const {
// I'm needed by gtest
return id == other.id && sector == other.sector;
}
Next one,
I've run it against std::map<custom_key, std::string> my_map = { {"id", "n... |
67,704,168 | 67,704,794 | Which method is better to initialize a vector | Please tell me which method would be better in this case, I want to use std::find later for the vectors.
Vectors will include all times a tiny dataset.
Thank you.
int main()
{
// method1
std::vector<int> v1 = {1,2,3,4,5};
bool cond;
if (cond)
{
// find something in v1
}
else
{... | If the second 'else' block is entered, do you need the values in v1? If not, you can simply re-use the memory capacity in v1 rather than constructing a new vector 'v2' within the scope of a conditional block (you seem to want to discard the contents of v1 anyway)
v1 = {1,2,3}
This line re-uses the memory already alloc... |
67,704,250 | 67,704,478 | Istream input checking | I have function, which recieves coeffecents of polynomial via istream input. Im struggling with implementing this piece of code into it (can't fully understand how istream& works), so i can shield it from incorrect input. :
while (!std::cin.good())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::st... | Expanding my comment to an answer, it's possible to make a function which takes the stream and uses the read-validation loop inside it to get the value.
Then in your operator>> overload you call this function to get each value.
Perhaps something like this:
template<typename T>
bool get_value(std::istream& input, T& va... |
67,704,473 | 67,704,623 | Purpose of rebind in the following container | I am reading some C++ code and specifically trying to understand a customised container.
The container has following the template parameters:
template<typename T, typename Alloc>
class container{ ... };
Where T is the type of data like float or int. The Alloc is the allocator and could be one of the standard librari... | It is not a data member. It is a template member, that allows code (which is probably itself a template) to get a different container type with a similar allocator.
e.g. applying a function to each element to get a new container of the results
template <typename Container, typename Function, typename Result = typename ... |
67,704,579 | 67,704,900 | Why is memcpy not copying the data I give to it? | I'm making a memory manager/allocator in C++. The function "memcpy" doesn't seem to be working as expected. Here's the offending code:
template <class Type>
Data<Type> MemoryManager::alloc(Type* data) {
...
printf("Allocating data of size %i at local address %i, absolute address %i\n", allocSize, allocAddress, ... | The First Argument should be Destination and second should be source
Like This :
void * memcpy ( void * destination, const void * source, size_t num );
A simple example :
char myname[] = "Pierre de Fermat";
/* using memcpy to copy string: */
memcpy ( person.name, myname, sizeof(myname) );
|
67,705,089 | 67,705,631 | Why ranges::unique_copy cannot work with std::ostream_iterator? | In [alg.unique], the signature of ranges::unique_copy is defined as:
template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, class Proj = identity,
indirect_equivalence_relation<projected<I, Proj>> C = ranges::equal_to>
requires indirectly_copyable<I, O> &&
(forward_iterator<I... | This is a bug in both implementations. Both contain the equivalent of
if constexpr (input_iterator<O> && same_as<iter_value_t<I>, iter_value_t<O>>)
In a constraint this is fine because constraint satisfaction is checked incrementally with short-circuiting (and in any event substitution failure just result in the co... |
67,705,562 | 67,707,394 | So I have to rotate an array by one position but withou allocating extra space other than the array. Is this a correct solution? | Here is my solution. Is it correct? Ignore bits/stdc++.h etc. I just want to know if it only uses the space allocated for the vector.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cout << "Size of array?\n";
cin >> n;
int x[n];
for (int i = 0; i < n; i++) {
cout << "Input... | For starters variable length arrays like this
int n;
cout << "Size of array?\n";
cin >> n;
int x[n];
is not a standard C++ feature. Instead you should use the standard container std::vector<int>.
To rotate an array or an object of the type std::vector<int> you can use the standard algorithm std::rotate.
As for your co... |
67,705,621 | 67,705,658 | How to have array size depending on parameter in class using template | I have a graph consisting of Q-tuples, where Q is either 3 or 6. The nodes in the graph are modeled as
typedef std::array<int,3> NODE or typedef std::array<int,6> NODE respectively. To be more flexible I used a template class
template <int Q>
class DARP
{
// some attributes
int capacity = Q;
typedef std::array<... | You can use Constexpr If (since C++17) with template parameter Q as:
if constexpr (Q==3)
depot = {0,0,0};
else
depot = {0,0,0,0,0,0};
According to the condition value, the statement-true or statement-false will be discarded and then won't cause the error.
Before C++17, you can specify create_nodes as:
templa... |
67,706,215 | 67,707,061 | How to copy void pointer (C++) to byte[] (C#) (CLI) | I have a byte[] in my C# code and I need to pass it to the C++ side and fill it with a data from void*
I do it this way
C# side
byte[] copy;
m_Logic.CopyToArray(out copy);
//There is filled `copy` that I can use
C++ (CLI) side
void Agent_CLI::CopyToArray([Out] array<unsigned char> ^% input)
{
std::vec... | Reading the articles about pin_ptr it seem like &input[0] will produce a interior_ptr, i.e. a pointer to the data of a managed object. This is supported by the error message you are getting.
This seem to be convertible to a pin_ptr that pins the object, preventing it from being moved by the garbage collector, and this ... |
67,706,271 | 67,706,459 | I'm trying to call the selected class in the class method | So, I am working on a school project and it's all going well except I have to call a function that requires a class as an argument. I need the function in a class method and I was wondering how do you fill in the argument? I will leave a sample code below
#include <iostream>
using namespace std;
class x
{
public:
... | Do you have successfully compile? Your member of class was named as class - X.
|
67,706,500 | 67,706,813 | How is overloaded operator| implemented specifically c++ range adaptors? | Since ranges were merged into C++ 20, I've been looking through headers to see how operator| is overloaded for range views, but I can't find the right track on how or where it is implemented.
C(R) is equivalent to R | C according to https://en.cppreference.com/w/cpp/ranges, based on what I've read.
Or, V(R, F) is equi... | This is the basic structure:
template<std::ranges::viewable_range Range, other_concepts... OtherArgs>
new_range_t my_view(Range range, OtherArgs... args);
template<other_concepts... OtherArgs>
/* some type */ my_view(OtherArgs... args);
template<std::ranges::viewable_range Range, other_concepts... OtherArgs>
new_rang... |
67,706,577 | 67,706,643 | What is the name for comments with '@' in them? | This is a case of not being able to look something up because I don't know the name for it. In many code editors you can include these in the preceding comment block of a definition and then get helpful mouse-over text elsewhere, or other programs can read these comments and do something useful with them. I'm working o... | I think what you're looking for is Doxygen markdown
https://www.doxygen.nl/manual/markdown.html
|
67,707,083 | 67,707,276 | How to covert int to double in c++ | I want to convert 3 to 3.00. I have done explicit type conversion. but guess it doesn't seem to work!whats wrong?
my code:
#include<iostream>
using namespace std;
int main(){
int PI = 3;
double a = static_cast<double>(PI);
cout<<a;
}
output: 3
| This may help.
#include<iostream>
using namespace std;
int main(){
int PI = 3;
double a = static_cast<double>(PI);
cout.precision(2);
cout << std::fixed << a;
}
|
67,707,205 | 67,707,306 | Qt Framework Saving inputs To Text File | I was trying to make a little program with Qt Framework C++ .
I made a simple Gui which contains 5 text inputs .
How can I save these inputs into a *.txt file with this schema :
Name : <firstInput>
Lastname : <secondInput>
Age : <ThirdInput>
Nationality : <forthInput>
Address : <fifthInput>
I still didn't do anything ... | Here's an example:
QFile data("output.txt");
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << ui->lineEdit->text();
}
This tries to save contents of one of the LineEdits into a file named "output.txt". You would put this code into some on-button-clicked slot.
See:
QFile
QTex... |
67,707,313 | 67,707,610 | How to do update-alternatives --config without having an interactive prompt? | So I'm trying to run these commands in the Github Actions environment:
sudo update-alternatives --config x86_64-w64-mingw32-gcc
sudo update-alternatives --config x86_64-w64-mingw32-g++
to change the threading model to POSIX, but it brings up the following prompt:
There are 2 choices for the alternative x86_64-w64-mingw... | If you can change value of compiler priorities, you can simply change 30 to 90(or any other value that is bigger than 60), so /usr/bin/x86_64-w64-mingw32-gcc-posix will became your auto compiler.
If this aproach is sutable for you, do something like this
sudo update-alternatives --install /usr/bin/x86_64-w64-mingw32-gc... |
67,708,412 | 67,708,529 | C++ and QT Complicated CSV parsing | I have a .csv file with some more or less complicated contents.
The main problem is description column which contains a long string of text with empty lines, , and " symbols inside. For example:
"NO SAFE PLACE LEFT At great cost to the Garrison and the Survey Corps, Commander Erwin ..."
I tried using default C++ and Q... | This is actively updated: https://github.com/d99kris/rapidcsv
I haven't used it, but a simple search of "csv parsing c++" shows a number of libraries. There might be others that are also actively updated.
|
67,708,708 | 67,709,003 | Period count function | I'm new to the chrono library and I'm trying to use it to write a function that returns how many 5 min periods there are between two times. Please note: The 1min source and 5min result period could be different so the solution needs to be flexible (e.g. 5min source, 15min result period is one possible combination).
For... | five_mins should be a type, not a variable.
Also, std::ratio<1, 5*60> makes for 1 three-hundredths of a second, not 5 minutes.
using five_mins = duration<int64_t, std::ratio<5*60>>;
Furthermore, since there is potential truncation happening and the time is not in floating point, you cannot use the five_mins constructo... |
67,708,723 | 67,725,216 | Cross-platform file names and wxString::ToStdString() | I want to handle files in a cross-platform application using wxWidgets 3.1. I rely on some functions that only accept the file name as an std::string.
On Windows, I can simply use wxString::ToStdString() and everything is fine.
On Linux (Ubuntu 20.04 LTS), the conversion fails and returns an empty string when there are... | Apparently the function wxString::ToStdString() uses the encoding of the current locale of the program.
The default locale of the program is not the locale set in the user environment. All C and C++ programs start in a locale named "C". In order to use the locale specified in the user environment, one needs to call
set... |
67,709,041 | 67,709,194 | Find position of a number in array closest to given number | I am searching for an elegant way to find the closest element in an array to a given value.
Here is a working implementation:
std::vector<double> array = { /* numbers */ };
double num = /* given number */;
double min_diff = std::abs(array[0] - num);
size_t best_pos = 0;
for (size_t i = 1; i < array.size(); i++) {
d... | To find the element that minimizes some function you can use std::min_element. Note that this isn't the most efficient, as it evaluates the function to be minimized for every comparison. When the function to be minimized is more costly, you'd maybe rather populate a container of the functions results and then find the ... |
67,709,794 | 67,710,159 | std::unordered_map find() operation not working in GCC7 | I am working on porting my c++ application from GCC4.7 to GCC7 and ran into an issue where std::hash_map find() function returns null result for keys which are present in map.
Existing code:
struct eqfunc {
bool operator()(const char* const &s1, const char* const &s2) const {
std::cout << "eqfunc in action " << s... | You've discovered that std::hash<const char*> hashes the actual pointer - not the C string it points at. Sometimes "def" and the second "def" will actually have the same pointer value. It depends on how the compiler optimized it.
To use C strings, you need to provide a hash functor for C strings. Here's one example:
#i... |
67,709,887 | 67,710,455 | error: reduction variable is private in outer context (omp reduction) | I am confused about the data sharing scope of the variable acc in the flowing two cases. In the case 1 I get following compilation error: error: reduction variable ‘acc’ is private in outer context, whereas the case 2 compiles without any issues.
According to this article variables defined outside parallel region are s... | Your case 1 is violating OpenMP semantics, as there's an implicit parallel region (see OpenMP Language Terminology, "sequential part") that contains the definition of acc. Thus, acc is indeed private to that implicit parallel region. This is what the compiler complains about.
Your case 2 is different in that the simd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.