c++ - 如何将 priority_queue 与类实例的非静态比较方法一起使用?

标签 c++ c++11 std priority-queue custom-compare

假设我有一个像这样的简单类:

class Test {
public:
  Test(int reference) { m_reference = reference; }
  void feed(int x) { m_data.push_back(x); }
  int get() { return m_data.front(); }
private:
  int m_reference;
  std::vector<int> m_data;
};

而不是 std::vector , 我想将值输入 std::priority_queue .我不想返回 .front() 值,而是想 .get() .top() priority_queue 基于自定义比较函数。假设此自定义比较计算为值与实例 reference 之间的绝对差异。

不知道如何在我的类属性中声明std::priority_queue

我试过:

bool compare(int a, int b) {
    return std::abs(a - m_reference) < std::abs(b - m_reference);
}

然后:

std::priority_queue<int, std::vector<int>, decltype(&Test::compare)> m_priority;

我也像这样尝试使用 std::function 但这会引发多个错误:

std::function<bool(int a, int b)>> pq([this](int a, int b){
   return std::abs(a - m_reference) < std::abs(b - m_reference);
});

但这行不通(请参阅 Repl.it)。

知道如何解决这个问题吗?

最佳答案

我设法通过使用使其工作:

std::function<bool(int,int)> comp = [this](int a, int b) { return std::abs(a - m_reference) < std::abs(b - m_reference); };

Test(int reference) : m_priority(comp) { m_reference = reference; }

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

您还需要#include <functional>

如果我没有正确理解你的问题,这就是你想要的?

您还可以将比较器设置为 struct或其他东西并使用它代替 std::function如果您不想要任何性能缺陷。

更新:

带有 struct 的版本看起来像这样(您可以传递一个 this 指针而不是对 int 的引用,或者您喜欢它):

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>

class Test {
public:
    Test(int reference) : m_priority(comp(m_reference)) { m_reference = reference; }
    void feed(int x) { m_data.push_back(x); }
    int get() { return m_priority.top(); }

    struct comp {
        int& reference;
        comp(int& ref) : reference(ref) {}
        bool operator()(int a, int b) { return std::abs(a - reference) < std::abs(b - reference); };
    };

private:
    int m_reference;
    std::vector<int> m_data;
    std::priority_queue<int, std::vector<int>, comp> m_priority;
};

关于c++ - 如何将 priority_queue 与类实例的非静态比较方法一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767011/

相关文章:

c++ - 在 C 的不同函数中共享打开的文本文件

c++ - C++中最大的数据类型是什么

相当于 Boost has_dereference 的 C++11 std

c++ - 使用 a<32> 将 bitset<a> 转换为 signed int

c++ - 如何通过id获取线程对象?

c++ - "using namespace std"有什么用?

c++ - 将对象作为异常 : Keeping the same Constructor of parent Exception class 抛出时出现问题

c++ - vector<struct> 的自定义迭代器

c++ - constexpr 函数和硬编码参数

c++ - "Forward-unbreakable"访问器类模板 [C++]