Initializer_list

Let us understand the concept of initializer_list with the help of an example:

#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
#define MAX 10
class array
{
public:
array(std::initializer_list<unsigned int> list)
{
index = 0;
for(auto item: list)
{
arr[index++] = item;
}
cout  << "C'tor" << endl;
}

void display()
{
for (unsigned int i = 0; i < index; ++i)
{
cout << arr[i] << endl;
}
}
private:
unsigned int arr[ MAX];
unsigned short index;
};

int main()
{
array arrObj = {0,1,5,7,8};
arrObj.display();
vector <unsigned int> v = {5,8,9,10,20};
cout << "Entries in vector: " << v.size() << endl;
return 0;
}

Output:
0
1
5
7
8
Entries in vector: 5

In order to compile the above code, compile with flag –std=c++11 in g++ compiler.

With the help of initializer_list, we can initialize the array class by passing all the values in the curly brackets.

When compiler see the values in the curly bracket as above, then it creates initializer_list<T> where T is the data type of elements used inside the curly bracket and array class has constructor that accepts initializer_list as its argument so this way code works perfectly fine.

This kind of support is present for STL as well as you can see in the main function as STL supports initializer_list in constructor as shown in the above example in the main function.

In C++98, we have to use push_back function to push the elements in to vector or in any other STL. Now with C++11, we can use this option as well. This way, we can initialize the STL with some default values in one line.

Let us say if we initialized the vector or array with mixed data types like:
vector <unsigned int> v = {5,8,9,10.5,20};

For the above statement, compiler gives warning message like:

narrowing conversion of ‘10.5e + 1’ from double to unsigned int inside { }

Output of above vector will be:
5, 8, 9, 10, 20


Related posts