导航

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

Posted on 2014-07-17 16:31  ggzone  阅读(202)  评论(0编辑  收藏  举报

该例展示以下技巧:

  • 如何使用map
  • 如何撰写和使用仿函数
  • 如何在执行期定义排序规则
  • 如何在“不在乎大小写”的情况下比较字符串
#include<iostream>
#include<map>
#include<algorithm>
#include<iomanip>
#include<string>

using namespace std;

class RuntimeStringCmp
{
public:
	enum cmp_mode{normal,nocase};

private:
	const cmp_mode mode;

	static bool nocase_compare(char c1, char c2)
	{
		return toupper(c1) < toupper(c2);
	}

public:
	RuntimeStringCmp(cmp_mode m = normal) :mode(m){}

	bool operator()(const string& s1, const string& s2)const
	{
		if (mode == normal)
			return s1 < s2;
		else
			return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
	}
};

typedef map<string, string, RuntimeStringCmp> StringStringMap;
void fillAndPrint(StringStringMap& coll);

int main()
{
	StringStringMap coll1;
	fillAndPrint(coll1);

	RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
	StringStringMap coll2(ignorecase);
	fillAndPrint(coll2);
	
	system("pause");
	return 0;
}

void fillAndPrint(StringStringMap& coll)
{
	coll["Deutschland"] = "Germany";
	coll["deutsch"] = "German";
	coll["Haken"] = "snag";
	coll["arbeiten"] = "work";
	coll["Hund"] = "dog";
	coll["gehen"] = "go";
	coll["Unternehmen"] = "enterprise";
	coll["unternehmen"] = "undertake";
	coll["gehen"] = "walk";
	coll["Bestatter"] = "undertaker";

	StringStringMap::iterator pos;
	cout.setf(ios::left, ios::adjustfield);
	for (pos = coll.begin(); pos != coll.end(); ++pos)
	{
		cout << setw(15) << pos->first.c_str() << " "
			<< pos->second << endl;
	}
	cout << endl;
}


本例摘自:C++标准库P212