你们好,最近小元发现有许多的小伙伴们关于c++中sort函数用法,sort函数用法这个问题都较为感兴趣的,今日小活为我们梳理了下,一同往下看看吧。
1、:
2、因为sort()函数是c++STL库中自带的函数,所以要引证该函数之前要声明正确的头文件。
3、运用全能头文件:
4、:
5、参数缺省:
6、void sort (first, last); ---其间first是未排序数组的第一个元素,last是未排序数组的最终一个元素。默许以递加的次序排序。
7、一般方式
8、void sort ( first, last, comp)-----多了一个比较函数,能够依照自己的主意进行排序。
9、:
10、#include<bits/stdc++.h>
11、using namespace std;
12、int main()
13、{
14、 int a[]={4,2 ,3 ,1,2};
15、 int n=sizeof(a)/sizeof(int);
16、 //print the unsorted array
17、 cout<<"unsorted array: "<<endl;
18、 for(int i=0;i<n;i++)
19、 cout<<a[i]<<" ";
20、 cout<<endl;
21、 //sorting
22、 sort(a,a+4);
23、 //print the sorted array
24、 cout<<"sorted array: "<<endl;
25、 for(int i=0;i<n;i++)
26、 cout<<a[i]<<" ";
27、 cout<<endl;
28、}
29、排序成果:
30、unsorted array:
31、4 2 3 1 2
32、sorted array:
33、1 2 3 4 5
34、不缺省,递减排序:
35、加比较函数greater<int>()
36、代码:
37、#include<bits/stdc++.h>
38、using namespace std;
39、int main()
40、{
41、 int a[]={4,2 ,3 ,1,2};
42、 int n=sizeof(a)/sizeof(int);
43、 //print the unsorted array
44、 cout<<"unsorted array: "<<endl;
45、 for(int i=0;i<n;i++)
46、 cout<<a[i]<<" ";
47、 cout<<endl;
48、 //sorting
49、 sort(a,a+4,greater<int>());
50、 //print the sorted array
51、 cout<<"sorted array: "<<endl;
52、 for(int i=0;i<n;i++)
53、 cout<<a[i]<<" ";
54、 cout<<endl;
55、}
56、。
57、#include<bits/stdc++.h>
58、using namespace std;
59、int compare(int a,int b)
60、{
61、 return a>b;
62、}
63、int main()
64、{
65、 int a[]={4,2 ,3 ,1,2};
66、 int n=sizeof(a)/sizeof(int);
67、 //print the unsorted array
68、 cout<<"unsorted array: "<<endl;
69、 for(int i=0;i<n;i++)
70、 cout<<a[i]<<" ";
71、 cout<<endl;
72、 //sorting
73、 sort(a,a+4,compare);
74、 //print the sorted array
75、 cout<<"sorted array: "<<endl;
76、 for(int i=0;i<n;i++)
77、 cout<<a[i]<<" ";
78、 cout<<endl;
79、}
以上便是sort函数用法这篇文章的一些介绍,期望对我们有所协助。
发表评论