C+中的运算符重载或比较函数+;优先级队列 我正在编写C++程序,我想定义我的类中的一个优先级队列。我需要它通过一个类成员变量来比较对象。我使用了操作符

C+中的运算符重载或比较函数+;优先级队列 我正在编写C++程序,我想定义我的类中的一个优先级队列。我需要它通过一个类成员变量来比较对象。我使用了操作符,c++,stl,performance,C++,Stl,Performance,我的做法如下: #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) {} boo

我的做法如下:

#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;
}
#包括
#包括
使用名称空间std;
阶级人{
公众:
字符串名;
智力年龄;
人类(字符串名称,int-age);
};
Human::Human(字符串名,int-age):name(name),age(age){}

bool运算符运算符重载是最好的方法,因为只执行比较指令,没有什么比它更有效,所以您的解决方案是最优的。

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

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


实施 您可以编写自由函数,如果需要状态,也可以使用函子

请注意,这两个函数都像内置操作符一样易于内联,因此在速度上没有本质上的差异(但编译器可能更难证明函数指针是内联的,因此通常首选函子)

struct OrderByAge
{
bool操作符()(人类常数&a,人类常数&b){返回a.age
#包括
#包括
#包括
#包括
使用名称空间std;
结构DatenWert{
国际奥德努格斯努默;
};
类数据比较{
公众:
布尔运算符()(DatenWert&t1、DatenWert&t2)
{
if(t1.ordnungsnummercout
返回a.age
看起来有点尴尬可能
返回a.age
?哦,是的,你是对的。我同意,谢谢。我如何编写这种函数?我应该在哪里声明它?但是比较运算符可以执行一百万次比较,你所知道的一切。使用t没有效率优势运算符或函子方法。也许大家都知道。我知道比较是一个原子处理器函数。但是我没有说重载比任何函数都好,但我说重载并不比任何其他函数差。两个
std::strings
的比较是原子的?好吧,我今天学到了一些东西。
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;
#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;
}