zoukankan      html  css  js  c++  java
  • 关于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;  //关键字将会从大向小排列
  • 相关阅读:
    Visual Studio 中的 .NET Framework 类库
    泛型
    泛型
    事件
    基于事件的异步模式
    使用委托进行异步编程
    使用 IAsyncResult 调用异步方法
    异步编程设计模式
    演练:使用VS2010 C# 创作简单的多线程组件
    [转][MEF插件式开发] 一个简单的例子
  • 原文地址:https://www.cnblogs.com/pjl1119/p/8179780.html
Copyright © 2011-2022 走看看