序列式容器List之初始化及其幾種(不支援隨機)訪問形式
阿新 • • 發佈:2019-02-08
#include <list> #include <iostream> #include <algorithm> using namespace std; void show(char elem) { cout << elem << " "; } int main() { list<char> coll; // list container for character elements // append elements from 'a' to 'z' for (char c = 'a'; c <= 'z'; ++c) { coll.push_back(c); } // print all elements: /* list容器不支援隨機訪問,即不可用[]操作符讀取容器中某元素 // WRONG CODE FOLLOWING for(int i =0; i<= coll.size(); ++i) { cout << coll[i] << " ";// wrong, 不支援隨機訪問 } */ // 迭代器是位置,*迭代器是該位置的值 // C++11後加入auto自動判斷符。 for (auto pos = coll.begin(); pos != coll.end();++pos) for (list<char>::iterator pos = coll.begin(); pos != coll.end();++pos) { cout << *pos << " ";// OK } cout << endl; // - use range-based for loop for (auto elem : coll) { cout << elem << ' '; } cout << endl; // for_each and Lambdas for_each(coll.begin(), coll.end(), [](char elem){ cout << elem << " "; }); cout << endl; // for_each and function objects(functors) for_each(coll.begin(), coll.end(), show); cin.get(); // return 0;// 可以不顯式的寫出返回值0。其實C++11厚int main()形式的main函式已經隱式提供了return 0; }
執行結果: