函數聲明
template< class RandomIt, class Compare >
constexpr void sort( RandomIt first, RandomIt last, Compare comp );
以一定排序規則排序指定范圍內的元素,但是算法不具有穩定性,如果元素的值是相同的話不保證它們的相對順序保持不變。
參數說明
first , last - 要排序的元素范圍。
comp - 比較的函數,這里要滿足compare的要求,如下:
總結下來一句話:就是在compare(int a ,int b)中,如果你想要從小到大排列,那么你需要的是 return a<b;(這里很簡單,如果記不住的話,先隨便按照一個方向寫,最后發現反了的話改下大小於符號就行)
時間復雜度
平均 O(N·log(N)) 次比較,其中 N = std::distance(first, last) 。
我們需要注意的是sort()采用的是優化版本的快速排序,在最后階段采用直接插入排序。因此時間復雜度為O(N·log(N))
舉例說明
#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};
// 用默認的 operator< 排序
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';
// 用 lambda 表達式排序
std::sort(s.begin(), s.end(), [](int a, int b) {
return b < a;
});
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
}