// Example illustrating the use of map STL container #include #include #include #include // store phone numbers as a MAP from string --> integer typedef map > phone_map; typedef map >::iterator phone_map_ptr; int main() { phone_map directory; directory["Einstein"] = 123456; directory["Newton"] = 987654; directory["Oppenheimer"] = 45678; directory["Fermi"] = 234567; // list the directory; map is complicated by the fact // that its elements are PAIRS of objects, the first is // the key, and the 2nd is the associated value // The pairs, fortunately, are represented by the STL // template "pair", and there are standard ways to get // the first and second element of the pair: using // PUBLIC MEMBER DATA (RATHER THAN FUNCTIONS!!) // of "pair" -- "first" and "second" respectively phone_map_ptr dp; for (dp=directory.begin(); dp!=directory.end(); dp++) cout << "Phone number for: " << (*dp).first << " is " << (*dp).second << endl; cout << "Map Lookups: " << endl; // You can use the subscript notation with maps cout << "Phone lookup for Oppenheimer is: " << directory["Oppenheimer"] << endl; // dangerous to loop up non existent items!! // nonexistent gets inserted in with a "default" value cout << "Phone lookup for nonexistent is: " << directory["nonexistent"] << endl; for (dp=directory.begin(); dp!=directory.end(); dp++) cout << "Phone number for: " << (*dp).first << " is " << (*dp).second << endl; // shows how to use the map as a simple database that // can be queried... string name; cout << "Enter name to look for: "; cin >> name; while (name != "done") { if (directory.find(name) != directory.end()) cout << "Phone Number for: " << name << " = " << directory[name] << endl; else cout << "No Phone Number for: " << name << endl; cout << "Enter name to look for: "; cin >> name; } }