学习了STL--map,然后通过下面的示例,将练习以下技巧:
1.如何使用map;
2.如何撰写和使用仿函数;
3.如何在执行期定义排序准则;
4.如何在“不在乎大小写”的情况下比较字符串;
示例代码:
//运用map,string并于执行期指定排序准则
#include<iostream>
#include<iomanip>
#include<map>
#include<string>
#include<algorithm>
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) {}//默认为normal
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()
{
RuntimeStringCmp normal_;//默认normal
StringStringMap coll1(normal_);//不加normal_即为默认
fillAndPrint(coll1);// 安插过程使用operator<,不区分大小写
RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
StringStringMap coll2(ignorecase);
fillAndPrint(coll2);// 安插过程使用operator<,区分大小写
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.c_str()<<endl;
}
cout<<endl;
}
运行结果:
运行结果分析:
1.coll1使用一个型别为RuntimeStringCmp的缺省仿函数,这个函数以元素的operator<来执行比较操作;
2.coll2使用一个型别为RuntimeStringCmp的仿函数,并以nocase为初值,而nocase会令这个仿函数以“大小写无关”模式来完成字符串的比较和排序。