关于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;  //关键字将会从大向小排列

猜你喜欢

转载自blog.csdn.net/usstmiracle/article/details/79877330