C++11对原有的初始化列表(用花括号围住的若干个值)进行了大幅的扩展。以下写法在C++11中都是被允许的:
1 int static_arr[5] = {1, 2, 3, 4}; // static_arr[4] is not initialized here 2 int static_arr2[] {1, 2, 3, 4}; // operator = can be omitted 3 4 int* dynamic_arr = new int[5] {1, 2, 3, 4}; 5 // dynamic_arr[4] is not initialized here 6 7 vector<int> stl_vec {1, 2, 3, 4}; 8 set<int> stl_set {1, 2, 3, 3}; 9 cout << stl_set.size() << endl; // 3 10 11 map<const char*, int> stl_map { 12 {"Alice", 1}, 13 {"Bob", 2}, 14 {"Cindy", 3} 15 };
C++11将初始化列表解释成一个initializer_list<T>类型的变量(T是列表中元素的类型)。它相当于一个只读的容器,只有三个成员函数:size(),begin()和end()。
在上面这个例子中,我们用初始化列表为STL容器提供初值。C++11为STL容器新增了一种构造函数,它可以接收一个initializer_list。
initializer_list也可以像其他类型的变量一样,在语句中被创建,或者用作函数(包括类的构造函数)的参数:
1 #include <initializer_list> // This header is required 2 #include <iostream> 3 4 using namespace std; 5 6 template <class Tp> 7 void print_ilist(const initializer_list<Tp> &ilist) 8 { 9 for (auto it = ilist.begin(); it != ilist.end(); ++it) 10 cout << *it << endl; 11 } 12 13 struct Foo 14 { 15 int vals[10]; 16 int n = 0; 17 18 Foo (const initializer_list<int> &ilist) { 19 for (int v: ilist) 20 vals[n++] = v; 21 } 22 }; 23 24 int main() 25 { 26 initializer_list<int> empty_ilist; 27 empty_ilist = {1, 2, 3, 4}; 28 cout << empty_ilist.size() << endl; // 4 29 30 Foo foo {1, 2, 3}; 31 Foo bar (empty_ilist); 32 cout << "bar.n = " << bar.n << endl; // 4 33 34 initializer_list<float> float_ilist {1.0, 1.2, 1.5, 2.0}; 35 print_ilist(float_ilist); 36 print_ilist( {"Reimu", "Marisa", "Sanae", "Reisen"} ); 37 return 0; 38 }
时间: 2024-11-06 13:54:24