46

How can I push_back a struct into a vector?

struct point {
    int x;
    int y;
};

std::vector<point> a;

a.push_back( ??? );
Micha Wiedenmann
  • 18,825
  • 20
  • 87
  • 132
XCS
  • 25,775
  • 24
  • 93
  • 146

5 Answers5

52
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));
fredoverflow
  • 246,999
  • 92
  • 370
  • 646
Steve Jessop
  • 265,622
  • 35
  • 449
  • 690
  • 3
    how does make_point function work, will the local var mypoint be not out of scope after the return? –  Mar 27 '16 at 07:58
  • 1
    Would'nt `emplace_back` be better? – ThePunisher Apr 10 '18 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 :-) – Steve Jessop Apr 13 '18 at 11:32
  • 1
    If you have a constructor you should probably use `emplace_back()` instead of `push_back()`. – Micha Wiedenmann May 15 '18 at 12:55
13
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.

Wim
  • 10,833
  • 38
  • 56
10
struct point {
    int x;
    int y;
};

vector <point> a;

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

Use the curly bracket.

Rewd0n
  • 101
  • 1
  • 2
  • This is nice, but how does emplace_back() compares to this, is it better in some way? – bbv Apr 10 '19 at 07: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 Mar 03 '20 at 06:36
  • This didn't work on my compiler (Apple LLVM) – BjornW May 08 '21 at 15:30
1
point foo; //initialize with whatever
a.push_back(foo);
The Communist Duck
  • 5,881
  • 3
  • 34
  • 49
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.