运用map,string并于执行期指定排序准则

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& mapObj)
{
	typedef map::const_iterator  mapIter;
	for (mapIter iter = mapObj.begin(); iter != mapObj.end(); iter++)
	{
		cout << iter->first << " " << iter->second << endl;
	}

}

int main()
{
	map stringMap;

	string tempString1;
	string tempString2;
	while(cin >> tempString1)
	{
		cin >> tempString2;
		stringMap[tempString1] = tempString2;
	}

	printMap(stringMap);
	cin.clear();

	RuntimeStringCmp cmp(RuntimeStringCmp::nocase);
	map stringMap2(cmp);

	while(cin >> tempString1)
	{
		cin >> tempString2;
		stringMap2[tempString1] = tempString2;
	}
	printMap(stringMap2);

	system("pause");
        return 0;
}

你可能感兴趣的:(STL)