龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++遍历集合应用经验总结

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
C++ 作为一种C语言的升级版本,可以为开发人员带来非常大的好处。我们在这篇文章中将会针对C++遍历集合的相关概念进行一个详细的介绍,希望大家可以从中获得一些帮助,以方便自

C++作为一种C语言的升级版本,可以为开发人员带来非常大的好处。我们在这篇文章中将会针对C++遍历集合的相关概念进行一个详细的介绍,希望大家可以从中获得一些帮助,以方便自己的学习。

在Java中,常见的遍历集合方式如下:

  1. Iterator iter = list.iterator();  
  2. while (iter.hasNext()) {  
  3. Object item = iter.next();  

也可以使用for

  1. for (Iterator iter = list.iterator(); iter.hasNext()) {  
  2. Object item = iter.next();  

JDK 1.5引入的增强的for语法

  1. List list =   
  2. for (Integer item : list) {  

在C#中,遍历集合的方式如下:

  1. foreach (Object item in list)   
  2. {  

其实你还可以这样写,不过这样写的人很少而已

  1. IEnumerator e = list.GetEnumerator();  
  2. while (e.MoveNext())   
  3. {  
  4. Object item = e.Current;  

在C# 2.0中,foreach能够作一定程度的编译期类型检查。例如:

  1. IList< int> intList =   
  2. foreach(String item in intList) { } //编译出错 

在C++标准库中。for_each是一种算法。定义如下:

  1. for_each(InputIterator beg, InputIterator end, UnaryProc op) 

在C++遍历集合中,由于能够重载运算符(),所以有一种特殊的对象,仿函数。

  1. template< class T> 
  2. class AddValue {  
  3. private:  
  4. T theValue;  
  5. public:  
  6. AddValue(const T& v) : theValue(v) {  
  7. }  
  8. void operator() (T& elem) const {  
  9. elem += theValue;  
  10. }  
  11. };  
  12. vector< int> v;  
  13. INSERT_ELEMENTS(v, 1, 9);  
  14. for_each (v.begin(), v.end(), AddValue< int>(10)); 

以上就是对C++遍历集合的相关介绍。

精彩图集

赞助商链接