std::initializer_list
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
| Заголовочный файл <initializer_list>
|
||
| template< class T > class initializer_list; |
(начиная с C++11) | |
объект типа
std::initializer_list<T> это легкий объект прокси-сервер, который обеспечивает доступ к массиву объектов типа T, выделенных реализации в неопределенных хранения (который может быть автоматическим, временные, или статический только для чтения памяти, в зависимости от ситуации )Original:
An object of type
std::initializer_list<T> is a lightweight proxy object, which provides access to an array of objects of type T, allocated by the implementation in unspecified storage (which could be automatic, temporary, or static read-only memory, depending on the situation)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Этот массив инициализируется и
std::initializer_list объект построен, когда приготовился-Init-лист используется в Список инициализации, в том числе вызова функции инициализации списка и выражения присваивания (не путать с инициализации конструктора списка), или когда приготовился-Init-лист связан с auto, в том числе в дальнюю цикла.Original:
This array is initialized and a
std::initializer_list object is constructed when a braced-init-list is used in Список инициализации, including function-call list initialization and assignment expression (not to be confused with инициализации конструктора списка), or when braced-init-list is bound to auto, including in a ranged for loop.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Initializer список может быть реализован как пара указателей или указателя и длины. Копирование
std::initializer_list не копирует основные объекты. основной массив не гарантирует существование после жизни оригинального объекта списке инициализаторов закончилось.Original:
Initializer list may be implemented as a pair of pointers or pointer and length. Copying a
std::initializer_list does not copy the underlying objects. The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Член типов
| Член типа
Original: Member type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
Definition |
value_type
|
T |
reference
|
const T& |
const_reference
|
const T& |
size_type
|
size_t |
iterator
|
const T* |
const_iterator
|
const T* |
[править] Член функций
| создает пустой список инициализации Original: creates an empty initializer list The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член) | |
Original: Capacity The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | |
| возвращает количество элементов в списке инициализаторов Original: returns the number of elements in the initializer list The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член) | |
Original: Iterators The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | |
| возвращает указатель на первый элемент Original: returns a pointer the first element The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член) | |
| возвращает указатель на следующий за последним элементом Original: returns a pointer to one past the last element The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (public функция-член) | |
[править] Не являющиеся членами функций
| Специализируется std::begin Original: specializes std::begin The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (шаблон функции) | |
| Специализируется std::end Original: specializes std::end The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (шаблон функции) | |
[править] Пример
#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"; } void append(std::initializer_list<T> l) { v.insert(v.end(), l.begin(), l.end()); } std::pair<const int*, size_t> c_arr() const { return {&v[0], v.size()}; // list-initialization in return statement } }; template<typename T> void templated_fn(T) { } int main() { S<int> s = {1,2,3,4,5}; // direct list-initialization s.append({6,7,8}); // list-initialization in function call std::cout << "The vector size is now " << s.c_arr().second << " ints:\n"; for(auto n : s.v) std::cout << ' ' << n; std::cout << '\n'; std::cout << "range-for over brace-init-list: \n"; for(int x : {-1, -2, -3}) // the rule for auto makes this ranged for work std::cout << x << ' '; std::cout << '\n'; auto al = {10, 11, 12}; // special rule for auto std::cout << "The list bound to auto has size() = " << al.size() << '\n'; // templated_fn({1,2,3}); // compiler error! "{1,2,3}" is not an expression, // it has no type, and so T cannot be deduced templated_fn<std::initializer_list<int>>({1,2,3}); // OK templated_fn<std::vector<int>>({1,2,3}); // also OK }
Вывод:
The vector size is now 8 ints: 1 2 3 4 5 6 7 8 range-for over brace-init-list: -1 -2 -3 The list bound to auto has size() = 3