Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element not at top from priority_queue?

In my program I need to delete an element from a priority queue that is not at the top. Can that be done? If not, please suggest a way to do so except creating your own heap.

like image 296
ishan3243 Avatar asked Oct 19 '13 15:10

ishan3243


People also ask

Can I remove an element from priority queue C ++?

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

Can you remove an element from the middle of a Queue?

You can use an index that contain the position of each element, and after if you want delete an element you use his position v(i). There are a lot of method, dependig by your algorithms. If you need to perform operations on elements in the middle, you need a List, not a Queue. It's conceptually wrong to do otherwise.


1 Answers

The standard priority_queue<T> can be customized through inheritance. It has protected members c and comp that can be referenced in a descendant class.

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()) {             this->c.erase(it);             std::make_heap(this->c.begin(), this->c.end(), this->comp);             return true;        }        else {         return false;        }  } };  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 << ", ";       }    }   } 

Output:

10, 4, 3, 2

like image 85
alexm Avatar answered Oct 09 '22 14:10

alexm