Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 701

19


The List Container
A list is a container designed to be optimal when you are frequently inserting and delet-
ing elements. The listSTL container class is defined in the header file <list>in the
namespace std. The listclass is implemented as a doubly-linked list, where each node
has links to both the previous node and the next node in the list.
Thelistclass has all the member functions provided by the vectorclass. As you have
seen in “Week 2 in Review,” you can traverse a list by following the links provided in
each node. Typically, the links are implemented using pointers. The standard listcon-
tainer class uses a mechanism called the iterator for the same purpose.
An iterator is a generalization of a pointer and attempts to avoid some of the dangers of a
pointer.
You can dereference an iterator to retrieve the node to which it points. Listing 19.9
demonstrates the use of iterators in accessing nodes in a list.

LISTING19.9 Traverse a List Using an Iterator


0: #include <iostream>
1: #include <list>
2: using namespace std;
3:
4: typedef list<int> IntegerList;
5:
6: int main()
7: {
8: IntegerList intList;
9:
10: for (int i = 1; i <= 10; ++i)
11: intList.push_back(i * 2);
12:
13: for (IntegerList::const_iterator ci = intList.begin();
14: ci != intList.end(); ++ci)
15: cout << *ci << “ “;
16:
17: return 0;
18: }

2 4 6 8 10 12 14 16 18 20

Listing 19.9 uses the STL’s list template. On line 1, the necessary include file is
#included. This pulls in the code for the list template from the STL.

OUTPUT


ANALYSIS
Free download pdf