std::initializer_list

From Cppreference

Jump to: navigation, search
Defined in header <initializer_list>

template< class T >
class initializer_list;
(since C++11)

An object of type std::initializer_list<T> is passed, by value, to the constructors of objects when they are initialized using initializer list syntax. It is a thin wrapper around an array of objects of type T, 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

constructs the initializer list
(public member function)
Capacity
returns the size of the initializer list
(public member function)
Iterators
returns a pointer to the first element
(public member function)
returns a pointer one past the last element
(public member function)

[edit] Non-member functions

specializes std::begin
(function template)
specializes std::end
(function template)

[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