4

I was wondering if it is possible to push_back multiple elements to c++ vector more easily

For example

I create 5 objects

A a1;
A a2;
A a3;
A a4;
A a5;

Currently, i push all of them back like this

vector<A> list;
list.push_back(a1);
list.push_back(a2);
list.push_back(a3);
list.push_back(a4);
list.push_back(a5);

I was wondering if this can be done more succinctly like vector list(a1, a2, a3, a4, a5)..etc Thanks!

kofhearts
  • 3,607
  • 8
  • 46
  • 79

1 Answers1

6

In C++11 you can use vector's initializer-list constructor:

vector<A> list {a1, a2, a3, a4, a5};

If C++11 isn't available you can use the iterator based constructor if you create a temporary array, but it's not as clean as the C++11 solution:

A tmp_list[] = {a1, a2, a3, a4, a5};
vector<A> list(tmp_list, tmp_list + 5};
Chad
  • 18,706
  • 4
  • 46
  • 63