简体   繁体   中英

C++ / priority_queue / Expression: invalid comparator

EDIT I included a screenshot of the compile error with reworked code. compile error screenshot

ORIGINAL POST I am writing a little program to practice my knowledge of priority_queue containers. I am trying to create a priority-queue that takes in Person objects that have an age and sex. The queue is supposed to prioritize older ages and then females over males (ie. older females are prioritized over younger females and females are prioritized over males). I've written a predicate that should handle the prioritization but I get a Expression: invalid comparator error when I try to compile the code snippet below. Can anyone explain what the problem is with my predicate?

#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <iostream>

class Person
{
public: 
    int age;
    bool isFemale; 

    Person(int Age, bool Female)
    {
        age = Age;
        isFemale = Female; 
    }

    bool operator < (const Person& compareHuman) const
    {
        bool bRet = false;

        if (age < compareHuman.age)
            bRet = true;

        if (isFemale && compareHuman.isFemale)
            bRet = true;

        return bRet;    
    }
};

int main()
{
    std::priority_queue<Person, std::vector<Person>> humanStack;
    humanStack.push(Person(15, true));
    humanStack.push(Person(42, true));
    humanStack.push(Person(76, true));
    humanStack.push(Person(65, false));
    humanStack.push(Person(21, false));
    humanStack.push(Person(35, true));
    humanStack.push(Person(15, false));

    while(humanStack.size() != 0)
    {
            std::cout << "This person is age " << humanStack.top().age << std::endl;
            humanStack.pop(); 
    }
}

The problem is your less than predicate isn't implemented correctly. As written a value will compare less than itself if isFemale is true. A value should never compare less than itself with a valid predicate. You probably want something like this:

bool operator < (const Person& compareHuman) const
{
    if (age < compareHuman.age)
        return true;
    else if (compareHuman.age < age)
        return false;

    // Note the ! added on this line
    return isFemale && !compareHuman.isFemale;
}

Your code compiles w/o error for me using C++11. (clang).

In c++03, the compiler complains about vector<Person>> humanStack - to fix that, insert a space between the two angle brackets thus: vector<Person> > humanStack

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