我定义了一个类,然后priority_queue中存放类并且使用自己定义的比较函数,但是如果比较函数传递的是函数指针就会发生崩溃:
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;
}
如果改为函数对象则正常:
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;
}
请问这是为什么??
It has been solved, thank you everyone, because when passing the function pointer, there is no initialization.
should be written like this:
priority_queue<Foo, vector<Foo>, decltype(cmp)* >que(cmp);
I think the function pointer requires you to pass a function name in the parameters of the constructor, because the pointer cannot be constructed by default. And
struct cmp
has a default constructor that can be constructed automatically, so you don’t need to pass it again.template <class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
Compare - A Compare type providing a strict weak ordering.
cmp要为一个class,而且不是class *。