std::list 為雙向鏈結串列容器,支援高效率插入/刪除,不支援隨機存取。本文系統整理核心操作與演算法應用。
#include
#include // 通用演算法
int main() {
std::list cList; // 宣告 list 實例
}
cList.push_back('a'); // 尾端插入
cList.push_front('b'); // 頭端插入
if (cList.empty()) {
printf("list is empty");
}
std::list::iterator it;
for (it = cList.begin(); it != cList.end(); ++it) {
printf("%c", *it);
}
// 注意:list 不支援 it + 3 等隨機存取運算
// 精確值統計
int cnt = std::count(cList.begin(), cList.end(), 'b');
// 條件統計:需仿函式
const char target = 'c';
struct IsC {
bool operator()(char& ch) { return ch == target; }
};
int cntIf = std::count_if(cList.begin(), cList.end(), IsC());
// 精確查找
auto it = std::find(cList.begin(), cList.end(), 'c');
if (it == cList.end()) puts("not found");
else printf("found: %c", *it);
// 條件查找
auto it2 = std::find_if(cList.begin(), cList.end(), IsC());
cList.sort(); // 列表專用 sort,O(N log N),穩定排序
// 單一元素插入於迭代器位置之前
cList.insert(cList.end(), 'c'); // 尾端插入等同 push_back
// 範圍插入
char arr[3] = {'a','b','c'};
cList.insert(cList.end(), &arr[0], &arr[3]);
cList.pop_front(); // 刪除首元素
cList.pop_back(); // 刪除尾元素
cList.erase(cList.begin()); // 刪除指定迭代器位置
cList.erase(cList.begin(), cList.end()); // 刪除範圍(清空)
cList.remove('c'); // 刪除所有值為 'c' 的元素
// remove_if 回傳新結尾迭代器(C++11 前標準寫法)
auto newEnd = std::remove(cList.begin(), cList.end(), 'c');
cList.erase(newEnd, cList.end());
| 操作 | 複雜度 | 備註 |
|---|---|---|
| push_front/back | O(1) | |
| insert/erase (迭代器位置) | O(1) | 不需搬移元素 |
| 隨機存取 | 不支援 | 需用 vector/deque |
| 搜尋 | O(N) | 線性掃描 |
| 排序 | O(N log N) | merge sort 實作 |
list。vector。deque。掌握 list 迭代器遍歷與通用演算法配合,是高效運用 STL 關鍵。