0%

C++语言STL中使用谓词的方法

  • C++的STL模板库中很多容器都需要谓词,比如有序集合set等,此时定义谓词主要有两种方式

    使用重载运算符作为谓词

  • 新建一个struct
    typedef struct compFun
    {
    bool operator()(const shared_ptr<test>& a, const shared_ptr<test>& b) const
    {
    return a->id>b->id;
    }
    /* data */
    };
  • 传参的时候使用
    set<shared_ptr<test>, compFun> setTest;
  • 上面不需要显式的传入比较函数,因为类型已经包含了比较函数

    使用lambda表达式作为谓词

  • 定义
    function<bool(const test&, const test&)> funComp = [](const test& a, const test& b)
    {
    cout<<"comparing!"<<endl;
    return (a.id)<(b.id);
    };
  • 使用
    set<test, function<bool(const test&, const test&)>> setTest(funComp);
  • 注意,不显式的传入lambda表达式的时候不能向set中插入超过一个元素,否则会因为触发比较而报错what(): bad_function_call
  • 根据leetcode的测试,使用内联函数作为STL标准库的函数的谓词,会比使用static inline但是功能相同的函数作为谓词快一些,比如
    static inline bool cmp(int& a, int& b)
    {
    return a>b;
    }
    // 更快的方法是
    auto cmp = [](int a, int b)->bool{return a>b;};
  • 此处注意使用
    auto cmp = [](int a, int b)->bool{return a<b;};
    // 以下二者结果不同,混用可能得到类型错误
    decltype(cmp);function<bool(int, int)>;
  • 注意对于cpp的优先级队列而言,使用大于号作为比较符得到的是最小堆,小于号是最大堆
  • 优先级队列在使用谓词之前必须先指定存储的数据结构,比如如下代码
    auto cmp = [](int a, int b)->bool{return a<b;};
    priority_queue<int, vector<int>, function<bool(int, int)>> pq(cmp);