Learning New C++ Standards - Initializer lists

| | 1 min read

If you have a vector and you need to fill it with some predefined data, we have to call push_back() with those data that many times. Its so tiring like the following.


    vecData.push_back(1);
    vecData.push_back(2);
    vecData.push_back(3);
    vecData.push_back(4);

New C++ standards solved this issue by std::initializer_list<>. Using this proxy object, standard containers can be initialized with initial values.

Eg:-

    vector<int> vecData = {1,2,3,4};

or

    vector<int> vecData{1,2,3,4};

If you want your own class provide this functionality to its users then you have to implement a constructor which takes std::initializer_list<T> as parameter. Use that to populate internal data structure.


    class ObjList
    {
      public:
	    ObjList(std::initializer_list<Obj> lst);
    };

This object can be used like follows.

    ObjList o1 = {1, 2, 4, 5};

This type of constructor is called initializer list constructor. Elements in std::initializer_list are read only. we cannot change that in the constructor.

We can use std::initializer_list in other places like other data types.