Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete element from priority queue in c++ stl

Tags:

c++

Is i have a priority queue with declaration

priority_queue<<Node>,vector<Node>,myComp> openQ

i am inserting node objects into it. but at some time i have to delete the element from it. (not to remove the top element)

Currently to delete it i am popping the element and putting it in array. if the top most element is desired then expect it i push other elements in array.

This is like linear search and delete. I know its not efficient and i am looking for some better ways

like image 856
harshit Avatar asked Sep 26 '09 23:09

harshit


People also ask

How do I remove a specific item from a priority queue?

The remove() method of PriorityQueue class of java. util package is used to remove a particular element from a PriorityQueue.

How do I remove a max element from a priority queue?

remove() - To remove an element from the max priority queue, first we need to find the largest element using findMax() which requires O(n) time complexity, then that element is deleted with constant time complexity O(1). The remove() operation requires O(n) + O(1) ≈ O(n) time complexity.

Can we delete a particular element from priority queue in C++?

CPP. pop() function is used to remove the top element of the priority queue.


2 Answers

priority_queue class is designed for using as queue with priorities. And it designed to remove elements with pop function. If you want to get different behavior you should use different class. For instance, std::map.

If you're ready to manually control a consistence of the queue you may take a look on std::make_heap. It's easy to create a max-heap with it. But in this case you need to manually rebuild a queue each time you want to remove an element.

like image 104
Kirill V. Lyadvinsky Avatar answered Sep 27 '22 00:09

Kirill V. Lyadvinsky


std::set are orderd and can erase elements by value. the underlying datastructure is a binary search tree, thats why its cheaper to erase elements by value.

a priority queue would have to linearly search through the queue, so its possible but just not very efficient, thats why they didnt include it.

like image 45
ColacX Avatar answered Sep 25 '22 00:09

ColacX