我定义了一个类,然后将指针保存到priority_queue中的Foo,并使用我定义的cmp函数。
但如果cmp-funtion调用function-object,则会发生错误:
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;
}
functione-object正常运行。
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;
}
答案 0 :(得分:2)
您需要使用您希望用作比较的函数构建que
变量。
#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;
}