C++ 如何使用用户定义的比较器将 priority_queue 作为属性正确添加到 class?

C++ How to properly add a priority_queue to a class as an attribute with a user-defined comparator?

我正在练习在 C++ 中使用具有用户定义数据类型的优先级队列。

我有 Person.hpp 作为

#include <stdio.h>

class Person {
    int age;
    int height;
    int weight;
public:
    Person(int _age, int _height, int _weight);
    int getAge();
    int getHeight();
    int getWeight();
};

和一个Person.cpp作为

#include "Person.hpp"
#include <queue>
using namespace std;

Person::Person(int _age, int _height, int _weight){
    this->age = _age;
    this->height = _height;
    this->weight = _weight;
    priority_queue<Person, vector<Person>, cmpAge > pqAge;
    priority_queue<Person, vector<Person>, cmpHeight > pqHeight;
}

int Person::getAge(){
    return this->age;
}

int Person::getHeight(){
    return this->height;
}

int Person::getWeight(){
    return this->weight;
}

class cmpAge{
public:
    int operator()(Person *a, Person *b) {
        return a->getAge() > b->getAge();
    }
};

class cmpHeight{
public:
    int operator()(Person *a, Person *b) {
        return a->getHeight() < b->getHeight();
    }
};

您可以看到,在我的 Person.cpp 中,我尝试将两个优先级队列作为我的属性,每个队列都有一个自定义比较器。我学习编写用户定义比较器的方法是将其编写为替代 class 并在其中定义一个运算符。

在这种情况下,我编写了一个比较器,试图为该人的年龄形成一个最小堆,并为该人的身高形成一个最大堆。

但是,当我尝试构建程序时,编译器报错

使用未声明的标识符'cmpAge'

使用未声明的标识符'cmpHeight'

我希望将它们作为字段的主要原因是稍后我将在 Person class 中编写其他方法来对这些队列执行操作。

那么使用自定义比较器将 priority_queue 作为属性添加到 class 的正确方法是什么?

谢谢大家!

首先,您应该将比较器放在优先级队列声明之前。否则,编译器将不知道 cmpAgecmpHeight 是什么。其次,比较器的 operator() 应该通过 const-refs 和 return bool:

来获取他们的参数
struct cmpAge {
    bool operator()(const Person& a, const Person& b) {
        return a.getAge() > b.getAge();
    }
};

您还应该将 getXXX 方法标记为 const:

int getAge() const;

第三,您可以使用struct代替class { public:,其中所有成员默认为public。