Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use vector::push_back()` with a struct?

Tags:

c++

vector

How can I push_back a struct into a vector?

struct point {     int x;     int y; };  std::vector<point> a;  a.push_back( ??? ); 
like image 255
XCS Avatar asked Mar 13 '11 13:03

XCS


People also ask

Can you put a vector in a struct?

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.

How do you use vector structure?

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.

Can you Push_back a vector?

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.


2 Answers

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)); 
like image 105
Steve Jessop Avatar answered Sep 24 '22 09:09

Steve Jessop


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.

like image 40
Wim Avatar answered Sep 23 '22 09:09

Wim