C++ map 自定义排序规则
2012-09-27 00:03
190 查看
map的模板定义第三个参数,即为我们的排序规则。
默认是试用std::less<>排序的,对key排序,而不是value。
如果我们想对key (string)不区分大小写进行排序,可以这样写。
运行结果:
ABC
map2中没有找到abc
默认是试用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
相关文章推荐
- 批量修改数据库排序规则,含主外键
- 关于如何实现接口IComparer以实现自己需要的排序规则
- 修改sqlserver2008数据库的排序规则 (转)
- Microsoft SQL Server 2005的排序规则冲突解决(转)
- [MSSQL]排序规则的 中文版MSSQL下开发的存储过程在布署到英文MSSQL时的一个运行错误
- SQL Server数据库的排序规则
- 字符集与排序规则
- Oracle 排序规则
- SQL collate(排序规则)设置。
- SQLServer陷阱(三) 字符串相等与排序规则
- 无法解决 equal to 操作的排序规则冲突
- Cxgrid获取选中行列,排序规则,当前正在编辑的单元格内的值
- Mysql中的排序规则utf8_unicode_ci、utf8_general_ci的区别总结
- 查询结果按自己的规则排序
- Google专利揭露Google新闻的排序规则
- mysql自定义排序规则函数——field()
- heap表按字符串和数值型排序规则
- 由于排序规则引起的“equal to”错误的解决方法
- Solr搜索的排序打分规则探讨
- SQLserver排序规则基本概念探索