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!
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With