roulette01
roulette01

Reputation: 2462

Custom comparer for priority_queue object in a class

I have a class that's structured like the following skeleton code.

class custom
{
private:
  struct info
  {
    // define some stuff
  };
  std::priority_queue<info, vector<info>, custom_comparer_t> pq;
}

I am wondering if there's a standard for how the custom_comparer_t in this case should be defined? Would it be best to use a lambda function, a functor, or perhaps overload the < or > operator in info?

Upvotes: 0

Views: 91

Answers (1)

Ghasem Ramezani
Ghasem Ramezani

Reputation: 2888

std::priority_queue template parameters according to cppreference:

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

The Compare template parameter of std::priority_queue must meet the Compare concept requirements. And std::priority_queue couldn't use the T::operator()() because:

  1. It would break the other STL <algorithm> functions.
  2. T could be a POD type or a user defined types and the result will be in a complex implementation of std::priority_queue.

And of curse, you could use a functor for the Compare:

class custom {
 private:
  struct info {
    // define some stuff
    bool operator()(info const&, info const&) const {
      return false;
    }
  };

 private:
  using custom_comparer_t = info;
  std::priority_queue<info, std::vector<info>, custom_comparer_t> pq;
};

Upvotes: 3

Related Questions