C++ 標準庫容器與算法淺析(附模板入門 + 全示例用法)
在 Python 中,標準容器使用非常直觀,如 list、dict、set 等。而在 C++ 中,標準模板庫 STL 提供了功能強大但略顯復雜的泛型容器體系。本篇將完整梳理 C++ 中常用容器的使用方式、操作方法,并結(jié)合泛型模板與算法庫,作為 C++ 泛型編程的入門實戰(zhàn)筆記。
STL 簡介
STL(Standard Template Library)是 C++ 的標準模板庫,核心組成包括:
- ? 容器(Container):如 
vector,map,set,stack,queue等 - ? 算法(Algorithm):如 
sort,find,count_if,for_each等 - ? 迭代器(Iterator):用于遍歷容器,作為容器和算法之間的橋梁
 - ? 函數(shù)對象(Function Object):如比較器、Lambda 表達式
 
?? 1. 常用容器與典型操作大全
vector(動態(tài)數(shù)組)
#include <vector>
#include <iostream>
using namespace std;
int main() {
    vector<int> nums = {1, 2, 3};           // 初始化
    nums.push_back(4);                      // 添加元素
    nums[1] = 10;                           // 修改元素
    cout << nums.at(1) << endl;            // 安全訪問(帶范圍檢查)
    nums.pop_back();                        // 刪除末尾元素
    cout << "Size: " << nums.size() << endl;
    // 遍歷 - 推薦方式
    for (const auto& val : nums) {          // const 避免拷貝 & 引用提升性能
        cout << val << " ";
    }
    nums.clear();                           // 清空所有元素
}// 輸出
10
Size: 3
1 10 3特性:連續(xù)內(nèi)存,支持隨機訪問。類似 Python 中的 list。
list(雙向鏈表)
#include <list>
#include <iostream>
using namespace std;
int main() {
    list<int> lst = {1, 2, 3};              // 初始化
    lst.push_back(4);                       // 添加到尾部
    lst.push_front(0);                      // 添加到頭部
    lst.remove(2);                          // 刪除值為 2 的元素
    lst.reverse();                          // 反轉(zhuǎn)鏈表
    for (auto it = lst.begin(); it != lst.end(); ++it) {
        cout << *it << " ";
    }
}// 輸出
4 3 1 0特性:雙向鏈表,插入刪除效率高。不支持隨機訪問。Python 中無對應結(jié)構(gòu)。
map(有序字典)
#include <map>
#include <iostream>
using namespace std;
int main() {
    map<string, int> scores;               // 默認升序(基于 <)
    scores["Tom"] = 90;
    scores["Jerry"] = 85;
    scores.erase("Tom");                   // 刪除元素
    cout << scores.count("Tom") << endl;   // 查找元素
    cout << scores.count("Jerry") << endl;   // 查找元素
    for (const auto& [key, val] : scores) { // 結(jié)構(gòu)化綁定(C++17 起)
        cout << key << ": " << val << endl;
    }
    scores.clear();                        // 清空
}// 輸出
0
1
Jerry: 85特性:紅黑樹實現(xiàn),有序存儲。類似 Python 的 dict(但有序性不同)。
unordered_map(無序字典)
#include <unordered_map>
#include <iostream>
using namespace std;
int main() {
    unordered_map<string, int> freq = {
        {"a", 1}, {"b", 2}
    };
    freq["c"] = 3;                           // 添加新鍵值對(自動插入)
    if (freq.find("a") != freq.end()) {     // 使用 find 查找鍵
        cout << "Found a" << endl;
    }
    for (const auto& [key, val] : freq) {   // C++17 結(jié)構(gòu)化綁定遍歷
        cout << key << ": " << val << endl;
    }
}// 輸出
Found a
b: 2
c: 3
a: 1特性:哈希表實現(xiàn),無序存儲。性能優(yōu)于 map,但不保證順序。
set(有序集合)
#include <set>
#include <iostream>
using namespace std;
int main() {
    set<int> s = {3, 1, 4, 1, 2};           // 自動去重,默認升序排序
    s.insert(5);                            // 插入元素
    s.erase(1);                             // 刪除特定元素
    for (int val : s) {                     // 范圍 for 遍歷
        cout << val << endl;
    }
    cout << "Has 4? " << (s.count(4) > 0) << endl; // 查找元素
}// 輸出
2
3
4
5
Has 4? 1類似 Python 的 set,但 C++ 中默認是有序集合。
unordered_set(無序集合)
#include <unordered_set>
#include <iostream>
using namespace std;
int main() {
    unordered_set<string> tags = {"cpp", "stl", "template"}; // 初始化集合
    tags.insert("lambda");                   // 插入新元素
    tags.erase("stl");                       // 刪除已有元素
    for (const auto& tag : tags) {           // 遍歷所有元素(順序不保證)
        cout << tag << endl;
    }
}// 輸出
lambda
template
cpp與 set 類似但不排序,哈希實現(xiàn),插入/刪除性能更高。
tuple(固定結(jié)構(gòu)組)
#include <tuple>
#include <iostream>
using namespace std;
int main() {
    tuple<int, string, double> t(1, "hello", 3.14); // 定義一個三元組
    cout << get<0>(t) << endl;   // 訪問第一個元素(索引從 0 開始)
    cout << get<1>(t) << endl;   // 第二個元素
}// 輸出
1
hello可用于函數(shù)返回多個值,類似 Python 中的 tuple。但類型必須聲明。
stack(棧)
#include <stack>
#include <iostream>
using namespace std;
int main() {
    stack<int> stk;
    stk.push(1);                          // 入棧
    stk.push(2);
    cout << stk.top() << endl;           // 查看棧頂元素(不移除)
    stk.pop();                           // 彈出棧頂
}// 輸出
2LIFO(后進先出)結(jié)構(gòu)。Python 中需手動實現(xiàn)。
queue(隊列)
#include <queue>
#include <iostream>
using namespace std;
int main() {
    queue<int> q;
    q.push(1);                           // 入隊(添加到尾部)
    q.push(2);
    cout << q.front() << endl;          // 查看隊首元素
    q.pop();                            // 出隊(移除隊首)
}// 輸出
1FIFO(先進先出)結(jié)構(gòu)。常用于任務調(diào)度。
priority_queue(優(yōu)先隊列 / 堆)
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
int main() {
    priority_queue<int> pq;             // 默認是最大堆(較大元素優(yōu)先)
    pq.push(3);
    pq.push(1);
    pq.push(5);
    while (!pq.empty()) {
        cout << pq.top() << " ";        // 取堆頂元素(最大值)
        pq.pop();                       // 移除堆頂
    }
}// 輸出
5 3 1等價于 Python 的 heapq(但默認是最大堆)
算法函數(shù)使用示例
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
    vector<int> v = {5, 3, 8, 1};
    cout << "原始數(shù)據(jù): ";
    for (int x : v) cout << x << " ";
    cout << endl;
    sort(v.begin(), v.end()); // 升序排序
    cout << "排序后: ";
    for (int x : v) cout << x << " ";
    cout << endl;
    reverse(v.begin(), v.end()); // 反轉(zhuǎn)
    cout << "反轉(zhuǎn)后: ";
    for (int x : v) cout << x << " ";
    cout << endl;
    auto it = find(v.begin(), v.end(), 3); // 查找值為3
    if (it != v.end()) {
        cout << "找到元素 3,位置索引為: " << distance(v.begin(), it) << endl;
    } else {
        cout << "未找到元素 3" << endl;
    }
    // 使用 Lambda 表達式統(tǒng)計 >4 的數(shù)量
    int cnt = count_if(v.begin(), v.end(), [](int x){ return x > 4; });
    cout << "大于 4 的元素個數(shù): " << cnt << endl;
    return 0;
}// 輸出
原始數(shù)據(jù): 5381
排序后: 1358
反轉(zhuǎn)后: 8531
找到元素 3,位置索引為: 2
大于 4 的元素個數(shù): 2模板函數(shù)入門
#include <iostream>  // ?? 引入輸入輸出流頭文件
// 泛型函數(shù),編譯期根據(jù)類型生成對應版本
template<typename T>
T max_val(T a, T b) {
    return (a > b) ? a : b;
}
int main(){
    // 使用方式
    std::cout << max_val(3, 7) << std::endl;       // int
    std::cout << max_val(3.14, 2.71) << std::endl; // double
    return 0;
}// 輸出
7
3.14與 Python 動態(tài)類型類似,但 C++ 在編譯期完成類型匹配與優(yōu)化,性能更高,錯誤更早暴露。
綜合實例
#include <iostream>      // 標準輸入輸出流
#include <vector>        // STL 動態(tài)數(shù)組容器
#include <algorithm>     // STL 算法頭,如 count_if
// 泛型函數(shù):統(tǒng)計 vector 中大于指定閾值的元素個數(shù)
// 模板函數(shù)接收任意類型的 vector,如 int、double 等
template<typename T>
int count_gt(const std::vector<T>& vec, T threshold) {
    // std::count_if 用于統(tǒng)計滿足條件的元素數(shù)量
    // Lambda 表達式 [=](T x){...} 捕獲 threshold 變量,判斷 x > threshold
    return std::count_if(vec.begin(), vec.end(), [=](T x) {
        return x > threshold;
    });
}
int main() {
    // 示例 1:整型向量
    std::vector<int> iv = {1, 4, 2, 7, 5};      // 初始化 int 類型 vector
    // 示例 2:浮點型向量
    std::vector<double> dv = {1.2, 2.5, 0.9, 3.3}; // 初始化 double 類型 vector
    // 調(diào)用模板函數(shù) count_gt,判斷元素 > 3 的數(shù)量
    // 輸出結(jié)果應為:3 (即 4, 7, 5)
    std::cout << count_gt(iv, 3) << std::endl;
    // 浮點數(shù)版本,判斷元素 > 1.5 的數(shù)量
    // 輸出結(jié)果應為:2 (即 2.5, 3.3)
    std::cout << count_gt(dv, 1.5) << std::endl;
    return 0;
}// 輸出
3
2?? 模板函數(shù) count_gt 支持任意類型容器,搭配 Lambda 與 STL 算法實現(xiàn)靈活、類型安全的復用邏輯。
小結(jié)
? STL 提供了結(jié)構(gòu)統(tǒng)一、高效、安全的容器與算法組合,是 C++ 開發(fā)的核心工具
? 多數(shù)容器功能可類比 Python,但類型系統(tǒng)更強、性能更高
? 模板與算法使 C++ 代碼更通用、復用性更強
? 推薦從 vector, map, set, tuple 入門,逐步掌握 stack, queue, priority_queue















 
 
 

 
 
 
 