Posts 「算法刷题」c++中sort函数的使用方法
Post
Cancel

「算法刷题」c++中sort函数的使用方法

参考链接: C++中sort函数使用方法 - 俊宝贝 - 博客园 (cnblogs.com)

1.sort函数包含在头文件为#include的c++标准库中,调用标准库里的排序方法可以实现对数据的排序,但是sort函数是如何实现的,我们不用考虑!

2.sort函数的模板有三个参数:

1
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

(1)第一个参数first:是要排序的数组的起始地址。

(2)第二个参数last:是结束的地址(最后一个数据的后一个数据的地址)

(3)第三个参数comp是排序的方法:可以是从升序也可是降序。如果第三个参数不写,则默认的排序方法是从小到大排序。

3 实例

1
2
3
4
5
6
7
8
9
10
11
12
 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 main()
 5 {
 6   //sort函数第三个参数采用默认从小到大
 7   int a[]={45,12,34,77,90,11,2,4,5,55};
 8   sort(a,a+10);
 9   for(int i=0;i<10;i++)
10   cout<<a[i]<<" ";     
11 } 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 bool cmp(int a,int b);
 5 main(){
 6   //sort函数第三个参数自己定义,实现从大到小 
 7   int a[]={45,12,34,77,90,11,2,4,5,55};
 8   sort(a,a+10,cmp);
 9   for(int i=0;i<10;i++)
10     cout<<a[i]<<" ";     
11 }
12 //自定义函数
13 bool cmp(int a,int b){
14   return a>b;
15 }
This post is licensed under CC BY 4.0 by the author.