The Foundation collection classes use a position indicator to describe a given position within the collection. To access one or more members of a collection, first initialize the position indicator and then repeatedly pass that position to the collection and ask it to return the next element. The collection is not responsible for maintaining state information about the progress of the iteration. That information is kept in the position indicator. But, given a particular position, the collection is responsible for returning the next element.
The following examples show how to iterate over the three main types of collections provided with the Microsoft Foundation Class Library.
·To iterate an array:
Use sequential index numbers with the GetAt member function:
CObArray myArray;
for( int i = 0; i < myArray.GetSize();i++ )
{
CPerson* thePerson = (CPerson*)myArray.GetAt( i );
...
}
·To iterate a list:
Use the member functions GetHeadPosition and GetNext to work your way through the list:
CPersonList myList;
POSITION pos = myList.GetHeadPosition();
while( pos != NULL )
{
CPerson* thePerson = myList.GetNext( pos );
...
}
·To iterate a map:
Use GetStartPosition to get to the beginning of the map and GetNextAssociation to repeatedly get the next key and value from the map, as shown by the following example:
CMapStringToOb myMap;
POSITION pos = myMap.GetStartPosition();
while( pos != NULL )
{
CObject* pObject;
CPerson* pPerson;
CString string;
// gets key ( string ) and value ( pObject )
myMap.GetNextAssoc( pos, string, pObject );
if( pObject->IsKindOf( RUNTIME_CLASS(CPerson) ) )
{
pPerson = (CPerson*)pObject;
//...
}
}