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

时间:2016-06-09 10:15:42

标签: c++ priority-queue

您好我需要创建一个包含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
}

是否有可能以某种方式获得此结果,并且我必须定义比较器函数?

1 个答案:

答案 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的显式拷贝构造函数。