在Java、C#和C++中遍历集合
在Java中,常见的遍历集合方式如下:
Iterator iter = list.iterator();
while (iter.hasNext()) {
Object item = iter.next();
}也可以使用for
for (Iterator iter = list.iterator(); iter.hasNext()) {
Object item = iter.next();
}
JDK 1.5引入的增强的for语法
List list = 
for (Integer item : list) {
}在C#中,遍历集合的方式如下:
foreach (Object item in list)
{
}其实你还可以这样写,不过这样写的人很少而已
IEnumerator e = list.GetEnumerator();
while (e.MoveNext())
{
Object item = e.Current;
}在C# 2.0中,foreach能够作一定程度的编译期类型检查。例如:
IList<int> intList = 
foreach(String item in intList) { } //编译出错
在C++标准库中。for_each是一种算法。定义如下:
for_each(InputIterator beg, InputIterator end, UnaryProc op)
C++中,由于能够重载运算符(),所以有一种特殊的对象,仿函数。
template<class T>
class AddValue {
private:
T theValue;
public:
AddValue(const T& v) : theValue(v) {
}
void operator() (T& elem) const {
elem += theValue;
}
};
vector<int> v;
INSERT_ELEMENTS(v, 1, 9);
for_each (v.begin(), v.end(), AddValue<int>(10));

AddValue(
浙公网安备 33010602011771号