容器分類總覽
| 類別 | 容器 | 底層結構 | 特點 |
| 序列容器 | vector | 動態數組 | 隨機訪問快,尾部增刪 O(1) |
| deque | 分段數組 | 雙端增刪 O(1),隨機訪問快 |
| list | 雙向鏈表 | 任意位置增刪 O(1),無隨機訪問 |
| 關聯容器 | set/multiset | 紅黑樹 | 有序、唯一/可重複、查找 O(log n) |
| map/multimap | 紅黑樹 | 鍵值對、按鍵有序 |
| unordered_set/map | 哈希表 | 無序、平均 O(1) |
| 容器適配器 | stack | deque/list | LIFO,默認 deque |
| queue | deque/list | FIFO,默認 deque |
| priority_queue | vector | 堆,默認大根堆 |
序列容器通用接口
// 構造
Container c; // 默認
Container c(n); // n 個值初始化
Container c(n, val); // n 個 val
Container c(beg, end); // 範圍構造
Container c = other; // 拷貝構造
// 容量
c.empty() c.size() c.max_size() c.resize(n, val)
// 迭代器
c.begin() c.end() c.rbegin() c.rend() c.front() c.back()
// 修改
c.push_back(val) c.pop_back()
c.insert(pos, val) c.insert(pos, n, val) c.insert(pos, beg, end)
c.erase(pos) c.erase(beg, end) c.clear()
c.assign(beg, end) c.assign(n, val)
c.swap(other)
// vector/deque 專有
c.capacity() c.reserve(n) c[i] c.at(i)
// list 專有
c.push_front(val) c.pop_front()
c.merge(other) c.remove(val) c.remove_if(pred)
c.reverse() c.sort() c.unique()
c.splice(pos, other) c.splice(pos, other, beg, end)
關聯容器通用接口
// 查找
c.find(key) // 返回迭代器
c.count(key) // 0/1 或 多重容器計數
c.lower_bound(key) // 首個 ≥ key
c.upper_bound(key) // 首個 > key
c.equal_range(key) // pair
// 修改
c.insert(val) // pair (set/map)
c.insert(beg, end) // 範圍插入
c.erase(key) // 返回刪除計數
c.erase(pos) c.erase(beg, end) c.clear()
// 比較函數對象
c.key_comp() c.value_comp()
// map 專有
c[key] // 若無則插入值初始化
容器適配器接口
// stack
s.push(val) s.pop() s.top() s.empty() s.size()
// queue
q.push(val) q.pop() q.front() q.back() q.empty() q.size()
// priority_queue
pq.push(val) pq.pop() pq.top() pq.empty() pq.size()
// 通用
c1 = c2 比較運算符 == != < <= > >=
string 專用接口精選
// 查找 (返回 size_type, npos 表示未找到)
s.find(str/char, pos) s.rfind(str/char, pos)
s.find_first_of(str/char, pos) s.find_last_not_of(str/char, pos)
// 修改
s.append(str) s.push_back(ch)
s.insert(pos, str) s.erase(pos, len)
s.replace(pos, len, str) s.assign(str)
// 子串
s.substr(pos, len)
// C 風格互轉
s.c_str() // 以 \0 結尾,不可修改
s.data() // 不保證 \0 結尾
s.copy(buf, len, pos)
// 輸入
getline(cin, s) getline(cin, s, delim)
選型決策樹
- 需隨機訪問 →
vector / deque
- 頻繁中間插刪 →
list
- 需有序、去重、區間查詢 →
set / map
- 需可重複鍵 →
multiset / multimap
- 無序、極致查找速度 →
unordered_set / unordered_map (C++11)
- 棧/隊列/優先隊列語義 → 適配器