Examples of std::initializer_list in C++
Example 1:
The below example demonstrates the use of an initializer list in C++.
C++
// C++ program to demonstrate the use of initializer list #include <initializer_list> #include <iostream> using namespace std; int main() { // Initializing an object using initializer_list initializer_list< int > num = { 2, 4, 6, 8, 10, 12 }; // Accessing elements cout << "Numbers in the list are: " ; for ( int it : num) { cout << it << " " ; } return 0; } |
Numbers in the list are: 2 4 6 8 10 12
Note Member initializer list and initializer_list are not the same. Both are different, it should not be confused with each other.
Example 2:
Program to illustrate the use of initializer_list to construct the objects.
C++
// C++ program to illustrate the use of initializer_list in // object construction #include <iostream> using namespace std; #include <initializer_list> // array type container constructed using initializer list template < typename T> class MyContainer { public : // Constructor taking initializer_list as a parameter MyContainer(initializer_list<T> values) : list(values) { } // Function to print all elements void printList() const { for ( const T& value : list) { cout << value << " " ; } cout << endl; } private : initializer_list<T> list; }; // diver code int main() { // Creating an instance of MyContainer with // initializer_list of int type MyContainer< int > intContainer = { 1, 2, 3, 4, 5 }; cout << "Elements of Integer type are: " ; intContainer.printList(); cout << endl; // Creating an instance of MyContainer with // initializer_list of double type cout << "Elements of double type are: " ; MyContainer< double > doubleContainer = { 1.1, 2.2, 3.3, 4.4, 5.5 }; doubleContainer.printList(); cout << endl; return 0; } |
Elements of Integer type are: 1 2 3 4 5 Elements of double type are: 1.1 2.2 3.3 4.4 5.5
std::initializer_list in C++ 11
The std::initializer_list class template was added in C++ 11 and contains many built-in functions to perform various operations with the initializer list. It provides member functions like a size(), begin(), end(), and constructor to construct, iterate, and access elements of the initializer list.
To use initializer_list, you need to include the <initializer_list> header in your C++ program.