Search code examples
c++priority-queue

remove a element in priority_queue minheap


I am trying to implement remove function to the priority_queue STL but for minheap implementation it throws an error.

#include <iostream>
#include <stdc++/bits>

using namespace std;
template<typename T>
class custom_priority_queue : public priority_queue<T, vector<T>>
{
  public:

      bool remove(const T& value) {
        auto it = find(this->c.begin(), this->c.end(), value);
        if (it != this->c.end()) {
            this->c.erase(it);
            make_heap(this->c.begin(), this->c.end(), this->comp);
            return true;
       }
       else {
        return false;
       }
 }
};

void findmedian(int arr[], int n, int k)
{
    custom_priority_queue<int> maxheap;

This works fine but if i try to create min heap like below

    custom_priority_queue<int , vector<int>, greater<int>> minheap;

It throws an error

    Too many template arguments for class template 'custom_priority_queue'

Solution

  • custom_priority_queue only has a single template argument T. So you can only use custom_priority_queue<T>, more parameters are invalid.

    You need to change your declaration to:

    template<typename T, Queue = std::vector< T >, Compare = std::less< T > >
    class custom_priority_queue : public priority_queue<T, Queue, Compare >
    {
    

    Deriving from standard library classes is generally not a good idea, encapsulation is a better approach.