# std::collections::btree_map

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

## 這個模組做什麼

`BTreeMap` 和 `HashMap` 一樣是「鍵對應值」的映射，差別在於它把鍵依大小排好。可以想成一本依字母排序的字典：查一個字稍慢一點（O(log n)），但可以從頭到尾依序翻、也能直接翻到「C 開頭到 F 開頭」這一段。

B 樹（B-tree）是一種每個節點存放多個鍵的平衡樹，比二元樹更符合 CPU 快取，所以實務上表現很好。

| 比較 | `HashMap` | `BTreeMap` |
| --- | --- | --- |
| 查詢／插入 | 平均 O(1) | O(log n) |
| 迭代順序 | 不固定 | 依鍵由小到大 |
| 鍵的要求 | `Hash + Eq` | `Ord` |
| 區間查詢 `range` | 不支援 | 支援 |
| 最小／最大鍵 | 要掃全部 | `first_key_value`／`last_key_value` |

選擇原則：只需要查值就用 `HashMap`（見 [hash_map](/pkg-collections-hash-map)）；需要排序輸出、區間、最大最小值，或希望輸出順序穩定，就用 `BTreeMap`。

## 匯入

```rust
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>`。不同的是迭代時一定依鍵由小到大。

簽名：
```rust
pub const fn new() -> BTreeMap<K, V>
pub fn insert(&mut self, key: K, value: V) -> Option<V>
pub fn get<Q: ?Sized + Ord>(&self, key: &Q) -> Option<&V>
```

範例：
```rust
use std::collections::BTreeMap;

fn main() {
    let mut phone = BTreeMap::new();
    phone.insert("王小明", "0912");
    phone.insert("陳大文", "0933");
    phone.insert("李美玲", "0988");
    println!("覆蓋陳大文：{:?}", phone.insert("陳大文", "0955"));

    println!("李美玲：{:?}", phone.get("李美玲"));
    for (name, num) in &phone {
        println!("{} -> {}", name, num);
    }
}
```

輸出：
```text
覆蓋陳大文：Some("0933")
李美玲：Some("0988")
李美玲 -> 0988
王小明 -> 0912
陳大文 -> 0955
```

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

### range：區間查詢

`range` 取出鍵落在某個區間的所有元素，區間寫法和切片一樣：`a..b`、`a..=b`、`a..`、`..b`。適合「某段時間的紀錄」「某個分數區間的人」這類查詢。

注意：區間起點大於終點（例如 `5..3`），或起點與終點相同但兩端都排除時，`range` 會 panic。

簽名：
```rust
pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
where
    T: Ord,
    K: Borrow<T> + Ord,
    R: RangeBounds<T>,
```

範例：
```rust
use std::collections::BTreeMap;

fn main() {
    let mut temps = BTreeMap::new();
    for (hour, t) in [(6, 18), (9, 22), (12, 27), (15, 29), (18, 24), (21, 20)] {
        temps.insert(hour, t);
    }

    println!("上午 (6..12)：");
    for (h, t) in temps.range(6..12) {
        println!("  {} 點 {} 度", h, t);
    }

    let afternoon: Vec<_> = temps.range(12..=18).map(|(_, t)| *t).collect();
    println!("下午溫度：{:?}", afternoon);
    println!("15 點以後：{:?}", temps.range(15..).count());
}
```

輸出：
```text
上午 (6..12)：
  6 點 18 度
  9 點 22 度
下午溫度：[27, 29, 24]
15 點以後：3
```

### first_key_value 與 last_key_value

直接拿到最小與最大的鍵值對，不必走訪全部。空映射回傳 `None`。這兩個函式在 Rust 1.66 起穩定。

簽名：
```rust
pub fn first_key_value(&self) -> Option<(&K, &V)>
pub fn last_key_value(&self) -> Option<(&K, &V)>
```

範例：
```rust
use std::collections::BTreeMap;

fn main() {
    let ranking = BTreeMap::from([(88, "Bob"), (95, "Amy"), (72, "Cat")]);
    println!("最低分：{:?}", ranking.first_key_value());
    println!("最高分：{:?}", ranking.last_key_value());

    let empty: BTreeMap<i32, &str> = BTreeMap::new();
    println!("空映射：{:?}", empty.first_key_value());
}
```

輸出：
```text
最低分：Some((72, "Cat"))
最高分：Some((95, "Amy"))
空映射：None
```

### pop_first 與 pop_last

把最小（或最大）的元素拿出來並從映射中移除，讓 `BTreeMap` 也能當成「可依鍵查詢的優先佇列」使用。Rust 1.66 起穩定。

簽名：
```rust
pub fn pop_first(&mut self) -> Option<(K, V)>
pub fn pop_last(&mut self) -> Option<(K, V)>
```

範例：
```rust
use std::collections::BTreeMap;

fn main() {
    let mut tasks = BTreeMap::from([(3, "寫報告"), (1, "回信"), (2, "開會")]);
    while let Some((priority, task)) = tasks.pop_first() {
        println!("優先度 {}：{}", priority, task);
    }
    println!("清空後：{:?}", tasks.pop_last());
}
```

輸出：
```text
優先度 1：回信
優先度 2：開會
優先度 3：寫報告
清空後：None
```

### entry：計數與分組

`BTreeMap` 也有與 `HashMap` 相同的 Entry API。因為結果已排序，直接印出來就是穩定的統計表。

簽名：
```rust
pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
pub fn or_insert(self, default: V) -> &'a mut V
```

範例：
```rust
use std::collections::BTreeMap;

fn main() {
    let text = "banana";
    let mut freq = BTreeMap::new();
    for ch in text.chars() {
        *freq.entry(ch).or_insert(0) += 1;
    }
    println!("{:?}", freq);

    let mut by_len: BTreeMap<usize, Vec<&str>> = BTreeMap::new();
    for w in ["go", "rust", "c", "zig", "java"] {
        by_len.entry(w.len()).or_default().push(w);
    }
    println!("{:?}", by_len);
}
```

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

### remove、retain 與 split_off

`remove` 刪除單一鍵；`retain` 依條件保留；`split_off(&k)` 把「鍵大於等於 k」的部分切成另一個新映射，原本的只留下比 k 小的。

簽名：
```rust
pub fn remove<Q: ?Sized + Ord>(&mut self, key: &Q) -> Option<V>
pub fn retain<F>(&mut self, f: F) where F: FnMut(&K, &mut V) -> bool
pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
```

範例：
```rust
use std::collections::BTreeMap;

fn main() {
    let mut m: BTreeMap<i32, char> = (1..=8).zip('a'..='h').collect();
    println!("移除 4：{:?}", m.remove(&4));

    m.retain(|k, _| k % 3 != 0);
    println!("去掉 3 的倍數：{:?}", m);

    let high = m.split_off(&5);
    println!("小於 5：{:?}", m);
    println!("大於等於 5：{:?}", high);
}
```

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

### 自訂型別當鍵：實作 Ord

`BTreeMap` 用比較大小來決定位置，所以鍵需要 `Ord`。最簡單是 derive：`struct` 會依欄位宣告順序逐一比較（字典序），`enum` 依變體宣告順序。詳見 [std::cmp](/pkg-cmp)。

簽名：
```rust
impl<K: Ord, V> BTreeMap<K, V>
```

範例：
```rust
use std::collections::BTreeMap;

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Date {
    year: u16,
    month: u8,
    day: u8,
}

fn main() {
    let mut diary = BTreeMap::new();
    diary.insert(Date { year: 2025, month: 3, day: 1 }, "搬家");
    diary.insert(Date { year: 2024, month: 12, day: 25 }, "聖誕節");
    diary.insert(Date { year: 2025, month: 1, day: 1 }, "元旦");

    for (d, event) in &diary {
        println!("{}-{:02}-{:02} {}", d.year, d.month, d.day, event);
    }
}
```

輸出：
```text
2024-12-25 聖誕節
2025-01-01 元旦
2025-03-01 搬家
```

## 重點整理

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