C++ Library -



The 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 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 Header

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

#include 

Functions of Header

Below is list of all functions from header.

Sr.No. Functions & Description
1 size

It returns the number of elements in the initializer_list.

2 begin

It returns a pointer to the first element.

3 end

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 
#include 
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 
#include 
#include 
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