Home > Enterprise >  Static priority queue of pointers in c
Static priority queue of pointers in c

Time:11-22

I have a class foo, and inside the class, I need a static priority queue bar that holds pointers to some number of foo objects, and the foo object also has a private member buzz that will hold the weight of the objects when compared.

So far, I have tried the following:

class foo{
private:
    // some stuff
    int buzz;
public:
    // some more stuffs
    static bool compare (const foo* l, const foo* r){
        return l->buzz < r->buzz;
    }
    static std::priority_queue<foo*, std::vector<foo*>, foo::compare> bar;
};

But I get this error in clang:

template argument for template type parameter must be a type

I read this and this but could not get my head around how to do it or what i was doing wrong.

CodePudding user response:

As you can see in the std::priority_queue documentation, the 3rd template argument Compare is:

A Compare type providing a strict weak ordering.

A function pointer (like you used) cannot be used for the compare type.
One way to supply a compare type is via a class with opertor() (preferably a const one):

#include <queue>

class foo {
private:
    int buzz;
public:
    // Our compare type:
    struct Compare
    {
        bool operator()(const foo* l, const foo* r) const 
                       { return l->buzz < r->buzz; }
    };

    //--------------------------------------------------vvvvvvvvvvvv-----
    static std::priority_queue<foo*, std::vector<foo*>, foo::Compare> bar;
};
  • Related