vector of class without default constructor

How can I create a std::vector of type A and give an argument to A's constructor?

std::vector<A> v1(10, 42);  // 10 elements each with value 42
std::vector<A> v2{1,2,3,4}; // 4 elements with different values

How would I add 3 to the vector?

v.emplace_back(3);          // works with any suitable constructor
v.push_back(3);             // requires a non-explicit constructor

The lack of a default constructor only means you can't do operations that need one, like

vector<A> v(10);
v.resize(20);

both of which insert default-constructed elements into the vector.


The trick is in how you add elements into the vector and what member functions of the vector you use.

std::vector<A> v;
v.emplace_back(3);

Templates are not instantiated in one go : they only instantiate what is needed. A satisfies all the conditions for the following (constructing an empty vector) to be valid :

std::vector<A> v;

However, as A does not have a default constructor, the following (creating a vector with default-initialized content) would fail :

std::vector<A> v(100);

And that's a good thing. However, valid methods will be instantiated fine :

v.emplace_back(42);

Tags:

C++

C++11

Vector