beautypg.com

Map-based iteration and pairs – HP Integrity NonStop J-Series User Manual

Page 127

background image

Again, your standard library documentation will describe all the operators and functions available
for each type of iterator.

In addition to the iterators just described, the standard library-based collection class templates also
provide two typedefs used to iterate over the items in a collection class: iterator, and const_iterator.
You can use the iterator typedef to traverse a collection class and modify the elements within. You
can use instances of const_iterator to traverse, but not modify, the collection class and access
elements. For the associative container-based and sorted sequence-based collections, which do not
allow modification of elements once they are in the collection class, the iterator and const_iterator
types are the same.

Finally, the templates also provide two member functions that return actual iterators you can use for
traversing their respective collection classes. These member functions are begin() and end(). Each
of these member functions is overloaded by a const receiver so that the non-const version returns an
instance of type iterator, and the const version returns an instance of type const_iterator.

Member function begin() always returns an iterator already positioned at the first item in the
collection class. Member function end() returns an iterator which has a past-the-end value, the way
a pointer to the NULL character of a null-terminated character string has a value that points "past
the end." An iterator of past-the-end value can be used to compare with another iterator to see if
you've finished visiting all the elements in the collection class. It can also be used as a starting point
for moving backwards through collection classes that provide either bidirectional or random-access
iterators. The one thing you cannot do with an end() iterator is dereference it. The one thing you
cannot do with an end() iterator is deference it. Here's an example using iterators to move through a
list and search for a match:

RWTValDlist intCollection; // a list of integers

// ... < put stuff in the list >

// position iter at start:
RWTValDlist::iterator iter = intCollection.begin();

// set another iterator past the end:
RWTValDlist::iterator theEnd = intCollection.end();

// iterate through, looking for a 7:
while (iter != theEnd) { // test for end of collection
if (*iter == 7) // use '*' to access current element
return true; // found a 7
++iter; // not a 7, try next element
}
return false; // never found a 7

This manual is related to the following products: