zoukankan      html  css  js  c++  java
  • initializer_list

    initializer_list是C++11提供的新类型,定义在<initializer_list>头文件中。

    首先有了initializer_list之后,对于STL的container的初始化就方便多了,比如以前初始化一个vector需要这样:

    int a[] = {0, 1, 2, 3};
    std::vector<int> vec(a, a+sizeof(a));

    或者:

    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(3);
    vec.push_back(3);
    vec.push_back(2);
    View Code

    首先看看initializer_list 的作用,可以用大括号来初始化STL的容器,以及可以在for循环中来使用。

     1 #include <iostream>
     2 #include <vector>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     vector<string> v{"ab","cd"};
     8     vector<string>::iterator begin = v.begin();
     9     while(begin!=v.end())
    10     {
    11         cout << *begin++ << endl;
    12     }
    13     for(int i:{1,2,3})
    14     {
    15         cout << i << endl;
    16     }
    17     return 0;
    18 }//输出 ab cd 1 2 3
    View Code

    我们可以在一个函数的参数中声明initializer_list,这样,我们在调用这个函数时,可以直接给这个函数传递大括号即可。

    头文件S.h

     1 #ifndef S_H_INCLUDED
     2 #define S_H_INCLUDED
     3 
     4 #include <vector>
     5 #include <initializer_list>
     6 #include <iostream>
     7 
     8 using namespace std;
     9 
    10 template <typename T>
    11 class S
    12 {
    13 private:
    14     vector<T> v;
    15 public:
    16     S(initializer_list<T> l):v(l)
    17     {
    18         cout << "constructed with a " << l.size() << " -element lists" << endl;
    19     }
    20     void append(initializer_list<T> l)
    21     {
    22         v.insert(v.end(),l.begin(),l.end());
    23     }
    24     void append(T t)
    25     {
    26         v.push_back(t);
    27     }
    28     void print()
    29     {
    30         typename vector<T>::iterator begin = v.begin();
    31         while(begin!=v.end())
    32         {
    33             cout << *begin++ << endl;
    34         }
    35     }
    36 };
    37 
    38 #endif // S_H_INCLUDED
    View Code

    main函数:

     1 #include <iostream>
     2 #include "S.h"
     3 
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     S<int> s{10};
     9     s.append(1);
    10     s.append({2,3,4,6,9});
    11     cout << "begin to print()" << endl;
    12     s.print();
    13     return 0;
    14 }
    View Code

  • 相关阅读:
    OSI安全体系结构
    PHP 二维数组根据相同的值进行合并
    Java实现 LeetCode 17 电话号码的字母组合
    Java实现 LeetCode 16 最接近的三数之和
    Java实现 LeetCode 16 最接近的三数之和
    Java实现 LeetCode 16 最接近的三数之和
    Java实现 LeetCode 15 三数之和
    Java实现 LeetCode 15 三数之和
    Java实现 LeetCode 15 三数之和
    Java实现 LeetCode 14 最长公共前缀
  • 原文地址:https://www.cnblogs.com/wsl96/p/13093150.html
Copyright © 2011-2022 走看看