C++ Library - <initializer_list>



The <initializer_list> in C++ provides a convenient way to initialize containers and user-defined types with a list of values. It allows for more flexible and readable code by enabling the initialization of collections with a comma separated list of elements.

The <initializer_list> is a lightweight proxy object that allows a constructor to accept a list of values without explicitly specifying the type. It is used when working with standard library containers such as vector, set and map.

Including <initializer_list> Header

To include the <initializer_list> header in your C++ program, you can use the following syntax.

 #include <initializer_list> 

Functions of <initializer_list> Header

Below is list of all functions from <initializer_list> header.

Sr.No.Functions & Description
1size

It returns the number of elements in the initializer_list.

2begin

It returns a pointer to the first element.

3end

It return a pointer to one past the last element.

Adding Values from an Initializer List

In the following example, we are going to calculate the sum of the elements from the initializer_list.

 #include <iostream> #include <initializer_list> int a(std::initializer_list < int > list) { int b = 0; for (auto x: list) { b += x; } return b; } int main() { int y = a({2,4,6,10}); std::cout << "Result : " << y << std::endl; return 0; } 

Output

Output of the above code is as follows −

 Result : 22 

Combining Two Initializer Lists

Consider the following example, where we are going ti combine values from multiple initializer lists.

 #include <iostream> #include <initializer_list> #include <vector> std::vector < int > a(std::initializer_list < int > x, std::initializer_list < int > y) { std::vector < int > b; b.insert(b.end(), x); b.insert(b.end(), y); return b; } int main() { auto b = a({1,3,5}, {2,4,6}); for (auto value: b) { std::cout << value << " "; } std::cout << std::endl; return 0; } 

Output

Following is the output of the above code −

 1 3 5 2 4 6 
Advertisements
close