notes/CS notes/pages/cpp_std_sort.md

64 lines
1.4 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# Sort
#### 2022-06-11
___
##### Algorithms:
#algorithm #sort
##### Difficulty:
#CS_analysis #difficulty-easy
##### Related problems:
```expander
tag:#coding_problem tag:#sort -tag:#template_remove_me
```
- [[Leetcode Intersection-of-Two-Arrays-II]]
##### Links:
- [cpp reference](https://en.cppreference.com/w/cpp/algorithm/sort)
___
### What is Sort?
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
```cpp
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
#include <string_view>
int main()
{
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
auto print = [&s](std::string_view const rem) {
for (auto a : s) {
std::cout << a << ' ';
}
std::cout << ": " << rem << '\n';
};
std::sort(s.begin(), s.end());
print("sorted with the default operator<");
std::sort(s.begin(), s.end(), std::greater<int>());
print("sorted with the standard library compare function object");
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");
std::sort(s.begin(), s.end(), [](int a, int b) {
return a > b;
});
print("sorted with a lambda expression");
}
```