Search code examples
c++templatesfunctor

std::priority_queue contain struct with functor that contains a state


There exists two excellent answers to questions about std::priority_queue containing struct/class:

What if I need those compare structs to hold a state, such as an object of ofstream?

Thanks in advance.


Solution

  • You can define compare functor with constructor requiring state:

        struct Compare
        {
            State state;
    
            Compare(State state)
                : state(state)
            {
            }
    
            bool operator()(const Item& a, const Item& b)
            {
                ... // use state
            }
        };
    

    and pass its instance constructed with required state to priority_queue constructor:

        priority_queue<Item, std::vector<Item>, Compare> queue(Compare(state));