C++ C++;如何使用用户定义的比较器将优先级队列作为属性正确地添加到类中?
我在C++中使用优先级用户队列使用优先级定义的数据类型。 我有Person.hpp作为C++ C++;如何使用用户定义的比较器将优先级队列作为属性正确地添加到类中?,c++,comparator,priority-queue,C++,Comparator,Priority Queue,我在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(); };
#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();
};
#包括
班主任{
智力年龄;
内部高度;
整数权重;
公众:
人(年龄、身高、体重);
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.hpp”
#包括
使用名称空间std;
人:人(智力年龄、智力身高、智力体重){
这->年龄=\u年龄;
此->高度=\u高度;
这->重量=\u重量;
优先级队列pqAge;
优先级队列高度;
}
int Person::getAge(){
返回此->年龄;
}
int Person::getHeight(){
返回此->高度;
}
int Person::getWeight(){
返回此->重量;
}
类cmpAge{
公众:
int运算符()(Person*a,Person*b){
返回a->getAge()>b->getAge();
}
};
类cmpHeight{
公众:
int运算符()(Person*a,Person*b){
返回a->getHeight()getHeight();
}
};
您可以看到,在my Person.cpp中,我尝试使用两个优先级队列作为属性,每个队列都有一个自定义比较器。我学习编写用户定义的比较器的方法是将其作为替代类编写,并在其中定义运算符
在本例中,我编写了一个比较器,试图为人的年龄形成一个最小堆,为人的身高形成一个最大堆
然而,当我试图构建程序时,编译器抱怨道
使用未声明的标识符“cmpAge”
使用未声明的标识符“cmpHeight”
我希望将它们作为字段的主要原因是,稍后我将在Person类中编写其他方法来对这些队列执行操作
那么,使用自定义比较器将优先级队列作为属性添加到类中的正确方法是什么呢
谢谢大家 首先,您应该将比较器放在优先级队列声明之前。否则,编译器将不知道
cmpAge
和cmpHeight
是什么。其次,比较器的运算符()
应该通过const refs获取参数并返回bool
:
struct cmpAge {
bool operator()(const Person& a, const Person& b) {
return a.getAge() > b.getAge();
}
};
您还应该将getXXX
方法标记为const
:
int getAge() const;
第三,而不是
类{public:
您可以使用struct
,默认情况下所有成员都是公共的。将比较器放在优先级队列声明之上。比较器可能应该按const-ref获取其参数。将类cmpAge和cmpHeight移到Person类之前。编译Person类时,它们需要可见。谢谢Evg!就像我需要定义优先级上方的类cmpAge一样?或者它应该是定义这个比较器的另一种方式?@jpw哦!!!!它可以工作!!!谢谢!!!!!@Evg谢谢!我想你和jpw的意思是一样的。我从来都不知道代码块顺序实际上会影响到它!再次感谢Evg提供更详细的解释!