XCS
XCS

Reputation: 28157

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

How can I push_back a struct into a vector?

struct point {
    int x;
    int y;
};

std::vector<point> a;

a.push_back( ??? );

Upvotes: 51

Views: 108918

Answers (5)

Healer-kid
Healer-kid

Reputation: 11

We should use emplace_back() for user defined data types such as structs.We can use it even with primitive data types as well.

Upvotes: 0

Rewd0n
Rewd0n

Reputation: 111

struct point {
    int x;
    int y;
};

vector <point> a;

a.push_back( {6,7} );
a.push_back( {5,8} );

Use the curly bracket.

Upvotes: 11

Steve Jessop
Steve Jessop

Reputation: 279315

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));

Upvotes: 55

PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

point foo; //initialize with whatever
a.push_back(foo);

Upvotes: 1

Wim
Wim

Reputation: 11252

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.

Upvotes: 15

Related Questions