![](/img/trans.png)
[英]How do you update values in priority_queue, or is there another way to update keys in heaps in c++
[英]How do you order objects in a priority_queue in C++?
我找不到有關如何在優先級隊列中排序對象的任何信息。 我嘗試了這個:
class Person {
...
public:
bool operator<(const Person& p) {
return age < p.age;
}
}
int main() {
priority_queue<Person*> people;
people.push(new Person("YoungMan", 21));
people.push(new Person("Grandma", 83));
people.push(new Person("TimeTraveler", -5000));
people.push(new Person("Infant", 1));
while (!people.empty()) {
cout << people.top()->name;
delete people.top();
people.pop();
}
而且應該根據年齡來分配優先級(老年人獲得更高的優先級,因此首先離開隊列),但這是行不通的。 但是我得到以下輸出:
Infant
Grandma
TimeTraveler
YoungMan
我不知道這是什么命令,但絕對不是年齡。
priority_queue<Person*>
實際上是基於使用比較器std::less<Person*>
比較Person
對象的內存地址來Person
。
聲明一個priority_queue<Person>
而不是根據您提供的operator<
進行訂購。
或者,如果您出於某種原因堅持使用指針,則聲明為:
auto age_comp = [](const std::unique_ptr<Person>& lhs, const std::unique_ptr<Person>& rhs) -> bool {
return *lhs < *rhs;
};
std::priority_queue<std::unique_ptr<Person>, std::vector<std::unique_ptr<Person>>,
decltype(age_comp)> people(age_comp);
// note: must pass age_comp to std::priority_queue constructor here as
// lambda closure types have deleted default constructors
請注意,這使用的是智能指針而不是原始指針,前者在現代C ++中更常用-除非您有充分的理由,否則不要使用原始指針。
此外, operator<
的Person
應該是const
規定,因為它不應該改變的Person
反對它屬於在任何時候-的比較std::priority_queue
預計const
並可能會拋出一個錯誤,如果operator<
沒有const
規格。 因此,將operator<
更改為:
bool operator<(const Person& p) const {
return age < p.age;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.