std::collections
最後更新
集合(collection)型別的總匯:雙端佇列、優先佇列、集合、映射與鏈結串列都在這裡。
這個模組做什麼
程式常常需要「一堆資料」:排隊等處理的工作、不重複的標籤、依分數排序的排行榜。
Vec<T> 能應付大多數情況,但遇到「從前面拿」「永遠拿最大的」「快速判斷有沒有」時,換一個專門的集合會更快、更好寫。std::collections 就是這些專門集合的工具箱。挑選時可以先問自己:要怎麼存取資料?| 需求 | 選擇 | 說明 |
|---|---|---|
| 依序存放、用索引取值 | Vec<T> | 預設首選,見 std::vec |
| 兩端都要快速推入/取出 | VecDeque<T> | 環狀緩衝區,像排隊的隊伍 |
| 每次都拿最大(或最小)的 | BinaryHeap<T> | 優先佇列(priority queue) |
| 不重複、只問「有沒有」 | HashSet<T> | 平均 O(1) 查詢,順序不固定 |
| 不重複且要排序 | BTreeSet<T> | 永遠由小到大迭代 |
| 鍵對應值 | HashMap<K, V>/BTreeMap<K, V> | 見 hash_map、btree_map |
| 中間大量插入、拼接 | LinkedList<T> | 很少真的需要,多數情況 Vec 或 VecDeque 更快 |
雜湊(hash)類集合要求元素實作
Hash + Eq(見 std::hash);B 樹類集合要求 Ord(見 std::cmp)。匯入
- use std::collections::{BTreeSet, BinaryHeap, HashSet, LinkedList, VecDeque};
這些型別都不在 prelude 中,使用前必須
use。只有 Vec<T>(std::vec::Vec)是 prelude 自動匯入的。常用 API
VecDeque:兩端都能進出的佇列
VecDeque<T> 是雙端佇列(double-ended queue)。Vec 從頭部移除元素要把後面全部往前搬,VecDeque 則在兩端推入、取出都是 O(1)。適合「先進先出」的工作佇列或滑動視窗。注意:
pop_front/pop_back 在佇列為空時回傳 None,不會 panic。簽名:
- pub fn push_back(&mut self, value: T)
- pub fn push_front(&mut self, value: T)
- pub fn pop_front(&mut self) -> Option<T>
- pub fn pop_back(&mut self) -> Option<T>
範例:
- use std::collections::VecDeque;
- fn main() {
- let mut queue = VecDeque::new();
- queue.push_back("洗碗");
- queue.push_back("倒垃圾");
- queue.push_front("急件:回信");
- println!("目前佇列:{:?}", queue);
- while let Some(job) = queue.pop_front() {
- println!("處理 {},剩下 {} 件", job, queue.len());
- }
- println!("空佇列 pop:{:?}", queue.pop_back());
- }
輸出:
- 目前佇列:["急件:回信", "洗碗", "倒垃圾"]
- 處理 急件:回信,剩下 2 件
- 處理 洗碗,剩下 1 件
- 處理 倒垃圾,剩下 0 件
- 空佇列 pop:None
VecDeque 的索引與 make_contiguous
VecDeque 也能用索引 q[i] 讀寫,或用 get 安全取值。因為內部是環狀緩衝區,資料在記憶體中可能分成兩段;需要一個連續切片(例如要排序)時,呼叫 make_contiguous 把它整理成一段。注意:
q[i] 超出範圍會 panic,不確定時改用 get(i)。簽名:
- pub fn get(&self, index: usize) -> Option<&T>
- pub fn make_contiguous(&mut self) -> &mut [T]
範例:
- use std::collections::VecDeque;
- fn main() {
- let mut q: VecDeque<i32> = VecDeque::from(vec![3, 1, 4]);
- q.push_front(9);
- q.push_back(2);
- println!("q[0] = {}", q[0]);
- println!("get(10) = {:?}", q.get(10));
- q.make_contiguous().sort();
- println!("排序後:{:?}", q);
- }
輸出:
- q[0] = 9
- get(10) = None
- 排序後:[1, 2, 3, 4, 9]
BinaryHeap:永遠先拿最大的
BinaryHeap<T> 是最大堆積(max-heap):push 進去的順序不重要,pop 一定拿到目前最大的元素。適合排程、找前 K 名。想要最小的先出來,把元素包進 std::cmp::Reverse。注意:直接迭代
BinaryHeap(iter())的順序不是排序過的;要排序結果請用 into_sorted_vec 或不斷 pop。簽名:
- pub fn push(&mut self, item: T)
- pub fn pop(&mut self) -> Option<T>
- pub fn peek(&self) -> Option<&T>
- pub fn into_sorted_vec(self) -> Vec<T>
範例:
- use std::cmp::Reverse;
- use std::collections::BinaryHeap;
- fn main() {
- let mut heap = BinaryHeap::new();
- for score in [70, 95, 60, 88] {
- heap.push(score);
- }
- println!("最高分:{:?}", heap.peek());
- println!("依序取出:{:?} {:?}", heap.pop(), heap.pop());
- let mut min_heap = BinaryHeap::new();
- for t in [5, 1, 3] {
- min_heap.push(Reverse(t));
- }
- if let Some(Reverse(smallest)) = min_heap.pop() {
- println!("最小值:{}", smallest);
- }
- let rest = BinaryHeap::from(vec![4, 8, 2]).into_sorted_vec();
- println!("into_sorted_vec:{:?}", rest);
- }
輸出:
- 最高分:Some(95)
- 依序取出:Some(95) Some(88)
- 最小值:1
- into_sorted_vec:[2, 4, 8]
HashSet:不重複的元素
HashSet<T> 只記得「某個值在不在裡面」。insert 回傳 bool:新加入是 true,已經存在是 false,很適合拿來去重。注意:
HashSet 的迭代順序不固定,每次執行都可能不同;要穩定輸出就先收集成 Vec 再排序。簽名:
- pub fn insert(&mut self, value: T) -> bool
- pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
- pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
範例:
- use std::collections::HashSet;
- fn main() {
- let mut seen = HashSet::new();
- for word in ["rust", "go", "rust", "zig", "go"] {
- if !seen.insert(word) {
- println!("重複:{}", word);
- }
- }
- println!("有 go 嗎?{}", seen.contains("go"));
- println!("移除 zig:{}", seen.remove("zig"));
- let mut all: Vec<_> = seen.into_iter().collect();
- all.sort();
- println!("剩下:{:?}", all);
- }
輸出:
- 重複:rust
- 重複:go
- 有 go 嗎?true
- 移除 zig:true
- 剩下:["go", "rust"]
集合運算:交集、聯集、差集
HashSet 與 BTreeSet 都支援數學上的集合運算,回傳的是惰性迭代器,需要時再 collect。簽名:
- pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>
- pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>
- pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>
範例:
- use std::collections::HashSet;
- fn main() {
- let alice: HashSet<&str> = ["咖啡", "爬山", "電影"].into_iter().collect();
- let bob: HashSet<&str> = ["電影", "游泳", "咖啡"].into_iter().collect();
- let mut both: Vec<_> = alice.intersection(&bob).collect();
- both.sort();
- let mut any: Vec<_> = alice.union(&bob).collect();
- any.sort();
- let mut only_alice: Vec<_> = alice.difference(&bob).collect();
- only_alice.sort();
- println!("共同興趣:{:?}", both);
- println!("全部興趣:{:?}", any);
- println!("只有 Alice:{:?}", only_alice);
- }
輸出:
- 共同興趣:["咖啡", "電影"]
- 全部興趣:["咖啡", "游泳", "爬山", "電影"]
- 只有 Alice:["爬山"]
BTreeSet:自動排序的集合
BTreeSet<T> 和 HashSet 一樣不重複,但元素永遠由小到大排列,迭代順序固定。還能用 first/last 取最小最大值,或用 range 取一段區間。簽名:
- pub fn insert(&mut self, value: T) -> bool
- pub fn first(&self) -> Option<&T>
- pub fn last(&self) -> Option<&T>
- pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>
範例:
- use std::collections::BTreeSet;
- fn main() {
- let mut days = BTreeSet::new();
- for d in [15, 3, 28, 3, 9] {
- days.insert(d);
- }
- println!("排序且去重:{:?}", days);
- println!("最早 {:?},最晚 {:?}", days.first(), days.last());
- let mid: Vec<_> = days.range(5..20).collect();
- println!("5 到 19 號:{:?}", mid);
- }
輸出:
- 排序且去重:{3, 9, 15, 28}
- 最早 Some(3),最晚 Some(28)
- 5 到 19 號:[9, 15]
LinkedList:雙向鏈結串列
LinkedList<T> 每個節點各自配置在堆積上,以指標互相串起。它能在 O(1) 內用 append 把兩條串列接起來,但隨機存取很慢、快取效率差。實務上幾乎都用 Vec 或 VecDeque 取代,只有需要頻繁拼接整條串列時才考慮。簽名:
- pub fn push_back(&mut self, elt: T)
- pub fn push_front(&mut self, elt: T)
- pub fn append(&mut self, other: &mut LinkedList<T>)
範例:
- use std::collections::LinkedList;
- fn main() {
- let mut a = LinkedList::new();
- a.push_back(1);
- a.push_back(2);
- let mut b = LinkedList::new();
- b.push_back(3);
- b.push_front(0);
- a.append(&mut b);
- println!("a = {:?}", a);
- println!("b 被清空:{:?},長度 {}", b, b.len());
- println!("頭尾:{:?} {:?}", a.front(), a.back());
- }
輸出:
- a = [1, 2, 0, 3]
- b 被清空:[],長度 0
- 頭尾:Some(1) Some(3)
重點整理
- 先用
Vec,遇到特定存取模式再換專門集合 - 兩端進出用
VecDeque;永遠要最大值用BinaryHeap,要最小值包Reverse - 去重、成員檢查用
HashSet;需要排序或區間查詢用BTreeSet - Hash 類集合的迭代順序不固定,輸出前先排序
LinkedList很少是最佳選擇