標籤: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