當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Rust BinaryHeap用法及代碼示例


本文簡要介紹rust語言中 Struct std::collections::BinaryHeap 的用法。

用法

pub struct BinaryHeap<T> { /* fields omitted */ }

使用二進製堆實現的優先級隊列。

這將是一個max-heap。

以這樣一種方式修改項目是一個邏輯錯誤,即項目相對於任何其他項目的排序(由 Ord 特征確定)在堆中時發生變化。這通常隻能通過 Cell RefCell 、全局狀態、I/O 或不安全代碼實現。未指定由此類邏輯錯誤導致的行為(它可能包括Panics、不正確的結果、中止、內存泄漏或未終止),但不會是未定義的行為。

例子

use std::collections::BinaryHeap;

// Type inference lets us omit an explicit type signature (which
// would be `BinaryHeap<i32>` in this example).
let mut heap = BinaryHeap::new();

// We can use peek to look at the next item in the heap. In this case,
// there's no items in there yet so we get None.
assert_eq!(heap.peek(), None);

// Let's add some scores...
heap.push(1);
heap.push(5);
heap.push(2);

// Now peek shows the most important item in the heap.
assert_eq!(heap.peek(), Some(&5));

// We can check the length of a heap.
assert_eq!(heap.len(), 3);

// We can iterate over the items in the heap, although they are returned in
// a random order.
for x in &heap {
    println!("{}", x);
}

// If we instead pop these scores, they should come back in order.
assert_eq!(heap.pop(), Some(5));
assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);

// We can clear the heap of any remaining items.
heap.clear();

// The heap should now be empty.
assert!(heap.is_empty())

可以從數組初始化具有已知項目列表的BinaryHeap

use std::collections::BinaryHeap;

let heap = BinaryHeap::from([1, 5, 2]);

Min-heap

core::cmp::Reverse 或自定義的 Ord 實現可用於使BinaryHeap 成為min-heap。這使得 heap.pop() 返回最小值而不是最大值。

use std::collections::BinaryHeap;
use std::cmp::Reverse;

let mut heap = BinaryHeap::new();

// Wrap values in `Reverse`
heap.push(Reverse(1));
heap.push(Reverse(5));
heap.push(Reverse(2));

// If we pop these scores now, they should come back in the reverse order.
assert_eq!(heap.pop(), Some(Reverse(1)));
assert_eq!(heap.pop(), Some(Reverse(2)));
assert_eq!(heap.pop(), Some(Reverse(5)));
assert_eq!(heap.pop(), None);

時間複雜度

push 的值是預期成本;方法文檔給出了更詳細的分析。

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Struct std::collections::BinaryHeap。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。