std::initializer_list
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <initializer_list> 中定义
|
||
template< class T > class initializer_list; |
(C++11 起) | |
std::initializer_list<T>
类型的对象是一个轻量级的代理对象,它提供了访问的实施在未指定的存储(可以是自动的,暂时的或静态的只读存储器,视情况而定,分配到一个数组中的对象类型T
)原文:
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)该数组初始化一个
std::initializer_list
对象被构造时,使用一个“支撑初始化列表”列表初始化,包括函数调用列表的初始化和赋值表达式(不要混淆构造函数初始化列表),或当“支撑初始化列表”,势必auto,包括中一个环..不等原文:
初始值设定项列表可能会被实现为一个对指针或指针和长度。复制
std::initializer_list
不会复制的基础对象。不保证底层数组后原来的初始化列表中对象的生命周期已经结束原文:
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.目录 |
[编辑] 会员类型
会员类型
|
Definition |
value_type
|
T |
reference
|
const T& |
const_reference
|
const T& |
size_type
|
size_t |
iterator
|
const T* |
const_iterator
|
const T* |
[编辑] 成员函数
创建一个空的初始值设定项列表 (公共成员函数) | |
| |
返回在初始化列表中的元素个数 原文: returns the number of elements in the initializer list (公共成员函数) | |
| |
返回的第一个元素的指针 (公共成员函数) | |
返回一个指针,指向一个过去的最后一个元素 原文: returns a pointer to one past the last element (公共成员函数) |
[编辑] 非成员函数
专业std::begin (函数模板) | |
模板特化 std::end (函数模板) |
[编辑] 示例
#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