高级篇 · 1.3 · 中级
STL迭代器与常用算法
迭代器:容器与算法之间的桥
迭代器(iterator)的行为很像指针:*it 取当前元素、++it 移到下一个。算法不直接操作容器,而是通过迭代器区间工作——sort(v.begin(), v.end()) 里的 [begin, end) 是左闭右开区间:begin() 指向首元素,end() 指向"最后一个元素的后面"(尾后位置),end 不可解引用。判断"找没找到"的通用写法就是 find(...) == v.end()。
常用算法速查(都在 <algorithm>)
| 算法 | 功能 | 示例 |
|---|---|---|
| sort | 区间升序排序 | sort(v.begin(), v.end()) |
| reverse | 区间逆置 | reverse(v.begin(), v.end()) |
| find | 查找值,返回迭代器 | find(v.begin(), v.end(), x) |
| count | 统计某值出现次数 | count(v.begin(), v.end(), x) |
| max_element / min_element | 最大/最小元素的迭代器 | *max_element(v.begin(), v.end()) |
| accumulate | 区间求和(在 <numeric>) | accumulate(v.begin(), v.end(), 0) |
| for_each | 对每个元素执行操作 | for_each(v.begin(), v.end(), f) |
自定义排序规则
sort 的第三参数是"比较函数"(谓词),返回"第一个参数应排在前面"的真假:greater<int>() 是现成的降序比较器;也可以写函数或 lambda(下一节详讲)。
区间约定的通用性
所有算法都吃"迭代器对":find、count 既能用于 vector,也能用于普通数组——find(a, a + n, x),因为数组名就是首地址。还有两个带谓词的变体 find_if、count_if:第三个参数是"返回 bool 的函数",例如 count_if(v.begin(), v.end(), [](int x){ return x >= 90; }) 可以直接统计不低于 90 分的人数。考法提醒
① 判断 end() 能否解引用(不能!);② 读代码写 sort/reverse 后的序列;③ 降序排序怎么写(greater<int>() 或自定义比较函数);④ find 失败时返回什么(end())。迭代器也有"等级"
vector 的迭代器是随机访问的(可 it+3);list 的是双向的(只能 ++/--)。所以 std::sort 不能用于 list——list 有自己的成员函数 lst.sort()。这是"为什么容器还有同名成员函数"的典型答案。避坑指南
解引用 end()
错误写法
vector<int> v = {1, 2, 3};
cout << *v.end(); // 错误: end是尾后位置, 不指向任何元素正确写法
vector<int> v = {1, 2, 3};
cout << *(v.end() - 1); // 正确: 最后一个元素
cout << v.back(); // 更推荐这一句end() 只是"最后一格后面的标记",解引用是未定义行为。取末元素用 back() 或 *(end()-1)。
sort 区间少排最后一个元素
错误写法
vector<int> v = {3, 1, 2, 5};
sort(v.begin(), v.end() - 1); // 只排了前3个, 5留在外面
// 本例结果 1 2 3 5 恰好"看起来有序"纯属侥幸;
// 若末元素比前面小(如 {3,1,2,0})会得到 1 2 3 0, 整体并未有序正确写法
vector<int> v = {3, 1, 2, 5};
sort(v.begin(), v.end()); // 完整区间 [begin, end)左闭右开区间下,"全部排序"就是 [begin, end)。误写成 end()-1 会把最后一个元素排除在外,区间含义最容易在这里出错。
对 list 使用 std::sort
错误写法
list<int> lst = {3, 1, 2};
sort(lst.begin(), lst.end()); // 编译错误: list迭代器不支持随机访问正确写法
list<int> lst = {3, 1, 2};
lst.sort(); // 使用list自己的成员函数sortstd::sort 内部需要跳到任意位置(随机访问),list 的双向迭代器做不到,直接编译失败。list 用成员函数 lst.sort(),这类"容器与算法的适配问题"是判断题常客。
代码实践
迭代器遍历 + 六大常用算法
先用迭代器手动遍历,再让 sort / reverse / max_element / min_element / accumulate / count 各展身手。
algo_basics.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
void show(const vector<int>& v) {
for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
cout << *it << " ";
cout << endl;
}
int main() {
vector<int> v;
v.push_back(8);
v.push_back(3);
v.push_back(9);
v.push_back(3);
v.push_back(5);
cout << "原始: "; show(v);
sort(v.begin(), v.end()); // 升序排序
cout << "sort后: "; show(v);
reverse(v.begin(), v.end()); // 整体逆置
cout << "reverse后: "; show(v);
cout << "最大值: " << *max_element(v.begin(), v.end()) << endl;
cout << "最小值: " << *min_element(v.begin(), v.end()) << endl;
cout << "总和: " << accumulate(v.begin(), v.end(), 0) << endl;
cout << "3的个数: " << count(v.begin(), v.end(), 3) << endl;
return 0;
}预期输出
原始: 8 3 9 3 5
sort后: 3 3 5 8 9
reverse后: 9 8 5 3 3
最大值: 9
最小值: 3
总和: 28
3的个数: 2for (it = v.begin(); it != v.end(); ++it)是迭代器遍历的标准三段式,判等用!=而非<。max_element返回的是迭代器,解引用*才是值。accumulate(v.begin(), v.end(), 0)从 0 开始累加,头文件是<numeric>。- sort 后为 3 3 5 8 9,再 reverse 得 9 8 5 3 3——两个操作的结果要能口算出来。
find 查找、erase 删除与降序排序
find 的"找到/没找到"判断、边遍历边安全删除元素、用 greater<int>() 做降序排序,三个高频考点一网打尽。
find_erase.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v;
v.push_back(10);
v.push_back(45);
v.push_back(30);
v.push_back(45);
v.push_back(20);
// find: 返回首个匹配元素的迭代器, 找不到返回end()
vector<int>::iterator pos = find(v.begin(), v.end(), 30);
if (pos != v.end())
cout << "找到30, 下标: " << pos - v.begin() << endl;
if (find(v.begin(), v.end(), 99) == v.end())
cout << "没有99" << endl;
// 边遍历边删除所有45: erase返回下一个有效迭代器
vector<int>::iterator it = v.begin();
while (it != v.end()) {
if (*it == 45) it = v.erase(it);
else ++it;
}
cout << "删除45后: ";
for (it = v.begin(); it != v.end(); ++it) cout << *it << " ";
cout << endl;
// 降序排序: 传入比较器 greater<int>()
sort(v.begin(), v.end(), greater<int>());
cout << "降序: ";
for (it = v.begin(); it != v.end(); ++it) cout << *it << " ";
cout << endl;
return 0;
}预期输出
找到30, 下标: 2
没有99
删除45后: 10 30 20
降序: 30 20 10 pos - v.begin()两个迭代器相减得到下标(vector 支持)。- 删除循环的骨架必须背下来:
it = v.erase(it)接住新位置,只有不删时才++it。 greater<int>()是预定义函数对象,加上它 sort 就变成降序。- 删除45后剩 10 30 20,降序即 30 20 10。
巩固练习
max_element 与 min_element · 简单
对
4, 12, 7, 1 使用 max_element 和 min_element 输出最大值与最小值。提示
这两个函数返回迭代器,别忘了前面的
*。参考解答
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int data[4] = {4, 12, 7, 1};
vector<int> v(data, data + 4);
cout << "最大值: " << *max_element(v.begin(), v.end()) << endl;
cout << "最小值: " << *min_element(v.begin(), v.end()) << endl;
return 0;
}预期输出
最大值: 12
最小值: 1count 统计出现次数 · 简单
统计
90, 85, 90, 70, 90 中 90 分出现的次数。提示
count(v.begin(), v.end(), 90) 直接返回次数。参考解答
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int data[5] = {90, 85, 90, 70, 90};
vector<int> v(data, data + 5);
cout << "90出现了: " << count(v.begin(), v.end(), 90) << "次" << endl;
return 0;
}预期输出
90出现了: 3次降序排序输出 · 中等
把
5, 1, 9, 3 按从大到小排序后输出(用 sort + greater 或自定义比较函数两种方式任选其一)。提示
sort(v.begin(), v.end(), greater<int>()); 需要包含 <functional>(很多编译器经 <algorithm> 间接引入,但显式写出更稳妥)。参考解答
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main() {
int data[4] = {5, 1, 9, 3};
vector<int> v(data, data + 4);
sort(v.begin(), v.end(), greater<int>());
for (int i = 0; i < (int)v.size(); ++i) cout << v[i] << " ";
cout << endl;
return 0;
}预期输出
9 5 3 1 删除 vector 中所有偶数 · 困难
对
1, 2, 3, 4, 5, 6 删除全部偶数后输出剩余元素及当前 size。提示
复用"边遍历边删除"骨架:
it = v.erase(it) / else ++it;判偶用 *it % 2 == 0。参考解答
#include <iostream>
#include <vector>
using namespace std;
int main() {
int data[6] = {1, 2, 3, 4, 5, 6};
vector<int> v(data, data + 6);
vector<int>::iterator it = v.begin();
while (it != v.end()) {
if (*it % 2 == 0) it = v.erase(it);
else ++it;
}
cout << "剩余: ";
for (it = v.begin(); it != v.end(); ++it) cout << *it << " ";
cout << endl;
cout << "size=" << v.size() << endl;
return 0;
}预期输出
剩余: 1 3 5
size=3延伸阅读
cppreference:算法库总览
sort/find/count 等全部标准算法的分类索引
cppreference:迭代器库
迭代器分类(输入/输出/前向/双向/随机访问)与适配器
Wandbox
运行本节算法示例,观察 sort 与迭代器的行为