Add stl sorting
All checks were successful
ci/woodpecker/push/test Pipeline was successful

This commit is contained in:
Sainnhe Park 2023-02-28 17:28:26 +08:00
parent 5c03c9e3f2
commit af6afd2d77
2 changed files with 45 additions and 0 deletions

View File

@ -63,6 +63,7 @@
# STL # STL
- [总结](./stl.md) - [总结](./stl.md)
- [排序](./stl_sorting.md)
# 技巧 # 技巧

44
notes/src/stl_sorting.md Normal file
View File

@ -0,0 +1,44 @@
# 排序
升序排序:
```cpp
void ascending(std::vector<int> &x) {
// #include <algorithm>
std::sort(x.begin(), x.end());
}
```
降序排序:
```cpp
void descending(std::vector<int> &x) {
// #include <algorithm>
// #include <functional>
std::sort(x.begin(), x.end(), std::greater<int>());
}
```
自定义比较函数:
```cpp
struct Data {
std::string name;
int age;
};
/**
* @brief 自定义比较函数
*
* @param a 第一个待比较的值
* @param b 第二个待比较的值
* @return 返回为 true 时代表 a 应该放在 b 前面
*/
bool compareFunc(Data &a, Data &b) {
return a.name.length() > b.name.length();
}
void customCompare(std::vector<Data> &x) {
std::sort(x.begin(), x.end(), compareFunc);
}
```