C++ map 自定义排序规则

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值