您好我需要创建一个包含priority_queue字段的类,其比较器函数需要访问该类中的另一个字段。总之,我需要写这样的东西:
class A
{
B foo;
priority_queue<C,vector<C>,comparator> bar;
}
比较器定义类似于
bool comparator(const C& c1, const C& c2)
{
//compute the boolean value using c1, c2 and the field foo
}
是否有可能以某种方式获得此结果,并且我必须定义比较器函数?
答案 0 :(得分:0)
执行此操作有两个步骤。
首先,比较器需要一个构造函数来保存对A
class comparator {
A &a;
public:
comparator(A &a_arg) : a(a_arg)
{
}
bool operator()(const C &first, const C &second) const
{
// The comparator can use "a" to access the contents of the
// A class.
}
};
第二步是A
的构造函数使用从priority_queue
构造的显式comparator
初始化其*this
成员:
A::A() : bar(comparator(*this))
{
// ...
}
注意:请记住比较器中对*this
的引用。如果复制了A
的实例,则this
引用在副本中无效。您的A
类应该具有delete
d拷贝构造函数,或者相应地初始化拷贝构造的A
priority_queue
的显式拷贝构造函数。