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


Rust BTreeSet用法及代碼示例

本文簡要介紹rust語言中 Struct alloc::collections::btree_set::BTreeSet 的用法。

用法

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

基於B-Tree 的集合。

請參閱 BTreeMap 的文檔,詳細討論此集合的性能優勢和劣勢。

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

例子

use std::collections::BTreeSet;

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

// Add some books.
books.insert("A Dance With Dragons");
books.insert("To Kill a Mockingbird");
books.insert("The Odyssey");
books.insert("The Great Gatsby");

// Check for a specific one.
if !books.contains("The Winds of Winter") {
    println!("We have {} books, but The Winds of Winter ain't one.",
             books.len());
}

// Remove a book.
books.remove("The Odyssey");

// Iterate over everything.
for book in &books {
    println!("{}", book);
}

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

use std::collections::BTreeSet;

let set = BTreeSet::from([1, 2, 3]);

相關用法


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