首页 > 编程知识 正文

单链表按位数排序c,sort函数的用法

时间:2023-05-03 18:39:38 阅读:114306 作者:2765

一.sort函数

I.sort函数包含在头文件为#include的c标准库中,可以通过调用标准库的排序方法对数据进行排序。 但是,sort函数是如何实现的完全不需要考虑。

II.sort函数的模板有三个参数。

语音软件(randomaccessiteratorfirst,RandomAccessIterator last,Compare comp );

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

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

)第三个参数comp是排序的方法。 升序或降序都可以。 如果没有写入第三个参数,则默认排序方法从小到大。

III .实例

1 # include iostream2# include algorithm3usingnamespacestd; 4 main ()5)5 { 6 //sort函数的第三个参数是默认的从小到大的7inta ()、12、34、77、90、11、2、4、5、55 ); 8sort(a,a 10 ); 9for(intI=0; i10; I ) 10 couta[i] '; 11 )运行结果:

1 # include iostream2# include algorithm3usingnamespacestd; 4BOOLCMP(inta,int b ); 5 main () { 6 //sort函数的第三个参数自己定义,从大到小7inta ) )、12、34、77、90、11、2、4、5、55 )。 8sort(a,a 10,cmp ); 9for(intI=0; i10; I ) 10 couta[i] '; 11 ) 12//自定义函数13boolCMP(inta,int b ) {14 return ab; 15 )运行结果:

1 # include iostream2# include algorithm3# include ' cstring '4usingnamespacestd; 5 typedefstructstudent {6charname [ 20 ]; 7英特曼; 8 int english; 9 }Student; 10boolCMP(studenta,Student b ); 11 main () {12 //先按math从小到大,按math相等,按english从小到大的顺序13studenta(4),{'apple (,67,89 ),{'limei,90,56 14sort(a,a 3,cmp ); 15for(intI=0; i3; I ) 16 couta [ I ].name ' ' a [ I ].math ' ' a [ I ].English endl; 17 ) 18boolCMP(studenta,Student b ) ) 19if ) a.mathb.math ) 20 return a.math b.math; 按math从小到大的顺序排列21elseif(a.math==b.math ) 22 return a.englishb.english; //math相等,在endlish中按照从大到小的顺序执行23 24 }结果

IV .容器情况下,容器内的数据类型可以多样化

1 )如果元素本身包含int、double等基本类型,可以直接比较greater (递减、less )增量)省略

1 # include iostream2# include algorithm3# include ' vector '4usingnamespacestd; 5 typedefstructstudent {6charname [ 20 ]; 7英特曼; 8 int english; 9 }Student; 10boolCMP(studenta,Student b ); 11 main () 12ints )=6534、56、11、23、45 ); 13vectorintarr(s,s 5; 14sort(arr.Begin (,arr.end )、greaterint ); 15for(intI=0; iarr.size (; I ) 16 coutarr[i] '; 17 )运行结果:

2 )元素本身为class或struct,类内部需要重载运算符,实现元素的比较

注意事项: Booloperator(constclassnameRHS ) const; 必须添加常数,以便临时变量可以赋值,以了解参数是如何引用的; 重载操作器是常量成员函数,可以用常量变量调用;

1 # include iostream2# include algorithm3# include ' vector '4usingnamespacestd; 5 typedefstructstudent {6charname [ 20 ]; 7英特曼; 8//math下9 inlinebooloperator (const studentx ) const ) 10returnmathx.math; 11 ) 12 ) student; 13 main () 14studenta(4) {'apple ',67},{'limei ',90},{'apple ',90}; 15sort(a,a 3); 16for(intI=0; i3; I ) 17c outa [ I ].name ' ' a [ I ].math ' ' endl; 18 )运行结果:

也可以用以下格式定义重载:

1结构CMP {2bool operator ((info a1,Info a2 ) const )3returnA1.valA2.val; 4 }5 };

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。