只需定义一个宏:
#define foreach(container,i) for(bool __foreach_ctrl__=true;__foreach_ctrl__;)\
for(typedef typeof(container) __foreach_type__;__foreach_ctrl__;__foreach_ctrl__=false)\
for(__foreach_type__::iterator i=container.begin();i!=container.end();i++)
就可以这样遍历STL容器:
std::list<int> list;/*输出结果:
list.insert(list.end(),5);
list.insert(list.end(),7);
list.insert(list.end(),3);
foreach(list,i) //可与C#、PHP的foreach相媲美的简便用法(i不用声明类型)
{
std::cout<<*i<<endl;
}
5
7
3
*/