如何使用优先级队列STL的对象? [英] How to use the priority queue STL for objects?

查看:137
本文介绍了如何使用优先级队列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> > 

更大的工作原理是什么?

How does the greater work?

推荐答案

您需要为存储在队列中的类型提供有效的严格弱排序比较, Person 在这种情况下。默认是使用 std :: less< T> ,它解析为等同于 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< Person> 。例如,

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< Person> 作为比较器,这将使用等效的 operator> ,并且具有创建具有优先级WRT的队列的效果的默认情况的效果。这将需要存在可以在两个 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.

这篇关于如何使用优先级队列STL的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆