We can use the following syntax to initialize a vector.
// assume that UserType has a default constructor
vector<UserType> vecCollections;
Now, if UserType doesn't provide a default constructor for UserType but only a constructor as follows:
explicit UserType::UserType(int i) { ... }.
How should I call this explicit element initializer with the vector constructor?
vector<UserType> vecCollections(10, UserType(2));
Unfortunately there is no way in current C++ (C++03) to initialize the vector with arbitrary elemtnts. You can initialize it with one and the same element as in @Erik's answer.
However in C++0x you can do it. It is called an initializer_list
vector<UserType> vecCollections({UserType(1), UserType(5), UserType(10)});
Incidentally, you might want to check out the boost::assign library, which is a very syntactically convenient way to assign to a vector and other containers
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