map
A classic example that relies on associative arrays is a word-counting program:
// count the number of times each word occurs in the input
map<string, size_t> word_count; // empty map from string to size_t
string word;
while (cin >> word)
++word_count[word]; // fetch and increment the counter for word
for (const auto &w : word_count) // for each element in the map
// print the results
cout << w.first << " occurs " << w.second
<< ((w.second > 1) ? " times" : " time") << endl;
This program reads its input and reports how often each word appears.
Like the sequential containers, the associative containers are templates (§ 3.3, p. 96). To define a map
, we must specify both the key and value types. In this program, the map
stores elements in which the keys are string
s and the values are size_t
s (§ 3.5.2, p. 116). When we subscript word_count
, we use a string
as the subscript, and we get back the size_t
counter associated with that string
.
The while
loop reads the standard input one word at a time. It uses each word to subscript word_count
. If word
is not already in the map
, the subscript operator creates a new element whose key is word
and whose value is 0
. Regardless of whether the element had to be created, we increment the value.
Once we’ve read all the input, the range for
(§ 3.2.3, p. 91) iterates through the map
, printing each word and the corresponding counter. When we fetch an element from a map
, we get an object of type pair
, which we’ll describe in § 11.2.3 (p. 426). Briefly, a pair
is a template type that holds two (public
) data elements named first
and second
. The pair
s used by map
have a first
member that is the key and a second
member that is the corresponding value. Thus, the effect of the output statement is to print each word and its associated counter.
If we ran this program on the text of the first paragraph in this section, our output would be
Although occurs 1 time
Before occurs 1 time
an occurs 1 time
and occurs 1 time
...