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)。

匯入


  1. 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。
簽名:
  1. pub fn push_back(&mut self, value: T)
  2. pub fn push_front(&mut self, value: T)
  3. pub fn pop_front(&mut self) -> Option<T>
  4. pub fn pop_back(&mut self) -> Option<T>

範例:
  1. use std::collections::VecDeque;
  2. fn main() {
  3. let mut queue = VecDeque::new();
  4. queue.push_back("洗碗");
  5. queue.push_back("倒垃圾");
  6. queue.push_front("急件:回信");
  7. println!("目前佇列:{:?}", queue);
  8. while let Some(job) = queue.pop_front() {
  9. println!("處理 {},剩下 {} 件", job, queue.len());
  10. }
  11. println!("空佇列 pop:{:?}", queue.pop_back());
  12. }

輸出:
  1. 目前佇列:["急件:回信", "洗碗", "倒垃圾"]
  2. 處理 急件:回信,剩下 2 件
  3. 處理 洗碗,剩下 1 件
  4. 處理 倒垃圾,剩下 0 件
  5. 空佇列 pop:None

VecDeque 的索引與 make_contiguous


VecDeque 也能用索引 q[i] 讀寫,或用 get 安全取值。因為內部是環狀緩衝區,資料在記憶體中可能分成兩段;需要一個連續切片(例如要排序)時,呼叫 make_contiguous 把它整理成一段。
注意:q[i] 超出範圍會 panic,不確定時改用 get(i)。
簽名:
  1. pub fn get(&self, index: usize) -> Option<&T>
  2. pub fn make_contiguous(&mut self) -> &mut [T]

範例:
  1. use std::collections::VecDeque;
  2. fn main() {
  3. let mut q: VecDeque<i32> = VecDeque::from(vec![3, 1, 4]);
  4. q.push_front(9);
  5. q.push_back(2);
  6. println!("q[0] = {}", q[0]);
  7. println!("get(10) = {:?}", q.get(10));
  8. q.make_contiguous().sort();
  9. println!("排序後:{:?}", q);
  10. }

輸出:
  1. q[0] = 9
  2. get(10) = None
  3. 排序後:[1, 2, 3, 4, 9]

BinaryHeap:永遠先拿最大的


BinaryHeap<T> 是最大堆積(max-heap):push 進去的順序不重要,pop 一定拿到目前最大的元素。適合排程、找前 K 名。想要最小的先出來,把元素包進 std::cmp::Reverse。
注意:直接迭代 BinaryHeap(iter())的順序不是排序過的;要排序結果請用 into_sorted_vec 或不斷 pop。
簽名:
  1. pub fn push(&mut self, item: T)
  2. pub fn pop(&mut self) -> Option<T>
  3. pub fn peek(&self) -> Option<&T>
  4. pub fn into_sorted_vec(self) -> Vec<T>

範例:
  1. use std::cmp::Reverse;
  2. use std::collections::BinaryHeap;
  3. fn main() {
  4. let mut heap = BinaryHeap::new();
  5. for score in [70, 95, 60, 88] {
  6. heap.push(score);
  7. }
  8. println!("最高分:{:?}", heap.peek());
  9. println!("依序取出:{:?} {:?}", heap.pop(), heap.pop());
  10. let mut min_heap = BinaryHeap::new();
  11. for t in [5, 1, 3] {
  12. min_heap.push(Reverse(t));
  13. }
  14. if let Some(Reverse(smallest)) = min_heap.pop() {
  15. println!("最小值:{}", smallest);
  16. }
  17. let rest = BinaryHeap::from(vec![4, 8, 2]).into_sorted_vec();
  18. println!("into_sorted_vec:{:?}", rest);
  19. }

輸出:
  1. 最高分:Some(95)
  2. 依序取出:Some(95) Some(88)
  3. 最小值:1
  4. into_sorted_vec:[2, 4, 8]

HashSet:不重複的元素


HashSet<T> 只記得「某個值在不在裡面」。insert 回傳 bool:新加入是 true,已經存在是 false,很適合拿來去重。
注意:HashSet 的迭代順序不固定,每次執行都可能不同;要穩定輸出就先收集成 Vec 再排序。
簽名:
  1. pub fn insert(&mut self, value: T) -> bool
  2. pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
  3. pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool

範例:
  1. use std::collections::HashSet;
  2. fn main() {
  3. let mut seen = HashSet::new();
  4. for word in ["rust", "go", "rust", "zig", "go"] {
  5. if !seen.insert(word) {
  6. println!("重複:{}", word);
  7. }
  8. }
  9. println!("有 go 嗎?{}", seen.contains("go"));
  10. println!("移除 zig:{}", seen.remove("zig"));
  11. let mut all: Vec<_> = seen.into_iter().collect();
  12. all.sort();
  13. println!("剩下:{:?}", all);
  14. }

輸出:
  1. 重複:rust
  2. 重複:go
  3. 有 go 嗎?true
  4. 移除 zig:true
  5. 剩下:["go", "rust"]

集合運算:交集、聯集、差集


HashSet 與 BTreeSet 都支援數學上的集合運算,回傳的是惰性迭代器,需要時再 collect。
簽名:
  1. pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>
  2. pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>
  3. pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>

範例:
  1. use std::collections::HashSet;
  2. fn main() {
  3. let alice: HashSet<&str> = ["咖啡", "爬山", "電影"].into_iter().collect();
  4. let bob: HashSet<&str> = ["電影", "游泳", "咖啡"].into_iter().collect();
  5. let mut both: Vec<_> = alice.intersection(&bob).collect();
  6. both.sort();
  7. let mut any: Vec<_> = alice.union(&bob).collect();
  8. any.sort();
  9. let mut only_alice: Vec<_> = alice.difference(&bob).collect();
  10. only_alice.sort();
  11. println!("共同興趣:{:?}", both);
  12. println!("全部興趣:{:?}", any);
  13. println!("只有 Alice:{:?}", only_alice);
  14. }

輸出:
  1. 共同興趣:["咖啡", "電影"]
  2. 全部興趣:["咖啡", "游泳", "爬山", "電影"]
  3. 只有 Alice:["爬山"]

BTreeSet:自動排序的集合


BTreeSet<T> 和 HashSet 一樣不重複,但元素永遠由小到大排列,迭代順序固定。還能用 first/last 取最小最大值,或用 range 取一段區間。
簽名:
  1. pub fn insert(&mut self, value: T) -> bool
  2. pub fn first(&self) -> Option<&T>
  3. pub fn last(&self) -> Option<&T>
  4. pub fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>

範例:
  1. use std::collections::BTreeSet;
  2. fn main() {
  3. let mut days = BTreeSet::new();
  4. for d in [15, 3, 28, 3, 9] {
  5. days.insert(d);
  6. }
  7. println!("排序且去重:{:?}", days);
  8. println!("最早 {:?},最晚 {:?}", days.first(), days.last());
  9. let mid: Vec<_> = days.range(5..20).collect();
  10. println!("5 到 19 號:{:?}", mid);
  11. }

輸出:
  1. 排序且去重:{3, 9, 15, 28}
  2. 最早 Some(3),最晚 Some(28)
  3. 5 到 19 號:[9, 15]

LinkedList:雙向鏈結串列


LinkedList<T> 每個節點各自配置在堆積上,以指標互相串起。它能在 O(1) 內用 append 把兩條串列接起來,但隨機存取很慢、快取效率差。實務上幾乎都用 Vec 或 VecDeque 取代,只有需要頻繁拼接整條串列時才考慮。
簽名:
  1. pub fn push_back(&mut self, elt: T)
  2. pub fn push_front(&mut self, elt: T)
  3. pub fn append(&mut self, other: &mut LinkedList<T>)

範例:
  1. use std::collections::LinkedList;
  2. fn main() {
  3. let mut a = LinkedList::new();
  4. a.push_back(1);
  5. a.push_back(2);
  6. let mut b = LinkedList::new();
  7. b.push_back(3);
  8. b.push_front(0);
  9. a.append(&mut b);
  10. println!("a = {:?}", a);
  11. println!("b 被清空:{:?},長度 {}", b, b.len());
  12. println!("頭尾:{:?} {:?}", a.front(), a.back());
  13. }

輸出:
  1. a = [1, 2, 0, 3]
  2. b 被清空:[],長度 0
  3. 頭尾:Some(1) Some(3)

重點整理


  • 先用 Vec,遇到特定存取模式再換專門集合
  • 兩端進出用 VecDeque;永遠要最大值用 BinaryHeap,要最小值包 Reverse
  • 去重、成員檢查用 HashSet;需要排序或區間查詢用 BTreeSet
  • Hash 類集合的迭代順序不固定,輸出前先排序
  • LinkedList 很少是最佳選擇