class RuntimeStringCmp { public: enum cmp_mode { normal, nocase, }; RuntimeStringCmp(cmp_mode mod=normal):mode(mod) { } ~RuntimeStringCmp() { } static bool nocase_compare(char char1,char char2) { return toupper(char1) < toupper(char2); } bool operator()(const string& str1, const string& str2) { if (mode == normal) { return str1 < str2; } else { return lexicographical_compare(str1.begin(), str1.end(), str2.begin(), str2.end(), nocase_compare); } } private: const cmp_mode mode; }; void printMap(const map<string, string, RuntimeStringCmp>& mapObj) { typedef map<string, string, RuntimeStringCmp>::const_iterator mapIter; for (mapIter iter = mapObj.begin(); iter != mapObj.end(); iter++) { cout << iter->first << " " << iter->second << endl; } } int main() { map<string, string, RuntimeStringCmp> stringMap; string tempString1; string tempString2; while(cin >> tempString1) { cin >> tempString2; stringMap[tempString1] = tempString2; } printMap(stringMap); cin.clear(); RuntimeStringCmp cmp(RuntimeStringCmp::nocase); map<string, string, RuntimeStringCmp> stringMap2(cmp); while(cin >> tempString1) { cin >> tempString2; stringMap2[tempString1] = tempString2; } printMap(stringMap2); system("pause"); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-20 23:35:57