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

时间:2012-12-09 18:19:46

标签: c++ stl performance

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

我做了如下:

#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;
}

3 个答案:

答案 0 :(得分:8)

风格

如果您的类型具有内在的“自然”排序,则可以使用内置运算符来表达它。

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


实施

您可以编写免费功能,或者在需要状态时使用仿函数。

请注意,这些完全可以作为内置运算符进行内联,因此速度没有固有的差异(编译器可能更难以证明函数指针是内联的 - 但是,所以通常首选的是仿函数。)

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;

答案 1 :(得分:1)

操作符的重载是最好的方法,因为只执行比较指令,没有什么比这更好,所以你的解决方案是最优的。

答案 2 :(得分:1)

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

struct DatenWert {
    int ordnungsnummer;
};

class DaternWert_Compare {
public:
    bool operator()(DatenWert& t1, DatenWert& t2)
    {
       if (t1.ordnungsnummer < t2.ordnungsnummer) return true;
       return false;
    }
};

int main(int argc, char** argv) {

    priority_queue<DatenWert, vector<DatenWert>, DaternWert_Compare> pq;

    DatenWert wert2 = {2};
    DatenWert wert1 = {1};
    DatenWert wert3 = {3};

    pq.push(wert1);
    pq.push(wert2);
    pq.push(wert3);

    while (! pq.empty()) {
       DatenWert t2 = pq.top();
       cout << setw(3) << t2.ordnungsnummer << " " << setw(3) << endl;
       pq.pop();
    }

    return 0;
}

结果:

3 2 1