用sort函数对数组,vector,string,结构体排序——C++新手上机疑难点总结③

用sort函数对数组,vector,string,结构体排序——C++新手上机疑难点总结③

对新手来说,短时间内写出快速高效的排序函数是比较困难的。好在C++内部提供了基于快速排序的sort函数。
那么该如何使用sort函数?

1. sort函数简介:

要使用sort函数,首先需要调用<algorithm>库函数。
#include <algorithm>
sort函数有三个参数:
sort(start, end, compare);

	start为需要排序区域的起点;
	end为需要排序区域的终点;
	compare为排序方式,可以不指定,此时默认为升序排列。

2. 使用sort对数组排序:

对数组排序时,start和end分别为数组名和数组名+数组长度:
#include <iostream>
#include <algorithm>

using namespace std;

bool compare(int x, int y){
    return x > y;
}

int main()
{
    int a[5] = {2, 1, 4, 3, 0};
    sort(a, a+5);                 //不指定排序方式,默认升序。

    for(int i=0;i<5;i++){
        cout << a[i] << " ";
    }
    cout << endl;

    sort(a, a+5, compare);        //指定排序方式为自定义的conpare方式,即降序排列。
    for(int i=0;i<5;i++){
        cout << a[i] << " ";
    }
    cout << endl;

    return 0;
}
0 1 2 3 4
4 3 2 1 0

Process returned 0 (0x0)   execution time : 0.264 s
Press any key to continue.

3. 使用sort对vector排序:

对vector排序时,start为 "vector名".start(), end为 "vector名".end()。
//假设a为vector<int>类型
sort(a.begin(), a.end());

4. 使用sort对string排序:

与对vector排序的方法一致。默认按字典序排序。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool compare(int x, int y){
    return x > y;
}

int main()
{

    string a = "qfrewbwrtbrdfad";
    sort(a.begin(), a.end());
    cout << a << endl;

    return 0;
}
abbddeffqrrrtww

Process returned 0 (0x0)   execution time : 0.108 s
Press any key to continue.

5. 使用sort对结构体排序:

因为结构体没有默认的大小比较方式,所以必须指定compare函数。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct dot{
    int x;
    int y;
};

bool compare(dot a, dot b){
    return a.x < b.x;
}

int main()
{

    dot d[3];
    d[0].x = 1;
    d[0].y = 2;
    d[1].x = 4;
    d[1].y = 8;
    d[2].x = 3;
    d[2].y = 1000;

    sort(d, d+3, compare);

    for(int i=0;i<3;i++){
        cout << d[i].x << " " << d[i].y << endl;
    }

    return 0;
}
1 2
3 1000
4 8

Process returned 0 (0x0)   execution time : 0.276 s
Press any key to continue.
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值