How can I push_back
a struct
into a vector?
struct point { int x; int y; }; std::vector<point> a; a.push_back( ??? );
The vector is fine. Be aware that if you copy this struct, then the vector will be copied with it. So in code with particular performance constraints, treat this struct the same way that you'd treat any other expensive-to-copy type.
To create a vector of structs, define the struct, with a generalized (class) name. Make the template argument of the vector of interest, the generalized name of the struct. Access each cell of the two dimensional structure with the syntax, vtr[i]. columnName.
push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
point mypoint = {0, 1}; a.push_back(mypoint);
Or if you're allowed, give point
a constructor, so that you can use a temporary:
a.push_back(point(0,1));
Some people will object if you put a constructor in a class declared with struct
, and it makes it non-POD, and maybe you aren't in control of the definition of point
. So this option might not be available to you. However, you can write a function which provides the same convenience:
point make_point(int x, int y) { point mypoint = {x, y}; return mypoint; } a.push_back(make_point(0, 1));
point p; p.x = 1; p.y = 2; a.push_back(p);
Note that, since a
is a vector of points (not pointers to them), the push_back will create a copy of your point struct -- so p
can safely be destroyed once it goes out of scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With