字数 1971,阅读大约需 10 分钟
在 Python 中,标准容器使用非常直观,如 list
、dict
、set
等。而在 C++ 中,标准模板库 STL 提供了功能强大但略显复杂的泛型容器体系。本篇将完整梳理 C++ 中常用容器的使用方式、操作方法,并结合泛型模板与算法库,作为 C++ 泛型编程的入门实战笔记。
STL(Standard Template Library)是 C++ 的标准模板库,核心组成包括:
vector
, map
, set
, stack
, queue
等sort
, find
, count_if
, for_each
等#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
📌 特性:连续内存,支持随机访问。类似 Python 中的 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(); // 反转链表
for (auto it = lst.begin(); it != lst.end(); ++it) {
cout << *it << " ";
}
}
// 输出
4 3 1 0
📌 特性:双向链表,插入删除效率高。不支持随机访问。Python 中无对应结构。
#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) { // 结构化绑定(C++17 起)
cout << key << ": " << val << endl;
}
scores.clear(); // 清空
}
// 输出
0
1
Jerry: 85
📌 特性:红黑树实现,有序存储。类似 Python 的 dict
(但有序性不同)。
#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 结构化绑定遍历
cout << key << ": " << val << endl;
}
}
// 输出
Found a
b: 2
c: 3
a: 1
📌 特性:哈希表实现,无序存储。性能优于 map
,但不保证顺序。
#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++ 中默认是有序集合。
#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
类似但不排序,哈希实现,插入/删除性能更高。
#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
📌 可用于函数返回多个值,类似 Python 中的 tuple
。但类型必须声明。
#include <stack>
#include <iostream>
using namespace std;
int main() {
stack<int> stk;
stk.push(1); // 入栈
stk.push(2);
cout << stk.top() << endl; // 查看栈顶元素(不移除)
stk.pop(); // 弹出栈顶
}
// 输出
2
📌 LIFO(后进先出)结构。Python 中需手动实现。
#include <queue>
#include <iostream>
using namespace std;
int main() {
queue<int> q;
q.push(1); // 入队(添加到尾部)
q.push(2);
cout << q.front() << endl; // 查看队首元素
q.pop(); // 出队(移除队首)
}
// 输出
1
📌 FIFO(先进先出)结构。常用于任务调度。
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
int main() {
priority_queue<int> pq; // 默认是最大堆(较大元素优先)
pq.push(3);
pq.push(1);
pq.push(5);
while (!pq.empty()) {
cout << pq.top() << " "; // 取堆顶元素(最大值)
pq.pop(); // 移除堆顶
}
}
// 输出
5 3 1
📌 等价于 Python 的 heapq
(但默认是最大堆)
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v = {5, 3, 8, 1};
cout << "原始数据: ";
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()); // 反转
cout << "反转后: ";
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 表达式统计 >4 的数量
int cnt = count_if(v.begin(), v.end(), [](int x){ return x > 4; });
cout << "大于 4 的元素个数: " << cnt << endl;
return 0;
}
// 输出
原始数据: 5381
排序后: 1358
反转后: 8531
找到元素 3,位置索引为: 2
大于 4 的元素个数: 2
#include <iostream> // ⬅️ 引入输入输出流头文件
// 泛型函数,编译期根据类型生成对应版本
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 动态类型类似,但 C++ 在编译期完成类型匹配与优化,性能更高,错误更早暴露。
#include <iostream> // 标准输入输出流
#include <vector> // STL 动态数组容器
#include <algorithm> // STL 算法头,如 count_if
// 泛型函数:统计 vector 中大于指定阈值的元素个数
// 模板函数接收任意类型的 vector,如 int、double 等
template<typename T>
int count_gt(const std::vector<T>& vec, T threshold) {
// std::count_if 用于统计满足条件的元素数量
// 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
// 调用模板函数 count_gt,判断元素 > 3 的数量
// 输出结果应为:3 (即 4, 7, 5)
std::cout << count_gt(iv, 3) << std::endl;
// 浮点数版本,判断元素 > 1.5 的数量
// 输出结果应为:2 (即 2.5, 3.3)
std::cout << count_gt(dv, 1.5) << std::endl;
return 0;
}
// 输出
3
2
🧠 模板函数 count_gt
支持任意类型容器,搭配 Lambda 与 STL 算法实现灵活、类型安全的复用逻辑。
vector
, map
, set
, tuple
入门,逐步掌握 stack
, queue
, priority_queue
📚 延伸阅读:
[1]
studycpp STL 总览: https://www.studycpp.cn/cpp/stl-overview/
[2]
cppreference STL 容器: https://en.cppreference.com/w/cpp/container
[3]
菜鸟教程 STL 教程: https://www.runoob.com/cplusplus/cpp-stl-tutorial.html