Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading