首先感谢Mr.Wang的援助计划!
sort函数包含在头文件#includealgorithm中的c标准库中,调用标准库的排序方法可以对数据进行排序,但目前不需要考虑sort函数是如何实现的。
sort函数格式:
语音软件(randomaccessiteratorfirst,RandomAccessIterator last,Compare comp ); (1)第一个参数first是要排序的数组的起始地址。
)第二个参数last )是终止的地址(最后一个数据的后一个数据的地址)
)第三个参数comp是排序的方法。 升序或降序都可以。 如果没有写入第三个参数,则默认排序方法从小到大。
//最基本的使用方法# include iostream # includealgorithmusingnamespacestd; int main () {//sort函数的第三个参数是从默认值较小到较大的inta ()、18、84、1、19、11、21、4、45、55 );//两个参数分别表示起始地址、结束地址。 请注意,结束地址是要排序的最后一个地址的下一个地址。 a 9表示数组a中最后一个元素的//地址,然后下一个地址是a 10sort(a,a10 )。 for(intI=0; i10; I ) couta[i] '; 返回0; }
执行结果:
1使用第1 4 11 18 19 21 43 45 55 84 //个参数创建函数# include iostream # includealgorithmusingnamespacestd; BOOLCMP(inta,int b ) { return ab; (}int main ) ) ({//sort函数的第三个参数是从默认值小到大的inta )、18、84、1、19、11、21、4、45、55 ); sort(a,a 10,cmp ); for(intI=0; i10; I ) couta[i] '; 返回0; }
执行结果:
1 4 11 18 19 21 43 45 55 84
数组中的元素也可以是结构。
# include iostream # includealgorithmusingnamespacestd; 结构稳定{ int math; int chinese; (; bool CMP (结构稳定,结构稳定b ) if ) a.math!=b.math(returna.mathb.math; }else{ return a.chineseb.chinese; }}int main () ({//sort函数的第三个参数是默认的从小到大的struct student a[5]; a [0]={ 89,73 }; a [1]={ 74,85 }; a [2]={ 90,88 }; a [3]={ 68,90 }; a [4]={ 89,68 }; sort(a,a 5,cmp ); for(intI=0; i5; I ) couta [ I ].math ' ' a [ I ].Chinese endl; 返回0; }执行结果:
90 8889 7389 6874 8568 90
通常,如果需要在比赛中对数组进行排序,请使用sort函数进行排序。