#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;
}
运行结果: