std::sort
: cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (1) | ||
template< class RandomIt > void sort( RandomIt first, RandomIt last ); |
(C++20) | |
template< class RandomIt > constexpr void sort( RandomIt first, RandomIt last ); |
(C++20) | |
template< class ExecutionPolicy, class RandomIt > void sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last ); |
(2) | (C++17) |
| (3) | ||
template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp ); |
(C++20) | |
template< class RandomIt, class Compare > constexpr void sort( RandomIt first, RandomIt last, Compare comp ); |
(C++20) | |
template< class ExecutionPolicy, class RandomIt, class Compare > void sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ); |
(4) | (C++17) |
[first, last)
1)
operator< 3)
comp 2,4) (1,3)
policy std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> true | first, last | - | |
| policy | - | |
| comp | - | 2 () true (Compare )
|
-RandomIt ValueSwappable LegacyRandomAccessIterator
| ||
-RandomIt MoveAssignable MoveConstructible
| ||
-Compare Compare
| ||
()
|
O(N·log(N)) |
(C++11) |
|
O(N·log(N)) |
(C++11) |
ExecutionPolicy
-
ExecutionPolicystd::terminateExecutionPolicy - std::bad_alloc
LWG713 sort() O(N2
)
libc++ LLVM 14
Run this code
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
int main()
{
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
// <
std::sort(s.begin(), s.end());
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
//
std::sort(s.begin(), s.end(), std::greater<int>());
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
//
struct {
bool operator()(int a, int b) const
{
return a < b;
}
} customLess;
std::sort(s.begin(), s.end(), customLess);
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
//
std::sort(s.begin(), s.end(), [](int a, int b) {
return a > b;
});
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
}
:
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
| N () | |
| () |