vector <int> scores = {89, 76, 98, 93}; //C++09

previous 10-Minute Solution demonstrated the new initialization rules of C++09 , which enable you to initialize standard containers (among the rest) in the following manner:

A new constructor type called a sequence constructor makes this syntax possible. The following sections will show how to enable the ={val1,val2,...} initialization syntax by adding a sequence constructor to your homemade classes.



Unlike C++09 Standard Library containers, your homemade container classes don't support the new initializer list syntax.



Adding a sequence constructor to your homemade container classes will allow you to initialize instances of those classes similarly to the new initializers in the C++09 Standard Library containers.

I Want C++09 Containers' Easy Initialization

template <typename T> class MyVector { T* elements; size_t n; public: virtual void reserve(size_t n); //polymorphic T& operator[] (int idx); size_t size() const; //... };

Suppose you designed a polymorphic container class with certain operations that C++09 standard container classes don't support. In all other aspects, however, your homemade container has the same interface as a standard container:

Here's the snag. Unlike with standard C++09 container classes, populating a MyVector object in your homemade container is an arduous task. You first need to default-construct MyVector and then call push_back() or assign(). The following code demonstrates the difference between standard C++09 containers and homemade containers:

//easy initialization of a standard C++09 container std::vector <int> vi={5,6,7,8}; //alas, "initializing" MyVector is tedious and bug prone int arr[]={0,2,4,8}; MyVector <int> vi; vi.assign(arr, arr+4);

Now suppose you want MyVector to support the same convenient initialization syntax that C++09 containers provide. What is the secret ingredient that C++09 containers use to enable such easy initialization? Answer: Sequence constructors.