首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

C++ STL 標準模板庫入門:list 容器完整操作指南

     編輯:關於VC++

前言

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 等隨機存取運算

通用演算法應用

count / count_if:統計元素個數


// 精確值統計
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());

find / find_if:查找元素


// 精確查找
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/backO(1)
insert/erase (迭代器位置)O(1)不需搬移元素
隨機存取不支援需用 vector/deque
搜尋O(N)線性掃描
排序O(N log N)merge sort 實作

選擇建議

  • 頻繁頭尾/中間插入刪除、不需隨機存取 → list。
  • 需隨機存取、尾端高效插入 → vector。
  • 需頭尾高效插入、隨機存取 → deque。

掌握 list 迭代器遍歷與通用演算法配合,是高效運用 STL 關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved