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++遍历集合的相关介绍。

【编辑推荐】

  1. C++ include机制基本概念详解
  2. C++ explicit关键字基本内容概述
  3. C++成员函数指针详细使用指南
  4. C++访问控制符内容相关介绍
  5. C++ typeof基本应用方式解析
THE END