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

来源:互联网 发布:linux给用户授权 编辑:程序博客网 时间:2024/05/16 13:48
#include<iostream>
#include<iomanip>
#include<map>
#include<string>
#include<algorithm>
using namespace std;


//function object to compare strings
//allows you to set the comparison criterion at runtime and compare case insensitive
class RuntimeStringCmp{
public:
//constants for the comparison criterion
enum cmp_mode{normal,nocase};
private:
//actual comparison mode
const cmp_mode mode;
//auxiliary function to compare case insensitive
static bool nocase_compare (char c1,char c2)
{
return toupper(c1) <toupper(c2);
}
public:
//constructor: initializes the comparison criterion
RuntimeStringCmp(cmp_mode m = normal):mode(m){
}
//the comparison
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);
}
};


// container type:map with sting keys sting values
//the special comparison object type


typedef map<string, string ,RuntimeStringCmp> StringStringMap;


//function that fills and prints such containers
void fillAndPrint(StringStringMap& coll);


int main()
{
//create a constainer with the default comparison criterion
StringStringMap coll1;
fillAndPrint(coll1);
//create an object for case-insensitive comparisons
RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
//create a container with the case-insensitive
//comparisons criterion
StringStringMap coll2(ignorecase);
fillAndPrint(coll2);
return 0;
}
void fillAndPrint(StringStringMap & coll)
{
//fill insert elements in random order
coll["Deutschland"] = "Germany";
coll["deutsch"] = "German";
coll["Haken"] = "snag";
coll["arbeitem"] = "work";
coll["gehen"] = "go";
coll["Unternehmen"] = "enterprise";
coll["Hund"] = "dog";
coll["unternehmen"] = "undertake";
coll["gehen"] = "walk";
coll["Bestatter"] = "undertaker";


//print elements
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;

}


其中main()构造出两个容器,并对他们调用fillAndPringt().这个函数以相同的元素值填充上述容器,然后打印其内容。两个容器的排序准则不同:

1、coll1使用一个型别为RuntimeStringCmp 的缺省仿函数。这个仿函数以元素的operator<来执行比较操作。

2、coll2使用一个型别为RuntimeStringCmp的仿函数,并以nocase为初值。nocase会令这个仿函数以“大小写无关”模式来完成字符串的比较和排序