掌握 C++ std::list:语法、函数与实战示例
什么是 std::list?
在 C++ 中,std::list 是一种序列容器,以双向链表形式存储元素。这种结构允许在常数时间内于任意位置插入或删除元素,并支持双向迭代。虽然它不像 std::vector 那样提供快速随机访问,但在频繁插入或删除的场景下表现出色。
容器通过分配器自动管理内存,因此可以在运行时从两端动态增长或收缩。
为什么使用 std::list?
- 在序列任意位置进行常数时间插入和删除。
- 适合频繁移动元素的算法。
- 容器大小不可预测变化时的理想选择。
定义列表
要使用 std::list,需包含 <list> 头文件:
#include <list> // 模板定义 // template<class T, class Alloc = std::allocator<T>> class list;
参数说明:
T– 存储的元素类型,允许任何可复制构造的类型。Alloc– 分配器类型,默认std::allocator通常足够。
示例 1:基本遍历
#include <iostream>
#include <list>
int main() {
std::list<int> my_list{12, 5, 10, 9};
for (int x : my_list) {
std::cout << x << '\n';
}
}
输出:

常用 std::list 操作
| 函数 | 说明 |
|---|---|
insert() | 在迭代器位置前插入元素。 |
push_back() | 在末尾添加元素。 |
push_front() | 在开头添加元素。 |
pop_front() | 移除首个元素。 |
size() | 返回元素数量。 |
front() | 访问首个元素。 |
back() | 访问最后一个元素。 |
reverse() | 反转元素顺序。 |
merge() | 将两个已排序的列表合并为一个。 |
构造函数
std::list()– 默认构造函数,创建空列表。std::list(n)– 填充构造函数,创建n个默认构造的元素。std::list(first, last)– 范围构造函数,从另一范围复制元素。std::list(const list&)– 拷贝构造函数。std::list(list&&)– 移动构造函数。std::list(std::initializer_list<T>)– 初始化列表构造函数。
示例 2:构造函数变体
#include <iostream>
#include <list>
int main() {
std::list<int> l; // 空列表
std::list<int> l1{10, 20, 30};
std::list<int> l2(l1.begin(), l1.end()); // 范围拷贝
std::list<int> l3(std::move(l1)); // 移动
std::cout << "Size of l: " << l.size() << '\n';
std::cout << "Contents of l2:\n";
for (int x : l2) std::cout << x << '\n';
std::cout << "Contents of l3:\n";
for (int x : l3) std::cout << x << '\n';
}
输出:

容器特性
- 序列 – 元素按线性顺序存储,可通过位置访问。
- 双向链表 – 每个节点知晓前驱和后继,支持常数时间插入/删除。
- 分配器感知 – 使用分配器按需请求内存。
插入元素
使用 push_front、push_back 或 insert 添加元素。
示例 3:混合插入
#include <algorithm>
#include <iostream>
#include <list>
int main() {
std::list<int> my_list{12, 5, 10, 9};
my_list.push_front(11); // 头部
my_list.push_back(18); // 尾部
auto it = std::find(my_list.begin(), my_list.end(), 10);
if (it != my_list.end()) {
my_list.insert(it, 21); // 在 10 之前插入
}
for (int x : my_list) std::cout << x << '\n';
}
输出:

删除元素
使用 erase 移除单个元素或范围。
示例 4:擦除演示
#include <iostream>
#include <list>
int main() {
std::list<int> my_list{12, 5, 10, 9};
std::cout << "删除前:\n";
for (int x : my_list) std::cout << x << '\n';
my_list.erase(my_list.begin()); // 移除首个
std::cout << "删除后:\n";
for (int x : my_list) std::cout << x << '\n';
}
输出:

核心要点
std::list是双向链表序列容器。- 任意位置插入/删除均为常数时间。
- 支持双向顺序遍历。
- 随机访问效率低;需快速索引时请用
std::vector。 - 构造函数、迭代器和分配器感知使
std::list适合动态数据集。
C语言
- C++ 运算符全解析:类型、示例与示例程序
- C++ do-while 循环详解:语法、实战示例与嵌套循环
- 掌握 C++ switch-case:语法、用法与实战示例
- C++ 动态数组分配实战指南:new/delete、初始化、扩容与内存管理
- C++ 指针精通:核心概念、代码示例与实战应用
- C++ 运算符重载实战指南:语法、方法、限制与代码示例
- C++ 结构体详解:定义、初始化、指针、函数参数与局限性
- C++ 函数详解:从声明到调用的实战指南
- C++ Struct 与 Class 核心差异、语法及最佳实践
- Python collections.Counter:高效计数、更新与算术运算
- Python list.count() 专家指南:语法、示例与性能解析
- Python list.index() 详解:查找元素位置的实用指南与示例