c++ initialize_list

看到这么一个东西,可以实现花括号( "{" "}" )初始化容器类。

使用时需包含头文件

include

我们都看过这样的代码

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 }

原文链接: https://www.cnblogs.com/makejeffer/p/5400808.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/232029

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午3:16
下一篇 2023年2月13日 下午3:16

相关推荐