简体   繁体   中英

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

I am practicing using priority queues with the user-defined data type in C++.

I have Person.hpp as

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

and a Person.cpp as

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

You could see that, in my Person.cpp, I tried to have two priority queues as my attributes, each with a custom comparator. The way I learned to write a user-defined comparator is to write it as an alternative class and define an operator in it.

In this case, I have written a comparator trying to form a min-heap for the person's age, and a max-heap for the person's height.

However, when I tried to build the program, the compiler complains

Use of undeclared identifier 'cmpAge'

Use of undeclared identifier 'cmpHeight'

The main reason I want to have them as fields is that later I will write other methods in the Person class to perform actions on these queues.

So what is a proper way to add a priority_queue to a class as an attribute with a custom comparator?

Thanks guys!

First, you should put the comparators before the priority queues declarations. Otherwise, a compiler would not know what cmpAge and cmpHeight are. Second, the comparators' operator() should take their arguments by const-refs and return bool :

struct cmpAge {
    bool operator()(const Person& a, const Person& b) {
        return a.getAge() > b.getAge();
    }
};

You should also mark getXXX methods as const :

int getAge() const;

And third, instead of class { public: you can use struct , in which all members are public by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM