簡體   English   中英

C++ / priority_queue / 表達式:無效的比較器

[英]C++ / priority_queue / Expression: invalid comparator

編輯我包含了帶有重新編寫的代碼的編譯錯誤的屏幕截圖。 編譯錯誤截圖

原始帖子我正在編寫一個小程序來練習我對priority_queue 容器的了解。 我正在嘗試創建一個優先級隊列,該隊列接收具有年齡和性別的 Person 對象。 該隊列應該優先考慮老年人,然后女性優先於男性(即,年長女性優先於年輕女性,女性優先於男性)。 我編寫了一個應該處理優先級的謂詞,但是當我嘗試編譯下面的代碼片段時,我得到一個 Expression: invalid comparison 錯誤。 誰能解釋我的謂詞有什么問題?

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

問題是您的小於謂詞未正確實施。 如所寫,如果isFemale為真,則值將小於自身。 一個值永遠不應該將小於自身的值與有效的謂詞進行比較。 你可能想要這樣的東西:

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;
}

您的代碼使用 C++11 為我編譯沒有錯誤。 (鐺)。

在 c++03 中,編譯器抱怨vector<Person>> humanStack - 為了解決這個問題,在兩個尖括號之間插入一個空格: vector<Person> > humanStack

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM