c++ - 优先级队列未正确比较 C++

标签 c++ priority-queue

我正在尝试创建一个由 int、char 对组成的优先级队列,该队列为我提供具有更大 int 的对,但我的代码无法正常工作。我做错了什么?

这是我的比较类:

class Compare
{
public:
    bool operator() (pair<int, char>a, pair<int, char>b)
    {
        return a.first > b.first;
    }
};

这是我的优先队列:

priority_queue<pair<int, char>, vector<pair<int, char>>, Compare> party;

但是如果我执行代码:

party.push(make_pair(2, 'A'));
party.push(make_pair(3, 'B'));
cout<<party.top().first;

它返回 2,而不是 3。如何修复优先级队列的实现?

最佳答案

Geordi La Forge 将使用的相同修复方法:反转极性:

bool operator() (const pair<int, char> &a, const pair<int, char> &b) const
{
    return a.first < b.first;
}

比较函数总是实现严格的弱排序,也就是逻辑 <手术。但是priority_queue ,根据定义,gives you the largest value in the priority queue, first :

... provides constant time lookup of the largest (by default) element,

但是比较函数仍然是严格的弱排序:

A Compare type providing a strict weak ordering.

有点反直觉,但过了一会儿,它确实有道理......

P.S.:比较函数应该是const功能,并采取const参数,为了提高效率,如我的示例所示;但这是一个额外的细节。

关于c++ - 优先级队列未正确比较 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41369074/

相关文章:

c++ - 如何在 QT 项目的输出构建中包含一个 json 文件

c++ - 如何以可移植的方式在 C++ 中删除名称为 wchar_t 类型的文件?

c++ - 有没有办法从用户模式调用 Windows Native API 函数?

python - 不可排序的类型 : Vertex() < Vertex()

c++ - 使用自制的 `std::priority_queue` 初始化 `std::Compare` 时避免使用模板?

c++ - 只允许特定的 `typedef` 作为函数参数

c++ - 初始化函数指针时出现问题?

c++ - STL 优先队列 : When/How Does Resorting Occur?

c++ - Bool 运算符重载不起作用