Search code examples
c++priority-queue

Custom ordering for std::priority_queue


I'm trying to make a program that has a std::priority_queue of objects. I want the queue to order the objects based on A::num. This is the code:

#include <iostream>
#include <queue>
#include <vector>

class A {
  public:
    int num;
    A (int n) {
        this->num = n;
    }
    ~A() {
        std::cout << "Deleting an A\n";
    }
};

struct Compare {
  bool operator()(const A* first, const A* second) {
      return first->num < second->num;
  }  
};

int main() {
    std::priority_queue AContainer(A*, std::vector<A*>, Compare);
    
    AContainer.push(new A(4));
    AContainer.push(new A(8));
    AContainer.push(new A(6));
    
    while (AContainer.size() < 0) {
        A* del = AContainer.top();
        delete del;
        del = nullptr;
        AContainer.pop();
    }
    return 0;
}

The compiler returns an error, however I'm not sure why or where it is referring to, or how to fix it:

error: deduced class type 'priority_queue' in function return type
   24 |     std::priority_queue AContainer(A*, std::vector<A*>, Compare);
      |                         ^~~~~~~~~~
In file included from /usr/include/c++/11/queue:64,
                 from /tmp/HvPOYonaOt.cpp:3:
/usr/include/c++/11/bits/stl_queue.h:456:11: note: 'template<class _Tp, class _Sequence, class _Compare> class std::priority_queue' declared here
  456 |     class priority_queue
      |           ^~~~~~~~~~~~~~

If you could help me out with this that would be great.


Solution

  • A*, std::vector<A*>, Compare are types that you need to supply to the template parameters of std::priority_queue, not values you supply to a constructor.

    std::priority_queue<A*, std::vector<A*>, Compare> AContainer;
    

    See it on coliru