多语言展示
当前在线:1784今日阅读:167今日分享:16

c++ 语言中的sort函数如何使用

c++语言中STL库中的sort函数可以用来对数组进行排序。对于c++语言来说由于其自带的sort()函数更容易被编译器编译,其排序速度比基于快速排序的qsort要快上不少,且用法简单。非常推荐大家使用。下面,小编将介绍一下该函数的使用方法。
工具/原料
1

c++ 11编译器

2

code::blocks

方法/步骤
1

头文件:由于sort()函数是c++STL库中自带的函数,所以要引用该函数之前要声明正确的头文件。使用万能头文件:#include

2

函数语法:参数缺省: void sort (first, last);  ---其中first是未排序数组的第一个元素,last是未排序数组的最后一个元素。默认以递增的顺序排序。一般形式 void sort ( first, last,  comp)-----多了一个比较函数,可以按照自己的想法进行排序。

3

比较函数缺省的排序:#includeusing namespace std;int main(){   int a[]={4,2 ,3 ,1,2};   int n=sizeof(a)/sizeof(int);   //print the unsorted array   cout<<'unsorted array: '<

4

排序结果:unsorted array: 4 2 3 1 2sorted array: 1 2 3 4 5

6

不缺省,自己写比较函数。#includeusing namespace std;int compare(int a,int b){      return a>b;}int main(){   int a[]={4,2 ,3 ,1,2};   int n=sizeof(a)/sizeof(int);   //print the unsorted array   cout<<'unsorted array: '<

注意事项

如果对您有帮助就请点个赞吧

推荐信息