On line 4, you see the use of the typedefcommend. In this case, instead of using
list<int>throughout the listing, the typedeflets you use IntegerList. This is much
easier to read.
On line 8,intListis defined as a list of integers using the typedefthat was just created.
The first 10 positive even numbers are added to the list using the push_back()function
on lines 10 and 11.
On lines 13–15, each node in the list is accessed using a constant iterator. This indicates
that there is no intent to change the nodes with this iterator. If you want to change a node
pointed to be an iterator, you need to use a non-constiterator instead:
intList::iterator
The begin()member function returns an iterator pointing to the first node of the list. As
can be seen here, the increment operator ++can be used to point an iterator to the next
node. Theend()member function is kind of strange—it returns an iterator pointing to
one-pass-last node of a list. You must be certain that your iterator doesn’t reach end()!
The iterator is dereferenced the same as a pointer, to return the node pointed to, as shown
on line 15.
Although iterators are introduced here with the listclass, the vectorclass also provides
iterators. In addition to functions introduced in the vectorclass, the listclass also pro-
vides the push_front()and pop_front()functions that work just like push_back()and
pop_back(). Instead of adding and removing elements at the back of the list, they add
and remove elements in the front of the list.
The Stacks Container
One of the most commonly used data structures in computer programming is the stack.
The stack, however, is not implemented as an independent container class. Instead, it is
implemented as a wrapper of a container. The template class stackis defined in the
header file <stack>in the namespace std.
A stackis a continuously allocated block that can grow or shrink at the back end.
Elements in a stack can only be accessed or removed from the back. You have seen simi-
lar characteristics in the sequence containers, notably vectorand deque. In fact, any
sequence container that supports the back(),push_back(), and pop_back()operations
can be used to implement a stack. Most of the other container methods are not required
for the stack and are, therefore, not exposed by the stack.
The STL stacktemplate class is designed to contain any type of objects. The only
restriction is that all elements must be of the same type.
702 Day 19