作者:王昊成(小红书:秋来拾光),无所不能哈基咪
本文由同学分享个人经验,仅供学习交流,严禁倒卖。 具体要求请以学校及学院最新发布的信息为准。
<algorithm>头文件
<algorithm>头文件
sort()函数
sort是 C++ 标准库中的排序函数(定义在<algorithm>头文件中),用于对指定区间内的元素进行排序,默认采用升序排序(从小到大),也可通过自定义规则实现降序或其他排序逻辑。
基础格式(默认升序)
sort(起始迭代器/指针, 结束迭代器/指针, [比较规则]);
参数说明:
起始迭代器:指向排序区间的第一个元素(包含在排序范围内)。
结束迭代器:指向排序区间的 “尾后位置”(不包含在排序范围内,即左闭右开区间[起始, 结束))。
比较器:可以是函数指针、函数对象、Lambda 表达式(最常用),规则是:返回 true 表示第一个参数应排在第二个参数前面,返回 false 则相反。
适用场景:元素类型支持<比较(如int、double、string等)。
#include <iostream>
#include <vector>
#include <algorithm> // 必须包含头文件
using namespace std;
int main() {
vector<int> vec = {5, 2, 9, 1, 5, 6};
sort(vec.begin(), vec.end()); // 对整个vector升序排序
for (int num : vec) {
cout << num << " "; // 输出:1 2 5 5 6 9
}
return 0;
}
降序方式 1:使用 greater<T>()(需包含 <algorithm>)
vector<int> vec = {3, 1, 4, 2};
sort(vec.begin(), vec.end(), greater<int>()); // 降序:4 3 2 1
sort 是个 “通用排序工具”,它不知道你想按什么规则排序(比如升序 / 降序、字符串 ASCII、结构体分数),所以需要通过 Lambda 告诉它:两个元素对比时,谁该在前?
Lambda 返回 true → 表示第一个参数 a 应该排在第二个参数 b 前面;返回 false → 表示 b 应该排在 a 前面。
就是如果满足return后面的条件,a就在b前面
Lambda 比较器的结构固定为:
[](参数1, 参数2) {
// 比较规则:返回 true/false
return 条件;
}
参数 1 / 参数 2:sort 遍历数组 / 容器时,每次取两个待比较的元素(比如 arr[i] 和 arr[i+1]);
返回值:决定这两个元素的前后顺序。
场景 1:排序普通数组(基础用法)
#include <iostream>
#include <algorithm> // 必须包含sort的头文件
using namespace std;
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int len = sizeof(arr) / sizeof(arr[0]); // 数组长度
// 1. 默认升序排序
sort(arr, arr + len); // 范围:[arr, arr+len),即0~len-1
cout << "升序:";
for (int num : arr) cout << num << " ";
// 输出:1 2 5 5 6 9
// 2. 自定义降序(Lambda表达式)
//(int a, int b) 中的 a 和 b 是形参,且名字可以完全由你自己定义
sort(arr, arr + len, [](int a, int b) { return a > b;});// 返回true表示a排在b前(降序)
cout << "\n降序:";
for (int num : arr) cout << num << " "; // 输出:9 6 5 5 2 1
return 0;
}
sort函数中的 Lambda 表达式参数为什么是int a, int b而非arr[i], arr[i+1]?核心原因是:这是std::sort算法的统一设计规则 ——Lambda 表达式在这里是「元素比较器」,接收的是数组 / 容器中「两个待比较的元素本身」,而非数组下标或数组元素的索引引用
场景 2:排序字符指针数组(字符串排序)
#include <iostream>
#include <algorithm> // sort 头文件
#include <string> // string 头文件
using namespace std;
int main() {
// 1. 定义待排序的字符串
string str = "bacfed";
cout << "原始字符串:" << str << endl; // 输出:bacfed
// 2. 升序排序(默认按 ASCII 码:a < b < c < ...)
sort(str.begin(), str.end()); // 排序范围:str的第一个字符到最后一个字符
cout << "升序排序后:" << str << endl; // 输出:abcdef
// 3. 降序排序(自定义比较规则)
sort(str.begin(), str.end(), [](char a, char b) {
return a > b; // 返回true表示a排在b前面(降序)
});
cout << "降序排序后:" << str << endl; // 输出:fedcba
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
char* name[] = {"Zhang", "Gao", "Tang", "Wang", "Li"};
int len = sizeof(name) / sizeof(name[0]);
//求字符数组的长度
// 按字符串ASCII升序(第一个字母小的在前,相同比第二个)
sort(name, name + len, [](const char* a, const char* b) {
return strcmp(a, b) < 0; // strcmp<0 表示a<b
});
cout << "字符串升序:\n";
for (auto s : name) cout << s << endl;
// 输出:Gao → Li → Tang → Wang → Zhang
return 0;
}
关键:为什么加 const?const char* a 中的 const 表示 “不能通过 a 修改指向的字符串内容”—— 因为字符串字面值(如 "Gao")存储在只读内存,修改会崩溃,const 是提前规避错误的 “安全锁”。
场景 3:排序 STL 容器(如 vector)
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<string> vec = {"apple", "banana", "cherry", "date"};
// 默认升序(字符串ASCII)
sort(vec.begin(), vec.end());
cout << "vector升序:\n";
for (auto s : vec) cout << s << " ";
// apple banana cherry date// 自定义:按字符串长度降序
sort(vec.begin(), vec.end(),
[](const string& a, const string& b){return a.length() > b.length();
// 长度长的在前
});
cout << "\n按长度降序:\n";
for (auto s : vec) cout << s << " "; // banana cherry apple date
return 0;}
&(引用):避免拷贝,提升效率
如果写 string a:sort 传参时会把 vec 里的 string 对象拷贝一份给 a/b;
string 是复杂对象(内部存字符数组、长度等),频繁拷贝会浪费内存、拖慢速度;
如果写 string& a(引用):a/b 相当于 vec 里原对象的 “别名”,直接操作原对象,没有拷贝,效率拉满。
const:禁止修改,保证安全
我们的逻辑只是 “比较长度”,完全不需要修改 a/b 的内容;
加 const 后,Lambda 内部如果误写 a = "pear" 这类修改语句,编译器会直接报错,避免意外修改原容器的内容
场景 4:排序自定义类型(如结构体)
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// 自定义结构体:学生(姓名+分数)
struct Student {
string name;
int score;};
int main() {
vector<Student> stu = {{"Zhang", 85},{"Li", 95},{"Wang", 85},{"Gao", 90}};
// 自定义规则:分数降序,分数相同按姓名升序
sort(stu.begin(), stu.end(), [](const Student& a, const Student& b)
{ if (a.score != b.score)
{return a.score > b.score; // 分数降序
}
else {return a.name < b.name; // 姓名升序
}
});
cout << "按分数排序:\n";for (auto s : stu) {
cout << s.name << " " << s.score << endl;}// 输出:Li(95) → Gao(90) → Wang(85) → Zhang(85)return 0;}
struct Student {
int id; // 学号
int score; // 成绩
};
// Lambda写法(考试推荐)
sort(students, students + n, [](const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score; // 成绩降序(第一优先级)
}
return a.id < b.id; // 学号升序(第二优先级)
});
find()函数
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
// 步骤1:定义容器并初始化(无序、有序均可)
std::vectorstd::string vec = {"apple", "banana", "orange", "banana", "grape"};
std::string target = "banana"; // 目标查找值
// 步骤2:调用std::find(),指定区间[vec.begin(), vec.end())和目标值
// auto 自动推导迭代器类型(std::vector<std::string>::iterator)
auto it = std::find(vec.begin(), vec.end(), target);
// 步骤3:判断迭代器是否有效(是否找到元素)
if (it != vec.end()) {
// 步骤4:处理结果——获取元素值、索引等
std::cout << "找到目标元素:" << *it << std::endl; // 解引用迭代器,获取元素值
std::cout << "目标元素的索引:" << it - vec.begin() << std::endl; // 迭代器转索引(仅支持随机访问迭代器)
} else {
// 迭代器等于vec.end(),表示未找到
std::cout << "未找到目标元素:" << target << std::endl;
}
return 0;
}
max()函数
#include <algorithm> // 必须包含的头文件
// 格式:max(值1, 值2)
类型 结果 = max(值1, 值2);
#include <algorithm>
// 格式:max({值1, 值2, 值3, ...})
类型 结果 =max({值1, 值2, 值3, ...});