priority_queue class 字段使用访问另一个 class 字段的比较器

priority_queue class field using a comparator that access another class field

你好,我需要创建一个 class,其中包含一个 priority_queue 字段,其比较函数需要访问 class 中的另一个字段。简而言之,我需要写这样的东西:

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
}

是否可以通过某种方式获得此结果以及我必须在哪里定义比较器函数?

有两个步骤可以做到这一点。

首先,您的比较器需要一个构造函数来保存对 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 的构造函数使用从 *this:[=24= 构造的显式 comparator 初始化其 priority_queue 成员]

A::A() : bar(comparator(*this))
{
   // ...
}

注意:请记住比较器中对 *this 的引用。如果 A 的实例被复制,this 引用在副本中将无效。你的 A class 应该有一个 deleted 复制构造函数,或者一个显式复制构造函数来初始化复制构造的 A priority_queue,相应地。