摘要
C++ 標準庫中的 `std::list` 是一種雙向鏈表容器,它允許在常數時間內進行插入和刪除操作,每個元素包含一個指向前一個和后一個元素的指針。這給我們開發提供了高效的插入和刪除操作。
引入頭文件
要使用 `std::list`,需要包含頭文件 `<list>`:
#include <list>
創建和初始化
#include <iostream>
#include <list>int main() {std::list<int> l1; // 默認構造函數std::list<int> l2(5, 10); // 創建包含 5 個值為 10 的元素的列表std::list<int> l3 = {1, 2, 3, 4, 5, 6}; // 列表初始化// 輸出列表 l3 的內容for (int n : l3) {std::cout << n << ' ';}std::cout << std::endl;return 0;
}
常用方法和操作
1. 插入和刪除元素
#include <iostream>
#include <list>int main() {std::list<int> l = {1, 2, 3, 4, 5, 6};// 在末尾添加元素l.push_back(6);// 在開頭添加元素l.push_front(0);// 在第三個位置插入元素auto it = l.begin();std::advance(it, 3); // 前進 3 個位置l.insert(it, 99);// 刪除開頭的元素l.pop_front();// 刪除末尾的元素l.pop_back();// 刪除特定位置的元素it = l.begin();std::advance(it, 2); // 前進 2 個位置l.erase(it);// 輸出列表 l 的內容for (int n : l) {std::cout << n << ' ';}std::cout << std::endl;return 0;
}
2. 訪問元素
`std::list` 不支持隨機訪問(即不支持 `operator[]`),但是可以使用迭代器遍歷和訪問元素:
#include <iostream>
#include <list>int main() {std::list<int> l = {1, 2, 3, 4, 5, 6};// 使用迭代器遍歷for (auto it = l.begin(); it != l.end(); ++it) {std::cout << *it << ' ';}std::cout << std::endl;// 使用范圍 for 循環遍歷for (int n : l) {std::cout << n << ' ';}std::cout << std::endl;return 0;
}
3. 反向遍歷
#include <iostream>
#include <list>int main() {std::list<int> l = {1, 2, 3, 4, 5, 6};// 反向遍歷for (auto it = l.rbegin(); it != l.rend(); ++it) {std::cout << *it << ' ';}std::cout << std::endl;return 0;
}
4. 其它用法
#include <iostream>
#include <list>int main() {std::list<int> l = {1, 2, 3, 4, 5, 6};// 獲取列表大小std::cout << "Size: " << l.size() << std::endl;// 檢查是否為空if (l.empty()) {std::cout << "List is empty" << std::endl;} else {std::cout << "List is not empty" << std::endl;}// 清空列表l.clear();std::cout << "Size after clear: " << l.size() << std::endl;return 0;
}
進階使用技巧
1. 合并和排序
#include <iostream>
#include <list>int main() {std::list<int> l1 = {1, 3, 5, 7};std::list<int> l2 = {2, 4, 6, 8};// 合并兩個已排序的列表l1.merge(l2);// 排序l1.sort();// 反轉l1.reverse();// 輸出列表 l1 的內容for (int n : l1) {std::cout << n << ' ';}std::cout << std::endl;return 0;
}
2. 去重
#include <iostream>
#include <list>int main() {std::list<int> l = {1, 2, 2, 3, 3, 3, 4, 5};// 必須先排序,然后去重l.sort();l.unique();// 輸出去重后的列表 l 的內容for (int n : l) {std::cout << n << ' ';}std::cout << std::endl;return 0;
}
自定義比較函數
在 `sort`、`merge` 等方法中,可以傳遞自定義比較函數:
#include <iostream>
#include <list>bool customCompare(int a, int b) {return a > b; // 降序排列
}int main() {std::list<int> l = {1, 3, 2, 5, 4};// 使用自定義比較函數排序l.sort(customCompare);// 輸出排序后的列表 l 的內容for (int n : l) {std::cout << n << ' ';}std::cout << std::endl;return 0;
}
總結
`std::list` 是 C++ 標準庫中功能強大且靈活的雙向鏈表容器,適用于需要頻繁插入和刪除操作的場景。在我們實際開發中,根據項目的具體需求選擇合適的容器,比如‘std::forward_list’等,可以顯著提高代碼性能和可維護性。
引用
std::list - cppreference.com