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 ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.