// File: MapCaseIndependentKey.cpp // Map using a comparator to acheive case independent lookup! #include #include #include using namespace std; // case-independent (ci) string less_than // returns true if s1 < s2 struct ci_less : binary_function { // case-independent (ci) compare_less binary function struct nocase_compare : public binary_function { bool operator() (const unsigned char& c1, const unsigned char& c2) const { return tolower (c1) < tolower (c2); } }; bool operator() (const string & s1, const string & s2) const { return lexicographical_compare (s1.begin (), s1.end (), // source range s2.begin (), s2.end (), // dest range nocase_compare ()); // comparison } }; // end of ci_less typedef map age_map; ostream &operator<<(ostream &out,age_map TheMap) { for (age_map::iterator it=TheMap.begin();it!=TheMap.end();it++) out << " [" << it->first << ", " << it->second << "]" << endl; } void addPeople(age_map &TheMap) { cout << "Enter a Name >"; string TheName; getline(cin,TheName); while (TheName.size()) { cout << "Enter age >"; int age; cin >> age; TheMap[TheName]=age; // Eat carriage return cin.get(); cout << "Enter a Name >"; getline(cin,TheName); } } int main (void) { // make a map of people age_map people; // add items to list people ["Nick"] = 28; people ["John"] = 14; people ["Mary"] = 88; // Add people to the map addPeople(people); // print whole map cout << people; // find someone by key cout << "Finding person 'nick' ..." << endl; age_map::const_iterator i = people.find ("nick"); if (i == people.end ()) cout << "Not found." << endl; else cout << "Found age = " << i->second << endl; return 0; } // end of main