C++中sort函数的用法汇总
最近写题的时候总会在贪心算法里面用到C++函数sort函数排序的方法,故在此总结一下 sort函数本身是对一段连续的存贮单元的数据进行排序的函数,其排序的元素可以是数值,亦可以是一组数据(结构体),其算法比正常的冒泡排序法,选择排序法,希尔排序要简便,故对于算法的简化大有帮助 1.将一段数据按升序排列 # include <cstdio> # include <algorithm> //sort函数储存在C++的algorithm函数库中 using namespace std ; int main ( ) { int a [ 10 ] = { 2 , 3 , 4 , 1 , 2 , 67 , 23 , 24 , 156 , 678 } ; int i ; sort ( a , a + 10 ) ; //对一段连续的存储空间进行排序 for ( i = 0 ; i < 10 ; i ++ ) printf ( "%d " , a [ i ] ) ; printf ( "\n" ) ; return 0 ; } 2.将一段数据按照降序排列 # include <cstdio> # include <algorithm> //sort函数储存在C++的algorithm函数库中 using namespace std ; bool compare ( int a , int b ) {