Using a map
A classic example that relies on associative arrays is a word-counting program:
// count the number of times each word occurs in the inputmap<string, size_t> word_count; // empty map from string to size_tstring word;while (cin >> word) ++word_count[word]; // fetch and increment the counter for wordfor (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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access