当前位置:   article > 正文

sort 排序使用介绍_sort排序怎么用

sort排序怎么用

定义

sort()排序是C++中自带的排序算法函数。排序过程相对于堆排序、希尔排序等其他排序算法较简单。

sort()排序函数的调用首先需要头文件algorithm:是“算法”的意思。
sort()函数有三个参数sort(begin, end, 参数三)。begin为指向待sort()的数组的第一个元素的指针,end为指向数组的最后一个元素的下一个位置的指针,参数三为排序方式,参数三如果不写,默认从小到大进行排序。将参数三写为greater()就是从大到小进行排序。<>中也可以写double、long、float等等,看我们变量类型了。

调用方式

简单数组排序

#include <iostream>
#include<algorithm>

using namespace std;

int main()
{
    int a[6]={6,2,3,1,5,10};
    sort(a,a+6);
    for(int i=0;i<6;i++)
        cout<<a[i]<<" ";
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

输出:1 2 3 5 6 10

这里可以看到是sort(a,a+10),但是数组a一共只有9个元素,为什么是a+10而不是a+9呢?
因为sort方法实际上最后一位地址对应的数是不取的,而且vector,set,map这些容器的end()取出来的值实际上并不是最后一个值,而end的前一个才是最后一个值!
需要用prev(xxx.end()),才能取出容器中最后一个元素。

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int num[10] = { 9,5,6,0,8,7,4,3,2,1 };
	sort(num, num + 10, greater<int>());
	for (int i = 0; i < 10; i++) {
		cout << num[i] << " ";
	}
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

输出 9 8 7 6 5 4 3 2 1 0

不只可以按照从大到小或从小到大的顺序排序,也可以在外部自定义一个函数,然后将此函数作为参数传递到sort()函数中的参数三处。因此达到按照自己需要的方式进行排序的目的。

#include<iostream>
#include<algorithm>
using namespace std;
int larger(int x, int y)
{
	return x % 10 > y % 10;
}
int main()
{
	int a[10] = { 6,25,31,9,25,16,34,17,28,61 };
	sort(a, a + 10,larger);
	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << " ";
	}
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

输出:9 28 17 6 16 25 25 34 31 61

sort()函数排序算法应用范围很广,适用于多种语言,同时又适用于数组、结构体等。

对string型 按字典序排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    string str("hello world");
    sort(str.begin(),str.end());
    cout<<str;
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

输出:dehllloorw

对结构体排序

对于结构体排序其实也不难,只是需要我们自己重写cmp函数
例如要对结构体中的元素b按照升序排序。

#include<bits/stdc++.h>
using namespace std;

struct node{
    int a;
    int b;
};
bool cmp(node time1,node time2)
{
    return time1.b<time2.b;
}
int main()
{
    int n;
    cin>>n;
    node time[n+10];
    for(int i=0;i<n;i++)
        cin>>time[i].a>>time[i].b;
    sort(time,time+n,cmp);
    for(int i=0;i<n;i++)
    {
        cout<<time[i].a<<" "<<time[i].b<<endl;
    }
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/807096
推荐阅读
相关标签
  

闽ICP备14008679号