From af6afd2d77f146767ab8079406baede11791ecf2 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 28 Feb 2023 17:28:26 +0800 Subject: [PATCH] Add stl sorting --- notes/src/SUMMARY.md | 1 + notes/src/stl_sorting.md | 44 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 notes/src/stl_sorting.md diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index 9667a76..7de8784 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -63,6 +63,7 @@ # STL - [总结](./stl.md) +- [排序](./stl_sorting.md) # 技巧 diff --git a/notes/src/stl_sorting.md b/notes/src/stl_sorting.md new file mode 100644 index 0000000..5f220a0 --- /dev/null +++ b/notes/src/stl_sorting.md @@ -0,0 +1,44 @@ +# 排序 + +升序排序: + +```cpp +void ascending(std::vector &x) { + // #include + std::sort(x.begin(), x.end()); +} +``` + +降序排序: + +```cpp +void descending(std::vector &x) { + // #include + // #include + std::sort(x.begin(), x.end(), std::greater()); +} +``` + +自定义比较函数: + +```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 &x) { + std::sort(x.begin(), x.end(), compareFunc); +} +```