C++ priority_queue与自定义比较器并删除任何项目
C++ priority_queue with custom comparator and removal of any item
我正在研究一个具有最小堆的解决方案,除了自定义比较器之外,还需要支持删除任何元素。完全自定义的堆 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>
{
...
};
相关文章:
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 删除字符串中具有相同值的任何相邻字母"pair"
- 从输入中删除重复项,而不使用任何数据结构
- 在不使用任何 STL 容器的情况下删除重复项
- C++ priority_queue与自定义比较器并删除任何项目
- 为什么当我不移动任何东西时,clang 会抱怨删除移动 ctor?
- 是否有任何情况下,具有已删除CTOR的课程可能有用
- 使用 C 字符串和指针.删除除小写和空格以外的任何字符
- 无法通过 .erase 从矢量 c++ 中删除任何内容
- 一个可以指向任何地方的指针,如何确定是否可以安全地调用"删除"
- 调用不访问已删除对象中的任何类成员的类方法是否安全
- 删除“按任何键” ..&quot.从VS C 控制台应用程序
- Unix 套接字挂在 recv 上,直到我在任何地方放置/删除断点
- 从数组中删除元素,而无需在 c++ 中内置任何函数
- 如何添加到此代码中,以便它打印"b"而不删除任何内容?
- 如何在不删除任何字符的情况下将字符从字符串中的某个位置移动到其最前面
- 在新的 c++11 项目中,我是否应该默认删除任何操作
- 如何在没有STL的情况下从2d阵列中删除任何未填充的插槽
- 从链表中删除节点会运行,但不会删除任何内容
- 为什么可以删除任何函数,而只能删除默认的特殊成员函数