Modeling Services > Relations > List-relations > List Iterators
 
List Iterators
Rogue Wave® Server provides an Iterator type that is used to:
*Read a list sequentially from top to bottom, and vice versa.
*Add items anywhere in a list or remove items from a list.
This type is nested in the class templates IlsOwnsList and IlsUsesList.
The Iterator type for the owned_cars relation we declared in “Declaring Simple List-relations”. is:
IlsOwnsList<Person,Car>::Iterator
Lets us suppose that the class Car contains the member function printCars:
class Person:
public IlsObject
{
public:
   IlsOwnsList<Person,Car> owned_cars;
   Person();
   void printCars();
};
To build an iterator to a list, you simply have to pass the list to the iterator constructor.
To implement the function Person::printCars, you first have to build an iterator to the relation owned_cars by passing the relation to the iterator constructor:
void Person::printCars(){
   IlsOwnsList<Person,Car>::Iterator i(owned_cars);
   // ...
}
You have simply passed the owned_cars relation to the constructor of the iterator variable (i).
Once the iterator has been built, you can read the list sequentially using the member
operator >>:
void Person::printCars(){
   IlsOwnsList<Person,Car>::Iterator i(owned_cars);
   CarP c;
   while (i>>c){
     c->print();
   }
}
Each time the operator (i>>c) is called, the smart pointer to the next car in the list is stored
in the c variable. The operator returns the iterator which converts to a Boolean type. When the end of the list is reached, the operator converts to IlsFalse and the while loop stops.
You can also move an iterator forwards or backwards in the list using the member
operators ++ or --.
To insert an element directly after the last item read, you just have to call the operator <<, like this:
i<<new Car();
To insert an item right before the last item read, you just have to call the sequence:
i--;
i<<new Car();
The iterator will be first moved backwards and then the new item will be added to the list.
To remove the item that comes after the last item read, call the shrink function like this:
i.shrink();
To remove the last item read, call the shrinkBefore function like this:
i.shrinkBefore();
This function call is equivalent to:
i--;
i.shrink();
When the iterator is positioned at the very beginning of the list, any item added to the list will be placed before the first item. Similarly, when the iterator is positioned at the end of the list, any new item will be inserted after the last item.
Figure 2.3    List Iterators
Similar rules apply to shrink and shrinkBefore.
For more information about how this iterator works, see IlsOwnsList::Iterator and IlsUsesList::Iterator in the Rogue Wave Server Reference Manual.

Version 5.8
Copyright © 2014, Rogue Wave Software, Inc. All Rights Reserved.