【发布时间】:2022-01-21 06:38:58
【问题描述】:
// program in c++ to use priority_queue with class
#include <iostream>
#include <queue>
using namespace std;
#define ROW 5
#define COL 2
class Person {
public:
int age;
float height;
// this is used to initialize the variables of the class
Person(int age, float height)
: age(age), height(height)
{
}
bool operator < (const Person& p1) {
return (this->height > p1.height);
}
};
// bool operator<(const Person& p1, const Person& p2)
// {
// return p1.height > p2.height;
// }
// struct myCmp
// {
// bool operator() (const Person& p1, const Person& p2) {
// return p1.height > p2.height;
// }
// };
int main()
{
priority_queue<Person> Q;
float arr[ROW][COL] = { { 30, 5.5 }, { 25, 5 },
{ 20, 6 }, { 33, 6.1 }, { 23, 5.6 } };
for (int i = 0; i < ROW; ++i) {
Q.push(Person(arr[i][0], arr[i][1]));
// insert an object in priority_queue by using
// the Person class constructor
}
while (!Q.empty()) {
Person p = Q.top();
Q.pop();
cout << p.age << " " << p.height << "\n";
}
return 0;
}
注意! 代码中的其他注释方法似乎有效,除了这给了我一个错误。
上面的代码是为了让身高较低的人排在最前面而创建一个优先队列。我尝试使用 struct 方法来定义似乎工作正常的自定义比较函数。上述 cmets 中的显式运算符重载也有效。
预期输出:
25 5
30 5.5
23 5.6
20 6
33 6.1
错误:
'operator
【问题讨论】:
-
该错误表明
operator<正在应用到 constPerson。您的运算符只有右手值作为 const。将您的operator<声明为 const。
标签: c++ operator-overloading priority-queue