Traverse the Set (ilist) in Java, C #, and C ++)

Source: Internet
Author: User

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 ));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.