Home  >  Q&A  >  body text

c++ - 函数对象与函数指针的区别??

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

请问这是为什么??

迷茫迷茫2761 days ago744

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 15:20:00

    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);

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:20:00

    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.

    reply
    0
  • PHPz

    PHPz2017-04-17 15:20:00

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

    reply
    0
  • Cancelreply