如何从priority_queue中删除不在顶部的元素
How to remove element not at top from priority_queue?
在我的程序中,我需要从优先级队列中删除不在顶部的元素。这能做到吗?如果没有,请建议一种方法,而不是创建自己的堆。
标准priority_queue<T>
可以通过继承进行自定义。它具有受保护的成员c
和comp
,这些成员可以在后代类中引用。
template<typename T>
class custom_priority_queue : 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()) {
return false;
}
if (it == this->c.begin()) {
// deque the top element
this->pop();
}
else {
// remove element and re-heap
this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp);
}
return true;
}
};
void main()
{
custom_priority_queue<int> queue;
queue.push(10);
queue.push(2);
queue.push(4);
queue.push(6);
queue.push(3);
queue.remove(6);
while (!queue.empty())
{
std::cout << queue.top();
queue.pop();
if (!queue.empty())
{
std::cout << ", ";
}
}
}
输出:
10, 4, 3, 2
最好的解决方案是使用 std::set。集合提供了允许它用作最小/最大堆(或优先级队列)的方法。
std::set<int> pq;
//accessing the smallest element(use as min heap)
*pq.begin();
//accessing the largest element (use as max heap)
*pq.rbegin();
此外,集合还允许随机删除。
//to delete the integer '6'
auto it = pq.find(6);
pq.erase(it);
处理
priority_queue STL 删除的一个巧妙的小技巧 - 使用另一个priority_queue,比如del_pq
。继续插入所有删除值。当您从原始优先级队列中弹出值时,请检查del_pq
顶部,看看我们是否要删除它。如果匹配,请从原始priority_queue中删除该值。
此方法实现了一种延迟删除原始优先级队列中的值的方法。可以占用两倍的内存,但平均删除和插入仍然O(logN)
。
Pradip 和 MASh 牺牲了时间来实现删除操作。但是,如果时间复杂度对您很重要,我建议您使用哈希min_heap。哈希表存储值指针,指针指向min_heap。这意味着您可以花费 O(1) 时间来查找 min_heap 中的值,并花费 O(log(n)) 来删除(筛选或筛选)元素。
请注意 ,以下方法可以解决问题,但不是优化的解决方案。有关优化方法,请查看其他答案。
让你要删除priority_queue<type> Q
中的第 5 个元素。然后你可以这样做,就像:
vector<type> tempQ;
int i = 0;
int n = 5;
type t;
// backup n-1 items
while(i < n-1)
{
tempQ.push_back(Q.top());
Q.pop();
i++;
}
// remove the nth item
Q.pop();
// restore the backed up items
i = 0;
while(i < n-1)
{
t = tempQ[i++];
Q.push(t);
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何实现唯一 id 队列,其中元素可以在 C++ 中"bumped"到顶部?
- 无法获取已填充堆栈<char>的顶部元素
- 将顶部堆栈元素传输到第二个堆栈的第一个
- 如何获得向量队列的前部或顶部元素
- 如何从priority_queue中删除不在顶部的元素
- 如何在不重新建立堆不变量的情况下有效地替换堆的顶部元素
- 排序的数据结构,用于按顺序迭代、有序推送和删除(仅从顶部开始 N 个元素)
- 使用堆查找地图的顶部元素