In Java, the common way to traverse a set is as follows:
Iterator iter = List. iterator ();
While (ITER. hasnext ()){
Object item = ITER. Next ();
}
You can also use
For (iterator iter = List. iterator (); ITER. hasnext ()){
Object item = ITER. Next ();
}
Enhanced for syntax introduced by JDK 1.5
List list =
For (integer item: List ){
}
In C #, the way to traverse the set is as follows:
Foreach (Object item in List)
{
}
You can write like this, but there are very few people writing like this.
Ienumerator E = List. getenumerator ();
While (E. movenext ())
{
Object item = E. Current;
}
In C #2.0, foreach can perform a certain degree of compile-time type check. For example:
Ilist <int> intlist =
Foreach (string item in intlist) {}// compilation Error
In the C ++ standard library. For_each is an algorithm. Definition:
For_each (inputiterator beg, inputiterator end, unaryproc OP)
In C ++, the operator () can be overloaded, so there is a special object that is similar to a function.
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 ));