-1

i defined a class, then save the pointer to Foo in the priority_queue, and use the cmp-function that i defined.

but if the cmp-funtion calls the function-object, an error occurs:

class Foo
{
    friend bool cmp(Foo *, Foo *);
public:
    Foo() = default;
    Foo(int x):val(x) {}
private:
    int val;
};
bool cmp(Foo *a, Foo *b)
{
    return a->val < b->val;
}
int main()
{
    priority_queue<Foo*, vector<Foo*>, decltype(cmp)*> que;
    que.push(new Foo(5));
    que.push(new Foo(6));
    return 0;
}

the functione-object runs normally.

class Foo
{
    friend struct cmp;
public:
    Foo() = default;
    Foo(int x):val(x) {}
private:
    int val;
};
struct cmp
{
    bool operator()(Foo *a, Foo *b)
    {
        return a->val < b->val;
    }
};
int main()
{
    priority_queue<Foo*, vector<Foo*>, cmp> que;
    que.push(new Foo(5));
    que.push(new Foo(6));
    return 0;
}
Wonter
  • 293
  • 1
  • 5
  • 15
  • the IDE is code::blocks – Wonter Jan 27 '17 at 04:52
  • 1
    "an error occurs"? Really? – John Zwinck Jan 27 '17 at 05:19
  • not compile error – Wonter Jan 27 '17 at 05:44
  • Default-initialized pointer-to-function has the value of `nullptr`. Default-initialized instance of `struct cmp` is a valid instance. `decltype(cmp)` is simply `bool(Foo *a, Foo *b)` - "some function taking two `Foo*` and returning a `bool`". Nothing connects this to a particular function named `cmp`. Similarly, `decltype(42) x;` is equivalent to `int x;` - it doesn't magically give `x` a value of `42`. – Igor Tandetnik Jan 27 '17 at 06:00

1 Answers1

2

You need to construct your que variable with the function you wish to use as a comparison.

#include <vector>
#include <queue>

using namespace std;

class Foo
{
    friend bool cmp(Foo*, Foo*);
public:
    Foo() = default;
    Foo(int x):val(x) {}
private:
    int val;
};
bool cmp(Foo* a, Foo* b)
{
    return a->val < b->val;
}
int main()
{
    //                                                     vvv
    priority_queue<Foo*, vector<Foo*>, decltype(cmp)*> que(cmp);
    que.push(new Foo(5));
    que.push(new Foo(6));

    return 0;
}
Gambit
  • 954
  • 9
  • 15