在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
看到这么一个东西,可以实现花括号( "{" "}" )初始化容器类。 使用时需包含头文件 #include <initialize_list>
我们都看过这样的代码 vector<int> arr = { 1,2,3,4,5 }; 或者 vector<int> arr{ 1,2,3,4,5 }; 右边那个花括号返回的类型便是initialize_list
我们可以在自己的类中这么用 class foo { public: std::vector<int> data; //构造函数里放上initialize_list foo() {} foo(std::initializer_list<int> list) :data(list) {} void print() { for (auto item : data) { std::cout << item; } std::cout << endl; } }; 试验一下 int main() { foo test1{ 1,2,3,4,5 }; foo test2 = { 1,2,3,4,5 }; test1.print(); test2.print(); return 0; } 可以正常输出
cppreference 的测试代码如下:可以看到这个东西的花样还是挺多的 1 #include <iostream> 2 #include <vector> 3 #include <initializer_list> 4 5 template <class T> 6 struct S { 7 std::vector<T> v; 8 S(std::initializer_list<T> l) : v(l) { 9 std::cout << "constructed with a " << l.size() << "-element list\n"; 10 } 11 void append(std::initializer_list<T> l) { 12 v.insert(v.end(), l.begin(), l.end()); 13 } 14 std::pair<const T*, std::size_t> c_arr() const { 15 return{ &v[0], v.size() }; // copy list-initialization in return statement 16 // this is NOT a use of std::initializer_list 17 } 18 }; 19 20 template <typename T> 21 void templated_fn(T) {} 22 23 int main() 24 { 25 S<int> s = { 1, 2, 3, 4, 5 }; // copy list-initialization 26 s.append({ 6, 7, 8 }); // list-initialization in function call 27 28 std::cout << "The vector size is now " << s.c_arr().second << " ints:\n"; 29 30 for (auto n : s.v) 31 std::cout << n << ' '; 32 std::cout << '\n'; 33 34 std::cout << "Range-for over brace-init-list: \n"; 35 36 for (int x : {-1, -2, -3}) // the rule for auto makes this ranged-for work 37 std::cout << x << ' '; 38 std::cout << '\n'; 39 40 auto al = { 10, 11, 12 }; // special rule for auto 41 42 std::cout << "The list bound to auto has size() = " << al.size() << '\n'; 43 44 //templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression, 45 // it has no type, and so T cannot be deduced 46 templated_fn<std::initializer_list<int>>({ 1, 2, 3 }); // OK 47 templated_fn<std::vector<int>>({ 1, 2, 3 }); // also OK 48 }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论