c++ initializer_list

來源:互聯網
上載者:User

標籤:begin   std   using   logs   列印   編譯   int   結果   iter   

 

首先需要開啟編譯器C++11,按照如下步驟(codeblocks)

Setting-->Compiler 勾選紅色方框的選項。

 

首先看看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 }

 列印結果如下:

 

來看看正式的作用:

我們可以在一個函數的參數中聲明initializer_list,這樣,我們在調用這個函數時,可以直接給這個函數傳遞大括弧即可。如下代碼所示:

 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 S12 {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

 

看看調用的代碼:

 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 }

 

最後列印結果如下:

 

不要忘記了,標頭檔是 #include <initializer_list>

 

c++ initializer_list

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.