51

How can I push_back a struct into a vector?

struct point {
    int x;
    int y;
};

std::vector<point> a;

a.push_back( ??? );
0

5 Answers 5

54
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));
4
  • 3
    how does make_point function work, will the local var mypoint be not out of scope after the return?
    – user1065101
    Commented Mar 27, 2016 at 7:58
  • 1
    Would'nt emplace_back be better? Commented Apr 10, 2018 at 20:24
  • 3
    @ThePunisher: definitely, but the question was asked 7 years ago about push_back, so I wasn't going to give a non-standard answer that the questioner's implementation may or may not have implemented yet :-) Commented Apr 13, 2018 at 11:32
  • 1
    If you have a constructor you should probably use emplace_back() instead of push_back(). Commented May 15, 2018 at 12:55
15
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.

11
struct point {
    int x;
    int y;
};

vector <point> a;

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

Use the curly bracket.

3
  • This is nice, but how does emplace_back() compares to this, is it better in some way?
    – bbv
    Commented Apr 10, 2019 at 7:04
  • @bbv You need a constructor for emplace_back(). Doing it like Rewd0n should however invoke the move variant of push_back, so the end result is pretty much the same.
    – marcbf
    Commented Mar 3, 2020 at 6:36
  • This didn't work on my compiler (Apple LLVM)
    – BjornW
    Commented May 8, 2021 at 15:30
1
point foo; //initialize with whatever
a.push_back(foo);
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.