11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

368Part V: Optional FeaturesInput a name (input an x to terminate list)AdamsDavisValentineSmithWilsonxSorted output:AdamsDavisSmithValentineWilsonPress any key to continue . . .The list container provides a large set of operators. Simple operationsinclude insert, swap, and erase. This same container also gives the programmerthe ability to automatically iterate through the list invoking thesame user-defined function on each object.The operation that the list cannot provide is random access. Becauseobjects can be snapped together in any order, there is no quick way for thelist class to return the nth object.IteratorsThe STLList sample program presented in the prior section uses a destructiveapproach to iterating through the list. The pop_front() method movesthe user through the list by removing the first object in each case.The programmer iterates through an array by providing the index of each element.However, this technique doesn’t work for containers like list that don’tallow for random access. One could imagine a solution based upon methodssuch as getFirst() and getNext(); however, the designers of the STL wantedto provide a common method for traversing any type of container. For this, theSTL defines the iterator.An iterator is an object that points to the members of a container. In general,every iterator supports the following functions: A class can return an iterator that points to the first member of thecollection. The iterator can be moved from one member to the next. The program can retrieve the element pointed to by the iterator.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!