代码之家  ›  专栏  ›  技术社区  ›  Edmund Young

在C++优先级队列中使用静态成员函数作为比较器时发生地址清理器错误

  •  0
  • Edmund Young  · 技术社区  · 9 月前

    我在C++中使用priority_queue,在类中使用静态成员函数作为自定义比较器时遇到了问题。

    一个可重复的例子是:

    #include <bits/stdc++.h>
    using namespace std;
    
    class testClass {
    private:
        static bool comp(const int& a, const int& b) {
            return a > b;
        }
        priority_queue<int, vector<int>, decltype(&testClass::comp)> q;
    
    public:
        void push(int num) {
            q.push(num);
        }
    };
    
    int main() {
        testClass t;
        t.push(0);
        t.push(0);
        return 0;
    }
    

    第二个电话 push 导致错误。我认为这意味着成员功能 comp 不能被调用 q .

    但是,当我将成员函数更改为类外的lambda函数,然后用 decltype(comp) ,代码运行良好。

    有人能解释一下为什么静态成员函数会导致这个问题,为什么lambda方法会起作用吗?

    1 回复  |  直到 9 月前
        1
  •  1
  •   3CxEZiVlQ    9 月前

    问题不在于 你使用 静态构件用作比较器。问题是 你不用

    std::priority_queue<int, vector<int>, decltype(&comp)> q;
    

    比较器不会传递给构造函数,并且使用了一个默认构造(null)。

    您应该将比较器传递给构造函数

    std::priority_queue<int, vector<int>, decltype(&comp)> q{comp};
    

    我打赌SO上一定有重复的问题,但我找不到。