text cover

Data Abstraction and Problem Solving with C++

Walls and Mirrors

by Frank M. Carrano

Addison Wesley Logo

example637.cpp

Go to the documentation of this file.
00001 
00015 #include <map>
00016 #include <iostream>
00017 #include <string>
00018 
00019 using namespace std;
00020 
00021 int main()
00022 {
00023    // declare a map to contain names and phone numbers
00024    map<string, string> phoneBook;
00025 
00026    // declare a map iterator
00027    map<string, string>::const_iterator it1;
00028 
00029    string name1 = "Smith, John";
00030    string name2 = "Thompson, Julia";
00031    string name3 = "Johnson, Mary";
00032    string name4 = "Little, Carol";
00033    string name5 = "Johnson, Mary";
00034    string phone1 = "212-555-4444";
00035    string phone2 = "806-555-6565";
00036    string phone3 = "445-555-7111";
00037    string phone4 = "745-555-6787";
00038    string phone5 = "745-555-7777";
00039 
00040    // assign elements to map using subscripts
00041    phoneBook[name1] = phone1;
00042    phoneBook[name2] = phone2;
00043    phoneBook[name3] = phone3;
00044    phoneBook[name4] = phone4;
00045    phoneBook[name5] = phone5;
00046 
00047    // print map elements
00048    // duplicate name keys are not listed
00049    for (it1 = phoneBook.begin(); it1 != phoneBook.end(); ++it1)
00050    {
00051       cout << it1->first << '\t' << it1->second << endl;
00052    }  // end for
00053 
00054    // find a map element
00055    it1 = phoneBook.find(string(name3));
00056 
00057    // display found map element
00058    if (it1 != phoneBook.end())
00059       cout << " Search for " << it1->first
00060       << " - phone numbers" << endl
00061       << it1->second << endl << endl;
00062 
00063    // create a multimap to contain names and phone numbers
00064    // use the make_pair function to insert elements
00065    multimap<string, string> phoneBook2;
00066    phoneBook2.insert(make_pair(name1, phone1));
00067    phoneBook2.insert(make_pair(name2, phone2));
00068    phoneBook2.insert(make_pair(name3, phone3));
00069    phoneBook2.insert(make_pair(name4, phone4));
00070    phoneBook2.insert(make_pair(name5, phone5));
00071 
00072    typedef multimap<string, string>::const_iterator iter2;
00073 
00074    // print map elements
00075    for (iter2 it2 = phoneBook2.begin();
00076         it2 != phoneBook2.end(); ++it2)
00077    {
00078       cout << it2->first << '\t' << it2->second << endl;
00079    }  // end for
00080 
00081    // returns map pairs with the same key
00082    pair<iter2, iter2> phoneNum = phoneBook2.equal_range(name3);
00083 
00084    // display pairs with same key
00085    cout << "Search for " << name3
00086         << " - phone numbers: " << endl;
00087 
00088    for(iter2 it2 = phoneNum.first; it2 != phoneNum.second; ++it2)
00089       cout << it2->second << endl;
00090 
00091    return 0;
00092 }  // end main

Generated on Sun Aug 27 22:03:18 2006 for AWLogo by  doxygen 1.4.6