如何对对象使用优先队列 STL?

2022-01-07 00:00:00 c++ stl
class Person
{
public:
    int age;
};

我想将 Person 类的对象存储在优先级队列中.

I want to store objects of the class Person in a priority queue.

priority_queue< Person, vector<Person>, ??? >

我想我需要为比较的东西定义一个类,但我不确定.

I think I need to define a class for the comparison thing, but I am not sure about it.

此外,当我们写作时,

priority_queue< int, vector<int>, greater<int> > 

更大的工作如何?

推荐答案

您需要为存储在队列中的类型(在本例中为 Person)提供有效的严格弱排序比较.默认使用 std::less,它解析为与 operator< 等效的内容.这依赖于它自己的存储类型.所以如果你要实施

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

它应该可以在没有任何进一步更改的情况下工作.实施可能是

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

如果类型没有自然的小于"比较,提供您自己的谓词会更有意义,而不是默认的std::less.例如,

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

然后像这样实例化队列:

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

关于使用 std::greater 作为比较器,这将使用等效于 operator> 并具有创建具有优先级的队列的效果倒置 WRT 默认情况.它需要一个 operator> 可以对两个 Person 实例进行操作.

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

相关文章