We continue the practice in this section of using the word count program to explore containers. However, rather than creating a container, we greatly simplify the programs by using existing STL containers. The basic program logic remains unchanged from the KVTree version: the program reads the input file one character at a time, converts the alphabetic characters to lower case, and appends them to a word. When the word is complete, the program searches a container for the word. If the word isn't in the container, the program adds it and increments its count otherwise. Please see the earlier example for details omitted for brevity.
The STL examples contrast a map implementation of the word-count program with two list implementations. The STL implements a map with a binary tree, providing fast insert and search operations. Both operations slow as the tree becomes larger. Fortunately, the slowdown is gradual with the runtime generally (ignoring some worst-case scenarios) proportional to log n, where n is the number of tree nodes. Conversely, lists are linear data structures whose insert and search operations degrade more quickly than binary trees as the data size increases. The time to run the list operations is proportional to n. We begin by introducing some STL support classes.
STL Iterators
Reiterating (did you see what I did there?) our previous definition, "iterators are objects that sequentially access the elements stored in a container object," allowing a program to loop or iterate through them. The rudimentary iterator we created for the KVTree is quite limited compared with the STL iterators. Although the iterators used by the following programs are all named iterator, their full names, formed with a container class name and the scope resolution operator, are unique - they are not the iterator.
While programs instantiate the STL iterators from distinct classes, they share several crucial features:
Containers using iterators provide numerous functions for creating them, e.g., begin, end, rbegin, and rend
The functions return pointers to the iterators, so they are often dereferenced or used with the arrow operator
Programs move forward or backward through the iterator elements with the increment (++) and decrement (--) operators
The pair class
The pair structure builds an association between two values whose types it represents with template variables. In Chapter 9, I claimed, "The only real difference between a struct and a class is the default visibility: structures have public visibility, and classes have private visibility. Nevertheless, C++ programmers generally only use structures to represent packaged data and reserve classes for truly object-oriented situations (i.e., when an entity should have attributes and operations packaged together)." pair is an exception: programmers often access both fields or members, but giving it functions eases its use.