Namespaces
Variants
Views
Actions

std::initializer_list

From cppreference.com
Defined in header <initializer_list>
template< class T >
class initializer_list;
(since C++11)

An object of type std::initializer_list<T> is a thin wrapper around an array of objects of type T.

A std::initializer_list is passed by value to the constructor of an object when it is initialized using the initializer list syntax.

Initializer lists are typically implemented as a pair of pointers or pointer and length. Copying a std::initializer_list does not copy the underlying objects.

Contents

[edit] Member types

Member type Definition
value_type T
reference const T&
const_reference const T&
size_type size_t
iterator const T*
const_iterator const T*

[edit] Member functions

creates an empty initializer list
(public member function) [edit]
Capacity
returns the number of elements in the initializer list
(public member function) [edit]
Iterators
returns a pointer the first element
(public member function) [edit]
returns a pointer to one past the last element
(public member function) [edit]

[edit] Non-member functions

specializes std::begin
(function template) [edit]
specializes std::end
(function template) [edit]

[edit] Example

#include <iostream>
#include <vector>
#include <initializer_list>
 
template<class T>
struct S {
    std::vector<T> v;
    S(std::initializer_list<T> l) : v(l) {
         std::cout << "constructed with a " << l.size() << "-element list\n";
    }
};
 
int main()
{
    S<int> s = {1,2,3,4,5};
    std::cout << "The vector now holds";
    for(auto n : s.v) std::cout << ' ' << n;
    std::cout << '\n';
}

Output:

constructed with a 5-element list
The vector now holds 1 2 3 4 5