Providing a third argument to a priority_queue's compare function

110 Views Asked by At

I've been trying to figure out a way to provide some extra information to my priority queue's compare function. Let's assume I have the following:

class MyClass
{
    class IntCompare
    {
        bool operator() (int lhs, int rhs)
        {
            //Do stuff with m_MyMap
        }
    }

    std::map<int, bool> m_MyMap;
    std::priority_queue <int, std::vector<int>, IntCompare> m_MyPriorityQueue;  
};

I'd like to be able to access m_MyMap from inside the IntCompare's operator() function. m_MyMap will be modified throughout the lifetime of this object so passing in a copy of this isnt an option. I've tried creating a constructor for IntCompare which takes a pointer, and in the constructor of MyClass, I've tried passing in m_MyMap via the initializer list:

IntCompare(std::map<int, bool>* map) : m_MapPointer(map) {} //assuming m_MapPointer is defined in IntCompare.
...
MyClass() : m_MyPriorityQueue(IntCompare(&m_MyMap)) {}

but this doesnt seem to work. Was hoping to ask for some help on figuring out if there is a way to do this, or if I need to think of a different approach.

1

There are 1 best solutions below

10
Ted Lyngmo On BEST ANSWER

A possible way forward: First, make your IntCompare constructor and operator() public and then ...

Comments inline:

class MyClass {
    class IntCompare {
    public:
        // the comparator constructor takes the map as argument and
        // stores a pointer to it:
        IntCompare(std::map<int, bool>& mm) : m_mm(&mm) {}

        bool operator()(int lhs, int rhs) const { // const qualified

            // Do stuff with m_MyMap, via m_mm-> ...
            return lhs < rhs;
        }

    private:
        std::map<int, bool>* m_mm;
    };

public:
    // ...

private:
    std::map<int, bool> m_MyMap;

    // initialize your priority_queue's comparator with m_MyMap:
    std::priority_queue<int, std::vector<int>, IntCompare>
        m_MyPriorityQueue{m_MyMap};
};