


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Reading: Ford & Topp, Sections 11.1 & 11.3; Koenig & Moo, Chapter 7.
map<key_type, value_type> var_name
In our first two examples above, key type is a string. In the first example, the value type is an int and in the second it is a vector
pair<const key_type, value_type>
Let’s see how this some of this works with a program to count the occurrences of each word in a file. We’ll look at more details and more examples later.
#include
int main() { std::string s; std::map<std::string, int> counters; // store each word and an associated counter
// read the input, keeping track of each word and how often we see it while (std::cin >> s) ++counters[s];
// write the words and associated counts std::map<std::string, int>::const_iterator it; for (it = counters.begin(); it != counters.end(); ++it) { std::cout << it->first << "\t" << it->second << std::endl; } return 0; }
second
it "see" 2
"run" 1
"spot" 1
map<string, int> counters first
The mechanics of using pairs are simple, but they challenge our understanding of types...
std::pair<int, double> p1(5, 7.5); std::pair<int, double> p2 = std::make_pair(8, 9.5); p1.first = p2.first; p2.second = 13.3; std::cout << p1.first << " " << p1.second << std::endl; std::cout << p2.first << " " << p2.second << std::endl; p1 = p2;
std::pair<const string, double> p3 = std::make_pair(string("hello"), 3.5); p3.second = -1.5; // p3.first = string("illegal"); // (a) // p1 = p3; // (b)
Maps provide three different versions of the erase member function:
Re-write the word count program so that it uses find and insert instead of operator[].