关于std::map的第三个参数

1、map的其中一个构造函数有第三个参数,可以直接定义map的key值得排序规则,

默认为std::less,即按“<”运算符进行排序

map<string, int> mapWord = { { "father", 1 },{ "mother", 4 },{ "daughter", 5 } };

等价于:

map<string, int, std::less<string>> mapWord2 = { { "father", 1 },{ "mother", 4 },{ "daughter", 5 } };

 

2、如果想把key值按从大到小的顺序排序,改为:

map<string, int, std::greater<string>> mapWord2 ;

 

3、使用比较函数也可以

bool compFunc(const string& a, const string& b)
{
  return a.compare(b) > 0;
}

map <string, int, decltype(compFunc)*> mapWord3;  //注意*号的存在。比较操作类型必须为函数指针类型

 

4、使用lambda表达式

auto fc = [](const string& str1, const string& str2) {return str1.compare(str2) > 0; };
map <string, int, decltype(fc)*> mapWord4;  //同样要使用使用函数指针

 

5、如果key的类型是自定义的类或结构体,可以重写“<运算符”

class A{

    ...

     bool operator <(const A& d)

    {

      return count > d.count; 
    }


    int count;

}

map <A, int> mapA;  //关键字将会从大向小排列

 

转载于:https://www.cnblogs.com/pjl1119/p/8179780.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值