class Name
class PhoneNumber
1: //multimap03.cpp
2: //Uses a multimap to create a "phone directory".
4: #include <iostream>
5: #include <map>
6: #include <string>
7: using namespace std;
9: //This is the "key" class for the key/value pairs.
10: //Note the inline function definitions.
11: class Name
12: {
13: public:
14: Name() { nameString = ""; }
15: Name(string s) { nameString = s; }
16: string getName() const { return nameString; }
17: private:
18: string nameString;
19: };
21: //Define operator< for Name objects.
22: //Try removing this definition to see what error is generated.
23: bool operator<(Name n1, Name n2)
24: {
25: return n1.getName() < n2.getName();
26: }
28: //This is the "value" class for the key/value pairs.
29: //Again note the inline function definitions.
30: class PhoneNumber
31: {
32: public:
33: PhoneNumber() { numberString = ""; }
34: PhoneNumber(string s) { numberString = s; }
35: string getNumber() const { return numberString; }
36: private:
37: string numberString;
38: };
40: int main()
41: {
42: cout << "\nThis program illustrates a \"phone book\" in which a "
43: "person may have\nmore than one phone number.";
44: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
46: multimap<Name, PhoneNumber> directory;
47: directory.insert(pair<Name, PhoneNumber>
48: (Name("Tom"), PhoneNumber("555-4533")));
49: directory.insert(pair<Name, PhoneNumber>
50: (Name("Tom"), PhoneNumber("555-9999")));
51: directory.insert(pair<Name, PhoneNumber>
52: (Name("Chris"), PhoneNumber("555-9678")));
53: directory.insert(pair<Name, PhoneNumber>
54: (Name("John"), PhoneNumber("555-8195")));
55: directory.insert(pair<Name, PhoneNumber>
56: (Name("Rachel"), PhoneNumber("555-0809")));
57: directory.insert(pair<Name, PhoneNumber>
58: (Name("Rachel"), PhoneNumber("555-3434")));
59: directory.insert(pair<Name, PhoneNumber>
60: (Name("Rachel"), PhoneNumber("555-7776")));
61: cout << "\nHere are the names and numbers in our phone book:\n";
62: multimap<Name, PhoneNumber>::iterator p1 = directory.begin();
63: while (p1 != directory.end())
64: {
65: cout << p1->first.getName() << " "
66: << p1->second.getNumber() << endl;
67: ++p1;
68: }
69: cout << "Press Enter to continue ... "; cin.ignore(80, '\n');
70:
71: string name;
72: cout << "\nEnter a name to get that person's phone number(s): ";
73: cin >> name; cin.ignore(80, '\n');
74: multimap<Name, PhoneNumber>::iterator p2;
75: p2 = directory.find(name);
76: if (p2 != directory.end())
77: {
78: do
79: {
80: cout << "Phone number: " << p2->second.getNumber() << endl;
81: p2++;
82: }
83: while (p2 != directory.upper_bound(name));
84: }
85: else
86: cout << "That name was not in our directory.\n";
87: cout << "Press Enter to continue ... "; cin.ignore(80, '\n');
88: }