Open In App

std::initializer_list in C++ 11

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

std::initializer_list in C++

In C++, the std::initializer_list is a class template that allows us to initialize a lightweight object with a list of values. An initializer list is used to set values to variables, arrays, classes, functions, constructors of classes, and standard containers like vectors in a convenient way.

Syntax

initializer_list<T> name_of_list= { };
  • Braced Initializer is used to construct the object for initializer_list.
  • It is generally implemented as a wrapper over arrays.
  • Unlike standard containers like vectors, copying the object of the initializer list does not copy the entire elements to the copied list. But both the original and copied object of the initializer list contain the same elements.

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;
}


Output

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;
}


Output

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 

Member Functions of std::initializer_list

The following are some of the commonly used member functions of the std::initialzer_list class:

S. No.

Function Name

Description

1

begin()

Returns a pointer to the first element of the initializer list.

2

end()

Returns a pointer to the last element of the initializer list.

3

size()

The size() function returns the number of elements present in the initializer list.

4

empty()

This function returns true if the initializer list is empty. False otherwise.

5

data()

Returns a pointer to the underlying array container.

Applications of initializer_list

Apart from the construction of objects, initializer list can be used in the following cases:

1. Variable Function Parameters

<initializer_list> are used to pass a variable number of arguments to a function.

Example

The below example demonstrates the passing of an initializer list to a function.

C++




// C++ program to demonstrate the passing of initializer
// list to a function.
  
#include <iostream>
using namespace std;
#include <initializer_list>
  
void myFunction(initializer_list<int> myList)
{
  
    // Print the size (length) of myList
    cout << "Size of myList: " << myList.size();
    cout << "\n";
  
    // Print elements of myList
    cout << "Elements of myList: ";
  
    // iterate to all the values of myList
    for (int value : myList) {
  
        // Print value at each iteration
        cout << value << " ";
    }
}
  
int main()
{
    // Using initializer list when calling a function
    myFunction({ 1, 2, 3, 4, 5 });
  
    return 0;
}


Output

Size of myList: 5
Elements of myList: 1 2 3 4 5 

2. Store Data in Contigious Memory

The elements of the initializer_list container can be used to store data as it is a lightweight container.

Example

The below example demonstrates the use of range-based loops to access elements of initializer_list.

C++




// C++ program to demonstrate the use of range based loops to access elements of initializer_list.
  
#include <iostream>
using namespace std;
#include <initializer_list>
  
int main() {
    initializer_list<int> list = {1, 2, 3, 4, 5};
  
    // Using range-based for loop
    for (int value : list) {
        cout << value << " ";
    }
  
    cout << endl;
    return 0;
}


Output

1 2 3 4 5 

3. Initialize Standard Containers

The initializer_list can be used for initializing the standard containers with a List of Elements like vectors.

Example

The below example demonstrates the use of initializer_list to initialize standard containers.

C++




// C++ program to demonstrate the use of initializer_list to
// initialize standard containers.
  
#include <iostream>
#include <vector>
using namespace std;
#include <initializer_list>
  
void printVector(initializer_list<int> list)
{
  
    //  initialize vector using initializer_list
    vector<int> myVector(list);
  
    // Printing the elements of vector
    for (int value : myVector) {
        cout << value << " ";
    }
    cout << endl;
}
  
int main()
{
  
    // pass initializer_list to function
    printVector({ 1, 2, 3, 4, 5 });
  
    return 0;
}


Output

1 2 3 4 5 

4. Initializer Lists as Return Types

The initializer_list can be used as a return type to return lists from any function. It allows the function to return multiple values.

Example

The below example demonstrates the use of initializer_list as a return type.

C++




// C++ program to demonstratethe use of initializer_list as
// return type.
  
#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;
  
initializer_list<int> getNumbers()
{
    return { 1, 2, 3, 4, 5 };
}
  
int main()
{
    auto num = getNumbers();
    // Use the generated numbers
    for (auto it : num) {
        cout << it << " ";
    }
    return 0;
}


Output

1 2 3 4 5 

Limitations of initializer_list

The initializer lists also have some limitations associated with it:

  • Size cannot be changed: The size of initializer_list is fixed at compile time. It does not have a dynamic nature as a standard container such as a vector. The size of the initializer cannot be changed once it has been created.
  • Cannot access the elements randomly: initializer_list supports only forward iteration. We cannot access the desired or random element using the index as standard containers.
  • Immutable elements: The elements within an initializer_list are immutable. Once the list is created, the values cannot be modified. Any attempt to modify the elements through the iterator or by any other means will result in a compilation error.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads