【问题标题】:Reverse order Priority Queue [duplicate]倒序优先队列[重复]
【发布时间】:2021-09-22 11:27:11
【问题描述】:

有谁知道是否可以在 Rust 中颠倒优先级队列中的顺序? 当我查看队列时,我希望接收到最低的 i32。但是,它似乎默认返回最高的 i32。

编辑

这是我正在使用的包:docs.rs/priority-queue/1.2.0/priority_queue

【问题讨论】:

标签: rust priority-queue


【解决方案1】:

除非您需要从两端访问它,否则使用std::cmp::Reverse 应该是最有效的解决方案。 (例如PriorityQueue<i32, Reverse<i32>>、.push(x, Reverse(x)))

【讨论】:

  • 如何将它与 PriorityQueue 一起使用?
  • @Jean 我的编辑回答你的问题了吗?
  • 非常好,谢谢!
  • 实际上,如何访问 Reverse 值?找到了,它是一个元组,这很混乱。所以reverse_variable.0 给出了值。
【解决方案2】:

根据箱子(包)的documentation。

我相信您应该使用DoublePriorityQueue 而不是PriorityQueue,因为它为队列中的peek 提供了最高值或最低值。分别使用peek_max 或peek_min。

查看他们在documentation中提供的代码的sn-p:

use priority_queue::DoublePriorityQueue;

let mut pq = DoublePriorityQueue::new();

assert!(pq.is_empty());
pq.push("Apples", 5);
pq.push("Bananas", 8);
pq.push("Strawberries", 23);

assert_eq!(pq.peek_max(), Some((&"Strawberries", &23)));
assert_eq!(pq.peek_min(), Some((&"Apples", &5)));

pq.change_priority("Bananas", 25);
assert_eq!(pq.peek_max(), Some((&"Bananas", &25)));

for (item, _) in pq.into_sorted_iter() {
    println!("{}", item);
}

【讨论】:

    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 2013-11-13
    • 2010-12-10
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多