C++的新特性for-each

C++实验课要求用for each 循环来实现关联容器 map 的输出,一开始完全萌比。查了好久的资料才整理出下面的:

  C++11新特性之一就是类似java的for each循环:

 1 map<int, string> m;
 2  // 1
 3 for (    auto &v : m)  
 4      {
 5          cout<<v.first<<" "<<v.second<<endl;
 6     }
 7 
 8  // 2 lamda表达式
 9  for_each(m.begin(),m.end(),[](map<int,string>::reference a){
10          cout<<a.first<<" "<<a.second<<endl;
11      });
12 
13 // 3 for_each
14  void fun(map<int,string>::reference a)  //不要少了reference,不然会报错。
15 {
16          cout<<a.first<<" "<<a.second<<endl;
17 }
18 for_each(m.begin(),m.end(),fun);

还有一种宏定义的方法: 

1 //定义
2 #define foreach(container,it) \
3     for(typeof((container).begin()) it = (container).begin();it!=(container).end();++it)
4 //输出
5 foreach(m,it)
6     {
7         cout<<it->first<<","<<it->second<<endl;
8     }

猜你喜欢

转载自www.cnblogs.com/DSYR/p/9151975.html