C++优先级队列中的运算符重载或比较函数

Bar*_*ach 10 c++ performance stl

我正在用C++编写一个程序,我想定义一个类的优先级队列.我需要它来通过类成员变量之一来比较对象.我使用了一个运算符<overload,但我知道有另一种方法可以实现这个目标 - 使用队列定义定义的特殊函数.哪种方式更好,更美观,更有效?以及如何编写这样的功能?

我这样做了:

#include <iostream>
#include <queue>
using namespace std;

class Human {

    public:
        string name;
        int age;
        Human(string name, int age);
};

Human::Human(string name, int age) : name(name), age(age) {}

bool operator<(Human a, Human b) {return a.age < b.age ? true : false;}

int main() {

    Human p1("Child",5);
    Human p2("Grandfather",70);
    Human p3("Older son",20);
    Human p4("Father",40);
    Human p5("Younger son",10); 

    priority_queue<Human> Q;

    Q.push(p1);
    Q.push(p2);
    Q.push(p3);
    Q.push(p4);
    Q.push(p5);

    while(!Q.empty()) {

        cout << "Name: " << Q.top().name << ", age: " << Q.top().age << endl;
        Q.pop();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Use*_*ess 8

样式

如果您的类型具有内在的"自然"排序,则使用内置运算符表达它是合理的.

如果排序因您使用类型的方式而异(例如,您有一个按年龄排序的人类集合,一个按高度排序,一个按IQ排序),那么说明排序是容器的属性而不是类型.


履行

您可以编写自由函数,或者如果需要状态则使用函子.

请注意,这些都与内置运算符的内联完全一样,因此速度没有固有的差异(编译器可能更难以证明函数指针是内联的,因此通常首选仿函数).

struct OrderByAge
{
    bool operator() (Human const &a, Human const &b) { return a.age < b.age; }
};
typedef std::priority_queue<Human, std::vector<Human>, OrderByAge> age_queue;
Run Code Online (Sandbox Code Playgroud)