首页 > 编程语言 > 详细

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

时间:2015-08-28 19:47:25      阅读:169      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!