adding multiple elements to c++ vector at once [du

2019-02-25 05:21发布

问题:

This question already has an answer here:

  • How do I pass multiple ints into a vector at once? 5 answers

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!

回答1:

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


标签: c++ vector