码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-08-28 19:49:22      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/king__moving/article/details/48056311

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!