zoukankan      html  css  js  c++  java
  • 运用map并于执行期指定排序准则

    该例展示以下技巧:

    • 如何使用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

  • 相关阅读:
    PhpStorm中如何调整字体大小
    PhpStorm-2017.1.2破解步骤
    Eclipse/MyEclipse 最最常用的快捷键
    Invalid result location value/parameter
    系统重装--相关问题
    喜马拉雅||亲爱的,慢慢行走
    QQ聊天界面模式切换
    myeclipse中如何修改项目的名称
    软考-程序设计语言基础(编译原理)
    软考-计算机组成原理、体系机构与网络安全
  • 原文地址:https://www.cnblogs.com/ggzone/p/4052437.html
Copyright © 2011-2022 走看看