4

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?

1
  • +1 for the question, as it made me to write a initializer, which I eventually liked :D Commented Mar 13, 2011 at 19:00

3 Answers 3

12
vector<UserType> vecCollections(10, UserType(2)); 
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

Even in C++03, you can initialize vector with arbitrary types! See my solution!
@Nawaz: I believe that's boost assign's solution :)
4
std::vector<char> items(10, 'A'); //initialize all 10 elements with 'A' 

However, if you want to initialize the vector with different values, then you can write a generic vector initializer class template, and use it everywhere:

template<typename T> struct initializer { std::vector<T> items; initializer(const T & item) { items.push_back(item); } initializer& operator()(const T & item) { items.push_back(item); return *this; } operator std::vector<T>&() { return items ; } }; int main() { std::vector<int> items(initializer<int>(1)(2)(3)(4)(5)); for (size_t i = 0 ; i < items.size() ; i++ ) std::cout << items[i] << std::endl; return 0; } 

Output:

1 2 3 4 5 

Demo at ideone: http://ideone.com/9dODD

3 Comments

+1 I believe this is what boost::assign::list_of does too.
why not overload the command-operator it would look much nicer.
just a smarter way to use operator(). This is real fancy:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.