std::initializer_list in C++ 11
Last Updated :
15 Jan, 2024
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;
}
OutputNumbers 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;
}
OutputElements 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:
|
begin()
| Returns a pointer to the first element of the initializer list.
|
end()
| Returns a pointer to the last element of the initializer list.
|
size()
| The size() function returns the number of elements present in the initializer list.
|
empty()
|
This function returns true if the initializer list is empty. False otherwise.
|
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;
}
OutputSize 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;
}
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;
}
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;
}
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.
Similar Reads
When do we use Initializer List in C++?
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class. Example [GFGTABS] C++
8 min read
Order of execution in initializer list in C++
Prerequisite: Classes, Constructors, Initializer list In this article, we will discuss the order of execution in the initializer list in C++. Generally, the order of execution is from top to bottom and left to right. But a rare condition arises where this rule fails is when the initializer list is u
2 min read
Different Ways to Initialize a List in C++ STL
Initializing a list means assigning some initial values to the list elements. In this article, we will learn different methods to initialize the list in C++. Letâs start from the easiest method: The easiest way to initialize a list is by passing the initial values inside an initializer list to its c
3 min read
std::integer_sequence in C++ 14
When programming, loops, and iteration are often required by developers. Occasionally, looping through a range of numbers whose span is unknown becomes necessary std::integer sequence is useful in that scenario. By using std::integer_sequence provided by C++14, one can create a sequence of integers
3 min read
std::move_iterator in C++ 11
std::move_iterator was introduced in C++11, with the ability to convert regular iterators into move iterators. Instead of copying, the std::move_iterator allows the STL to move the objects it manipulates. The move iterator wraps the other iterator. This is particularly helpful while working with hug
3 min read
Zero Initialization in C++
Setting the initial value of an object to zero is called zero initialization. Syntax: static T object; Tt = {} ; T {} ; char array [n] = " "; Zero initialization is performed in the following situations:- Zero is initialized for every named variable with static or thread-local storage duration that
3 min read
std::inserter in C++
std::inserter constructs an insert iterator that inserts new elements into x in successive locations starting at the position pointed by it. It is defined inside the header file . An insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (su
4 min read
Designated Initializers in C++ 20
With C++20, we get a convenient way of initializing data members. The new feature is called Designated Initializers and it might be familiar to C programmers. In other words, Designated Initializers are a new feature that has been introduced in C++20. It allows developers or programmers to initiate
5 min read
Different methods to initialize a Linked List
Like arrays, a Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. They include a series of connected nodes. Here, each node stores the data and the address of the next node. There are two method
15+ min read
std::back_inserter in C++
std::back_inserter constructs a back-insert iterator that inserts new elements at the end of the container to which it is applied. It is defined inside the header file . A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as
4 min read