您的位置:首页 > 编程语言 > C语言/C++

C++ map 自定义排序规则

2012-09-27 00:03 190 查看
map的模板定义第三个参数,即为我们的排序规则。

默认是试用std::less<>排序的,对key排序,而不是value。

如果我们想对key (string)不区分大小写进行排序,可以这样写。

#include "stdafx.h"
#include <cctype>
#include <map>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

// 提供自定义的排序
struct CCaseInsensitive{
bool operator() (const string& str1, const string& str2) const{
string str1NoCase(str1);
string str2NoCase(str2);
transform(str1.begin(), str1.end(), str1NoCase.begin(), tolower);
transform(str2.begin(), str2.end(), str2NoCase.begin(), tolower);
return str1NoCase < str2NoCase;
}
};

//定义StrMapNoCase
typedef map<string, string, CCaseInsensitive> StrMapNoCase;
typedef StrMapNoCase::value_type MapValue;
typedef map<string, string> StrMap;

int main(){
StrMapNoCase map1;
map1.insert(MapValue("John", "5214563"));
map1.insert(MapValue("tom", "5214563"));
map1.insert(MapValue("LiYang", "98874745"));
map1.insert(MapValue("ABC", "98874745"));

StrMap map2;
map2.insert(MapValue("John", "5214563"));
map2.insert(MapValue("tom", "5214563"));
map2.insert(MapValue("LiYang", "98874745"));
map2.insert(MapValue("ABC", "98874745"));

StrMapNoCase::iterator iter1 = map1.find("abc");
if( iter1 != map1.end())
cout << (*iter1).first <<endl;

StrMap::iterator iter2 = map2.find("abc");
if(iter2 != map2.end())
cout << (*iter2).first <<endl;
else
cout << "map2中没有找到abc" << endl;

system("pause");
return 0;
}


运行结果:

ABC

map2中没有找到abc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ string iterator struct less