[C++]std::sort()函数使用总结

函数声明#

 

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';
}

 

作者:lizhenghao126

出处:https://www.cnblogs.com/lizhenghao126/p/11053598.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   李正浩  阅读(37178)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu