Search code examples
c++priority-queue

priority_queue class field using a comparator that access another class field


Hello I need to create a class which contains a priority_queue field whose comparator function needs to access another field in the class. In short I need to write something like this:

class A
{
    B foo;
    priority_queue<C,vector<C>,comparator> bar;
}

where the comparator definition is something like

bool comparator(const C& c1, const C& c2)
{
    //compute the boolean value using c1, c2 and the field foo
}

Is it possible to obtain this result in some way and where I have to define the comparator function?


Solution

  • There are two steps to do this.

    First, your comparator needs a constructor that saves a reference to an instance of 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.
         }
    };
    

    And the second step is for A's constructor to initialize its priority_queue member using an explicit comparator that gets constructed from *this:

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

    Note: keep in mind the reference to *this in the comparator. If the instance of A gets copied, the this reference will not be valid in the copy. Your A class should have either a deleted copy-constructor, or an explicit copy-constructor that initializes the copy-constructed A priority_queue, accordingly.