C++ sort排序函数详解

在很多应用中,排序都是至关重要的。基于C语言的经典排序算法有很多(冒泡排序、快速排序、插入排序、选择排序等)

一、sort函数描述

在基于C++的实际应用中(支持 < 运算符的语言)已经为我们提供了一个已经实现好的排序工具——sort()

当我们要使用它时,需要先引入一个算法库——<algorithm>

sort函数可以排序任何类型的元素,包括我们自己定义的结构体

它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)

二、sort函数用法

Sort函数有三个参数:(第三个参数可不写)
(1)第一个是要排序的数组的起始地址
(2)第二个是结束的地址(最后一位要排序的地址)
(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序

有两种方式可以进行降序

a:使用greater<int>() // 其中<int>表示待排序的数组中的元素类型为int

b:自定义降序函数,作为sort函数的第三个参数

三、sort函数实现

两个参数实现

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    vector<string> sArray = { "13","12A","A93","936","1234","23" };
    sort(sArray.begin(), sArray.end());
    for (auto s : sArray)
    {
	cout << s << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

三个参数实现

库函数greater<string>()

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    vector<string> sArray = { "13","12A","A93","936","1234","23" };
    sort(sArray.begin(), sArray.end(), greater<string>()); // 使用greater<string>()
    for (auto s : sArray)
    {
	cout << s << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

自定义函数compare

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool compare(string s1, string s2)
{
    return s1.size() > s2.size();
}

int main()
{
    vector<string> sArray = { "13","12A","A93","936","1234","23" };
    sort(sArray.begin(), sArray.end(), compare); // 自定义函数compare
    for (auto s : sArray)
    {
	cout << s << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

发布了12 篇原创文章 · 获赞 27 · 访问量 749

猜你喜欢

转载自blog.csdn.net/Gary_ghw/article/details/103918612
今日推荐