std::collections::btree_map

最後更新


以 B 樹實作、鍵永遠保持排序的映射 BTreeMap<K, V>。

這個模組做什麼


BTreeMap 和 HashMap 一樣是「鍵對應值」的映射,差別在於它把鍵依大小排好。可以想成一本依字母排序的字典:查一個字稍慢一點(O(log n)),但可以從頭到尾依序翻、也能直接翻到「C 開頭到 F 開頭」這一段。
B 樹(B-tree)是一種每個節點存放多個鍵的平衡樹,比二元樹更符合 CPU 快取,所以實務上表現很好。
比較HashMapBTreeMap
查詢/插入平均 O(1)O(log n)
迭代順序不固定依鍵由小到大
鍵的要求Hash + EqOrd
區間查詢 range不支援支援
最小/最大鍵要掃全部first_key_value/last_key_value

選擇原則:只需要查值就用 HashMap(見 hash_map);需要排序輸出、區間、最大最小值,或希望輸出順序穩定,就用 BTreeMap。

匯入


  1. use std::collections::BTreeMap;

BTreeMap 不在 prelude 中。std::collections::BTreeMap 與 std::collections::btree_map::BTreeMap 是同一個型別;Entry 等配套型別在 std::collections::btree_map 下。

常用 API


insert、get 與排序迭代


基本操作和 HashMap 幾乎一樣:insert 覆蓋時回傳舊值,get 回傳 Option<&V>。不同的是迭代時一定依鍵由小到大。
簽名:
  1. pub const fn new() -> BTreeMap<K, V>
  2. pub fn insert(&mut self, key: K, value: V) -> Option<V>
  3. pub fn get<Q: ?Sized + Ord>(&self, key: &Q) -> Option<&V>

範例:
  1. use std::collections::BTreeMap;
  2. fn main() {
  3. let mut phone = BTreeMap::new();
  4. phone.insert("王小明", "0912");
  5. phone.insert("陳大文", "0933");
  6. phone.insert("李美玲", "0988");
  7. println!("覆蓋陳大文:{:?}", phone.insert("陳大文", "0955"));
  8. println!("李美玲:{:?}", phone.get("李美玲"));
  9. for (name, num) in &phone {
  10. println!("{} -> {}", name, num);
  11. }
  12. }

輸出:
  1. 覆蓋陳大文:Some("0933")
  2. 李美玲:Some("0988")
  3. 李美玲 -> 0988
  4. 王小明 -> 0912
  5. 陳大文 -> 0955

中文字串依 Unicode 碼位排序,不是依筆畫或注音。

range:區間查詢


range 取出鍵落在某個區間的所有元素,區間寫法和切片一樣:a..b、a..=b、a..、..b。適合「某段時間的紀錄」「某個分數區間的人」這類查詢。
注意:區間起點大於終點(例如 5..3),或起點與終點相同但兩端都排除時,range 會 panic。
簽名:
  1. pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
  2. where
  3. T: Ord,
  4. K: Borrow<T> + Ord,
  5. R: RangeBounds<T>,

範例:
  1. use std::collections::BTreeMap;
  2. fn main() {
  3. let mut temps = BTreeMap::new();
  4. for (hour, t) in [(6, 18), (9, 22), (12, 27), (15, 29), (18, 24), (21, 20)] {
  5. temps.insert(hour, t);
  6. }
  7. println!("上午 (6..12):");
  8. for (h, t) in temps.range(6..12) {
  9. println!(" {} 點 {} 度", h, t);
  10. }
  11. let afternoon: Vec<_> = temps.range(12..=18).map(|(_, t)| *t).collect();
  12. println!("下午溫度:{:?}", afternoon);
  13. println!("15 點以後:{:?}", temps.range(15..).count());
  14. }

輸出:
  1. 上午 (6..12):
  2. 6 點 18 度
  3. 9 點 22 度
  4. 下午溫度:[27, 29, 24]
  5. 15 點以後:3

first_key_value 與 last_key_value


直接拿到最小與最大的鍵值對,不必走訪全部。空映射回傳 None。這兩個函式在 Rust 1.66 起穩定。
簽名:
  1. pub fn first_key_value(&self) -> Option<(&K, &V)>
  2. pub fn last_key_value(&self) -> Option<(&K, &V)>

範例:
  1. use std::collections::BTreeMap;
  2. fn main() {
  3. let ranking = BTreeMap::from([(88, "Bob"), (95, "Amy"), (72, "Cat")]);
  4. println!("最低分:{:?}", ranking.first_key_value());
  5. println!("最高分:{:?}", ranking.last_key_value());
  6. let empty: BTreeMap<i32, &str> = BTreeMap::new();
  7. println!("空映射:{:?}", empty.first_key_value());
  8. }

輸出:
  1. 最低分:Some((72, "Cat"))
  2. 最高分:Some((95, "Amy"))
  3. 空映射:None

pop_first 與 pop_last


把最小(或最大)的元素拿出來並從映射中移除,讓 BTreeMap 也能當成「可依鍵查詢的優先佇列」使用。Rust 1.66 起穩定。
簽名:
  1. pub fn pop_first(&mut self) -> Option<(K, V)>
  2. pub fn pop_last(&mut self) -> Option<(K, V)>

範例:
  1. use std::collections::BTreeMap;
  2. fn main() {
  3. let mut tasks = BTreeMap::from([(3, "寫報告"), (1, "回信"), (2, "開會")]);
  4. while let Some((priority, task)) = tasks.pop_first() {
  5. println!("優先度 {}:{}", priority, task);
  6. }
  7. println!("清空後:{:?}", tasks.pop_last());
  8. }

輸出:
  1. 優先度 1:回信
  2. 優先度 2:開會
  3. 優先度 3:寫報告
  4. 清空後:None

entry:計數與分組


BTreeMap 也有與 HashMap 相同的 Entry API。因為結果已排序,直接印出來就是穩定的統計表。
簽名:
  1. pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
  2. pub fn or_insert(self, default: V) -> &'a mut V

範例:
  1. use std::collections::BTreeMap;
  2. fn main() {
  3. let text = "banana";
  4. let mut freq = BTreeMap::new();
  5. for ch in text.chars() {
  6. *freq.entry(ch).or_insert(0) += 1;
  7. }
  8. println!("{:?}", freq);
  9. let mut by_len: BTreeMap<usize, Vec<&str>> = BTreeMap::new();
  10. for w in ["go", "rust", "c", "zig", "java"] {
  11. by_len.entry(w.len()).or_default().push(w);
  12. }
  13. println!("{:?}", by_len);
  14. }

輸出:
  1. {'a': 3, 'b': 1, 'n': 2}
  2. {1: ["c"], 2: ["go"], 3: ["zig"], 4: ["rust", "java"]}

remove、retain 與 split_off


remove 刪除單一鍵;retain 依條件保留;split_off(&k) 把「鍵大於等於 k」的部分切成另一個新映射,原本的只留下比 k 小的。
簽名:
  1. pub fn remove<Q: ?Sized + Ord>(&mut self, key: &Q) -> Option<V>
  2. pub fn retain<F>(&mut self, f: F) where F: FnMut(&K, &mut V) -> bool
  3. pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self

範例:
  1. use std::collections::BTreeMap;
  2. fn main() {
  3. let mut m: BTreeMap<i32, char> = (1..=8).zip('a'..='h').collect();
  4. println!("移除 4:{:?}", m.remove(&4));
  5. m.retain(|k, _| k % 3 != 0);
  6. println!("去掉 3 的倍數:{:?}", m);
  7. let high = m.split_off(&5);
  8. println!("小於 5:{:?}", m);
  9. println!("大於等於 5:{:?}", high);
  10. }

輸出:
  1. 移除 4:Some('d')
  2. 去掉 3 的倍數:{1: 'a', 2: 'b', 5: 'e', 7: 'g', 8: 'h'}
  3. 小於 5:{1: 'a', 2: 'b'}
  4. 大於等於 5:{5: 'e', 7: 'g', 8: 'h'}

自訂型別當鍵:實作 Ord


BTreeMap 用比較大小來決定位置,所以鍵需要 Ord。最簡單是 derive:struct 會依欄位宣告順序逐一比較(字典序),enum 依變體宣告順序。詳見 std::cmp。
簽名:
  1. impl<K: Ord, V> BTreeMap<K, V>

範例:
  1. use std::collections::BTreeMap;
  2. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
  3. struct Date {
  4. year: u16,
  5. month: u8,
  6. day: u8,
  7. }
  8. fn main() {
  9. let mut diary = BTreeMap::new();
  10. diary.insert(Date { year: 2025, month: 3, day: 1 }, "搬家");
  11. diary.insert(Date { year: 2024, month: 12, day: 25 }, "聖誕節");
  12. diary.insert(Date { year: 2025, month: 1, day: 1 }, "元旦");
  13. for (d, event) in &diary {
  14. println!("{}-{:02}-{:02} {}", d.year, d.month, d.day, event);
  15. }
  16. }

輸出:
  1. 2024-12-25 聖誕節
  2. 2025-01-01 元旦
  3. 2025-03-01 搬家

重點整理


  • BTreeMap 的鍵永遠排序,迭代順序穩定
  • 查詢與插入是 O(log n);不需要順序時 HashMap 通常更快
  • range 做區間查詢,起點大於終點會 panic
  • first_key_value/last_key_value/pop_first/pop_last 快速取得最小最大值
  • 鍵需要 Ord,自訂型別 derive 時依欄位順序比較