c++ - 函数对象与函数指针的区别??
迷茫
迷茫 2017-04-17 15:18:00
0
3
775

我定义了一个类,然后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;
}

请问这是为什么??

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
迷茫

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.

PHPzhong

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 *。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template