notes/OJ notes/pages/cpp_std_sort.md

67 lines
1.3 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# Sort
#### 2022-06-11
2022-09-03 15:41:36 +08:00
---
2022-06-14 23:33:35 +08:00
##### Algorithms:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#algorithm #sort
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Difficulty:
2022-09-03 15:41:36 +08:00
2022-09-06 20:22:48 +08:00
#CS_analysis #difficulty_easy
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Related problems:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- [cpp reference](https://en.cppreference.com/w/cpp/algorithm/sort)
2022-09-03 15:41:36 +08:00
---
2022-06-14 23:33:35 +08:00
### What is Sort?
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
Sorts the elements in the range `[first, last)` in non-descending order. The order of equal elements is not guaranteed to be preserved.
The default Compare function is less: `<`
### Example
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
```cpp
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
#include <string_view>
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
int main()
{
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
auto print = [&s](std::string_view const rem) {
for (auto a : s) {
std::cout << a << ' ';
}
std::cout << ": " << rem << '\n';
};
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
std::sort(s.begin(), s.end());
print("sorted with the default operator<");
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
std::sort(s.begin(), s.end(), std::greater<int>());
print("sorted with the standard library compare function object");
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
struct {
bool operator()(int a, int b) const { return a < b; }
} customLess;
std::sort(s.begin(), s.end(), customLess);
print("sorted with a custom function object");
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
std::sort(s.begin(), s.end(), [](int a, int b) {
return a > b;
});
print("sorted with a lambda expression");
}
2022-09-03 15:41:36 +08:00
```