C++ priority_queue与自定义比较器并删除任何项目

C++ priority_queue with custom comparator and removal of any item

本文关键字:删除 任何 项目 比较器 自定义 priority queue C++      更新时间:2023-10-16

我正在研究一个具有最小堆的解决方案,除了自定义比较器之外,还需要支持删除任何元素。完全自定义的堆 impl 是一种方法。但我想依靠 C++ STL 进行所需的操作。
C++文档和StackOverflow的答案指出我使用自定义类并重载自定义remove方法。我还在同一类中重载了自定义比较器。

template<typename T>
class custom_priority_queue_MinHeap : public std::priority_queue<T, std::vector<T>>
{
public:
bool remove(const T& value) 
{
auto it = std::find(this->c.begin(), this->c.end(), value);
if (it != this->c.end())
{
this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp);
return true;
}
return false;
}
bool operator()(const pair<int, int> &a, const pair<int, int> &b)
{
cout << "Custom comparator called" << endl;  <----------- Never called
return a.second > b.second;
}
};

自定义堆的使用如下所示:

custom_priority_queue_MinHeap<pair<int, int>> minHeap;
minHeap.push({0, 10});
minHeap.push({1, 5});
minHeap.push({2, 15});
while(!minHeap.empty())
{
pair<int, int> p = minHeap.top();
minHeap.pop();
cout << p.first << " " << p.second << endl;
}

在 Ideone 上运行时,minHeappush无法按预期工作。它在输出下方闪烁:

2 15
1 5
0 10    

正确的输出应该是:

1 5
0 10  
2 15      

从未调用()比较器过载,这似乎是罪魁祸首。元素按插入顺序弹出。有趣的是,remove功能工作正常。

问题:
是否可以完全依靠C++ priority_queue STL来实现所需的操作,即支持去除任何元素的定制比较器?如果是,在上述实现中我缺少什么吗?

感谢PaulMcKenzie为我指出正确的方向!问题是 STL 中的priority_queue是三个参数类。我的 impl 缺少第三个比较类参数。
下面的变化工作正常。Ideone link

class Comp
{
public:
bool operator()(const pair<int, int> &a, const pair<int, int> &b)
{
cout << "Custom comparator called" << endl;
return a.second > b.second;
}
};
template<typename T>
class custom_priority_queue_MinHeap : public std::priority_queue<T, std::vector<T>, Comp>
{
...
};