跳转到主要内容
后端开发 · C/C++标准库和新特性

C++标准库STL介绍

最后核对于 2026-07-26推断

一、STL概述

STL(Standard Template Library,标准模板库)是C++标准库的核心组成部分,提供了一系列通用的模板类和函数,实现了常见的数据结构和算法。STL的设计基于泛型编程思想,具有高度的可重用性和灵活性。

STL由以下六大组件构成:

  1. 容器(Containers)
  2. 迭代器(Iterators)
  3. 算法(Algorithms)
  4. 仿函数(Functors)
  5. 适配器(Adapters)
  6. 分配器(Allocators)

二、容器(Containers)

1. 序列容器

vector

CPP
#include <vector>
std::vector<int> v;          // 创建空vector
v.push_back(10);             // 末尾添加元素
v.pop_back();                // 删除末尾元素
v.size();                    // 获取元素数量
v[0];                        // 访问元素
v.insert(v.begin()+1, 20);   // 在指定位置插入元素
v.erase(v.begin()+1);        // 删除指定位置元素

deque

CPP
#include <deque>
std::deque<int> dq;          // 双端队列
dq.push_back(10);            // 末尾添加
dq.push_front(20);           // 头部添加
dq.pop_back();               // 末尾删除
dq.pop_front();              // 头部删除

list

CPP
#include <list>
std::list<int> lst;          // 双向链表
lst.push_back(10);
lst.push_front(20);
lst.pop_back();
lst.pop_front();
lst.sort();                  // 链表排序
lst.merge(other_lst);        // 合并链表

forward_list (C++11)

CPP
#include <forward_list>
std::forward_list<int> flst;  // 单向链表
flst.push_front(10);
flst.pop_front();

array (C++11)

CPP
#include <array>
std::array<int, 5> arr = {1,2,3,4,5};  // 固定大小数组
arr.size();
arr[0];

2. 关联容器

set

CPP
#include <set>
std::set<int> s;             // 有序不重复集合
s.insert(10);
s.erase(10);
s.find(10);                  // 返回迭代器,找不到返回s.end()
s.count(10);                 // 返回元素数量(0或1)

multiset

CPP
#include <set>
std::multiset<int> ms;       // 有序可重复集合
ms.insert(10);
ms.insert(10);               // 允许重复
ms.count(10);                // 可能大于1

map

CPP
#include <map>
std::map<std::string, int> m; // 键值对映射
m["apple"] = 5;              // 插入或修改
m.insert({"banana", 3});      // 插入
m.erase("apple");            // 删除
m.find("apple");             // 查找
for(auto& [key, value] : m)  // C++17结构化绑定
    std::cout << key << ": " << value;

multimap

CPP
#include <map>
std::multimap<std::string, int> mm; // 允许重复键的映射
mm.insert({"apple", 5});
mm.insert({"apple", 6});     // 允许相同键

unordered_set (C++11)

CPP
#include <unordered_set>
std::unordered_set<int> us;  // 哈希集合
us.insert(10);
us.erase(10);

unordered_map (C++11)

CPP
#include <unordered_map>
std::unordered_map<std::string, int> um; // 哈希映射
um["apple"] = 5;
um.erase("apple");

3. 容器适配器

stack

CPP
#include <stack>
std::stack<int> s;           // 栈
s.push(10);
s.pop();
s.top();
s.empty();

queue

CPP
#include <queue>
std::queue<int> q;           // 队列
q.push(10);
q.pop();
q.front();
q.empty();

priority_queue

CPP
#include <queue>
std::priority_queue<int> pq; // 优先队列(默认大顶堆)
pq.push(10);
pq.pop();
pq.top();

三、迭代器(Iterators)

迭代器提供了访问容器元素的统一接口,分为五类:

  1. 输入迭代器
  2. 输出迭代器
  3. 前向迭代器
  4. 双向迭代器
  5. 随机访问迭代器
CPP
std::vector<int> v = {1,2,3,4,5};

// 正向遍历
for(auto it = v.begin(); it != v.end(); ++it) {
    std::cout << *it << " ";
}

// 反向遍历
for(auto it = v.rbegin(); it != v.rend(); ++it) {
    std::cout << *it << " ";
}

// C++11范围for循环
for(int num : v) {
    std::cout << num << " ";
}

四、算法(Algorithms)

1. 非修改序列算法

CPP
#include <algorithm>
#include <numeric>

std::vector<int> v = {1,2,3,4,5};

// 查找
auto it = std::find(v.begin(), v.end(), 3);
bool exists = std::binary_search(v.begin(), v.end(), 3); // 有序序列

// 计数
int cnt = std::count(v.begin(), v.end(), 3);

// 最值
auto min_it = std::min_element(v.begin(), v.end());
auto max_it = std::max_element(v.begin(), v.end());

// 求和
int sum = std::accumulate(v.begin(), v.end(), 0);

// 检查条件
bool all_even = std::all_of(v.begin(), v.end(), [](int x){return x%2==0;});
bool any_even = std::any_of(v.begin(), v.end(), [](int x){return x%2==0;});
bool none_even = std::none_of(v.begin(), v.end(), [](int x){return x%2==0;});

2. 修改序列算法

CPP
// 排序
std::sort(v.begin(), v.end());
std::stable_sort(v.begin(), v.end()); // 稳定排序

// 部分排序
std::partial_sort(v.begin(), v.begin()+3, v.end());

// 第n大元素
std::nth_element(v.begin(), v.begin()+2, v.end());

// 填充
std::fill(v.begin(), v.end(), 0);

// 生成
std::generate(v.begin(), v.end(), [](){return rand()%100;});

// 移除
auto new_end = std::remove(v.begin(), v.end(), 3);
v.erase(new_end, v.end()); // 真正删除

// 去重(需先排序)
std::sort(v.begin(), v.end());
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end());

// 反转
std::reverse(v.begin(), v.end());

// 旋转
std::rotate(v.begin(), v.begin()+2, v.end());

// 洗牌
std::random_shuffle(v.begin(), v.end());

3. 数值算法

CPP
#include <numeric>

// 累加
int sum = std::accumulate(v.begin(), v.end(), 0);

// 内积
int product = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0);

// 部分和
std::vector<int> result(v.size());
std::partial_sum(v.begin(), v.end(), result.begin());

// 相邻差
std::adjacent_difference(v.begin(), v.end(), result.begin());

// 填充递增序列
std::iota(v.begin(), v.end(), 0); // 0,1,2,3,...

五、仿函数(Functors)与Lambda表达式

1. 内置仿函数

CPP
#include <functional>

std::plus<int> add;
int sum = add(10, 20); // 30

std::greater<int> gt;
bool b = gt(10, 20); // false

// 其他常用仿函数:
// minus, multiplies, divides, modulus, negate
// equal_to, not_equal_to, less, less_equal, greater, greater_equal
// logical_and, logical_or, logical_not
// bit_and, bit_or, bit_xor

2. Lambda表达式 (C++11)

CPP
auto lambda = [](int a, int b) { return a + b; };
int sum = lambda(10, 20); // 30

// 捕获列表
int x = 10;
auto lambda2 = [x](int a) { return a + x; };

// 可变lambda
auto lambda3 = [x](int a) mutable { x++; return a + x; };

// 引用捕获
auto lambda4 = [&x](int a) { x += a; };

// 通用捕获 (C++14)
auto lambda5 = [y = x + 1](int a) { return a + y; };

// 模板lambda (C++20)
auto lambda6 = []<typename T>(T a, T b) { return a + b; };

六、适配器(Adapters)

1. 容器适配器

如前所述的stack、queue、priority_queue

2. 迭代器适配器

reverse_iterator

CPP
std::vector<int> v = {1,2,3,4,5};
for(auto it = v.rbegin(); it != v.rend(); ++it) {
    std::cout << *it << " "; // 5 4 3 2 1
}

back_insert_iterator

CPP
std::vector<int> v;
std::back_insert_iterator<std::vector<int>> back_it(v);
*back_it++ = 1; // v.push_back(1);

front_insert_iterator

CPP
std::deque<int> dq;
std::front_insert_iterator<std::deque<int>> front_it(dq);
*front_it++ = 1; // dq.push_front(1);

insert_iterator

CPP
std::vector<int> v = {1,3,5};
std::insert_iterator<std::vector<int>> insert_it(v, v.begin()+1);
*insert_it++ = 2; // v.insert(position, 2);

3. 函数适配器

bind (C++11)

CPP
#include <functional>
using namespace std::placeholders;

void func(int a, int b, int c) {
    std::cout << a << " " << b << " " << c << std::endl;
}

auto f1 = std::bind(func, _1, _2, 100); // 绑定第三个参数为100
f1(10, 20); // 相当于func(10, 20, 100)

auto f2 = std::bind(func, _2, _1, 100); // 交换前两个参数
f2(10, 20); // 相当于func(20, 10, 100)

function (C++11)

CPP
#include <functional>

std::function<int(int, int)> func_obj;
func_obj = [](int a, int b) { return a + b; };
int sum = func_obj(10, 20); // 30

mem_fn

CPP
struct Foo {
    void display(int x) { std::cout << x << std::endl; }
};

Foo foo;
auto display = std::mem_fn(&Foo::display);
display(foo, 10); // 调用foo.display(10)

七、智能指针 (C++11)

CPP
#include <memory>

// unique_ptr (独占所有权)
std::unique_ptr<int> uptr(new int(10));
// auto uptr = std::make_unique<int>(10); // C++14

// shared_ptr (共享所有权)
std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
std::shared_ptr<int> sptr2 = sptr1; // 引用计数增加

// weak_ptr (不增加引用计数)
std::weak_ptr<int> wptr = sptr1;
if(auto spt = wptr.lock()) { // 尝试提升为shared_ptr
    std::cout << *spt << std::endl;
}

八、其他重要组件

1. 字符串处理

CPP
#include <string>
#include <string_view> // C++17

std::string str = "Hello, STL!";
str.substr(7, 3);      // "STL"
str.find("STL");       // 返回位置
str.replace(7, 3, "C++"); // "Hello, C++!"
str += " Welcome!";    // 字符串连接

// C++17 string_view (不拥有字符串)
std::string_view sv = str;
sv.substr(7, 3);       // "C++" (无拷贝)

2. 元组 (C++11)

CPP
#include <tuple>

auto t = std::make_tuple(1, 3.14, "hello");
int a = std::get<0>(t);       // 1
double b = std::get<1>(t);    // 3.14

// C++17结构化绑定
auto [x, y, z] = t;           // x=1, y=3.14, z="hello"

3. 可选值 (C++17)

CPP
#include <optional>

std::optional<int> maybe_int;
maybe_int = 42;
if(maybe_int) {
    std::cout << *maybe_int << std::endl; // 42
}

// 或提供默认值
int value = maybe_int.value_or(0);

4. 变体 (C++17)

CPP
#include <variant>

std::variant<int, double, std::string> v;
v = 3.14;
if(std::holds_alternative<double>(v)) {
    std::cout << std::get<double>(v) << std::endl;
}

// 访问器模式
std::visit([](auto&& arg) {
    using T = std::decay_t<decltype(arg)>;
    if constexpr (std::is_same_v<T, int>)
        std::cout << "int: " << arg;
    else if constexpr (std::is_same_v<T, double>)
        std::cout << "double: " << arg;
    else if constexpr (std::is_same_v<T, std::string>)
        std::cout << "string: " << arg;
}, v);

九、C++20新增特性

1. 范围库 (Ranges)

CPP
#include <ranges>
#include <algorithm>

std::vector<int> v = {1,2,3,4,5,6,7,8,9};

// 过滤偶数并转换平方
auto result = v | std::views::filter([](int x){return x%2==0;})
                | std::views::transform([](int x){return x*x;});

for(int x : result) {
    std::cout << x << " "; // 4 16 36 64
}

// 排序视图
auto sorted = std::views::all(v) | std::ranges::sort;

2. 概念 (Concepts)

CPP
#include <concepts>

template <std::integral T>
T add(T a, T b) {
    return a + b;
}

// 只允许整数类型调用
add(1, 2);    // 正确
add(1.0, 2.0); // 编译错误

3. 格式化库 (Format)

CPP
#include <format>

std::string msg = std::format("Hello, {}! The answer is {}.", "world", 42);
// "Hello, world! The answer is 42."

int a = 10, b = 20;
std::cout << std::format("{} + {} = {}", a, b, a + b);

十、STL最佳实践

  1. 优先使用算法而非循环:尽量使用STL算法替代手写循环,提高代码可读性和安全性。

  2. 选择合适的容器:

    • 需要随机访问:vector、deque、array
    • 频繁插入删除:list、forward_list
    • 需要快速查找:set、map、unordered_set、unordered_map
  3. 使用emplace操作:C++11引入的emplace系列函数可以避免不必要的拷贝/移动。

  4. 利用移动语义:C++11后,STL支持移动语义,可以高效转移资源。

  5. 注意迭代器失效:某些操作(如vector的插入删除)可能导致迭代器失效。

  6. 使用智能指针管理资源:避免内存泄漏。

  7. C++11及以后特性:尽可能使用现代C++特性编写更简洁高效的代码。