jeudi 26 janvier 2017

the differences between function-object and function-pointer?

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

Aucun commentaire:

Enregistrer un commentaire