sort

来源:互联网 发布:linux 加载u盘 编辑:程序博客网 时间:2024/06/11 11:20

简要介绍下标准库里的排序方法——STL里的sort()函数:


使用sort()函数,需要头文件 <algorithm>,且默认升序排序,用户可自定义cmp实现降序排序。

演示如下:

#include <iostream>#include <cstdio>#include <algorithm>using namespace std;boolcompare(const int& a, const int& b) {return a > b;}intmain() {//使用硬编码方式生成小数组数据inta[10] = { 1,3,5,7,9,2,4,6,8,10 };//输出原数组数据for (int i = 0; i < 10; ++i)printf("\ta[%d] = %d\n", i, a[i]);//STL排序,默认为升序,"<=",并输出排序后数组sort(a, a + 10);putchar('\n');for (int i = 0; i < 10; ++i)printf("\ta[%d] = %d\n", i, a[i]);//STL排序,自定义为降序,">=",并输出排序后数组sort(a, a + 10,compare);putchar('\n');for (int i = 0; i < 10; ++i)printf("\ta[%d] = %d\n", i, a[i]);return 0;}


运送结果如下:





简化一下代码,如下:

#include <iostream>#include <algorithm>using namespace std;boolcmp(const int& a, const int& b) {return a > b;}voidPrint_Array(int* a, int n) {for (int i = 0; i < n; ++i)cout << '\t' << a[i] << " ";cout << endl;}intmain() {//使用硬编码方式生成小数组数据,并输出原数组数据const int SIZE = 10;inta[SIZE] = { 1,3,5,7,9,2,4,6,8,10 };Print_Array(a, SIZE);//STL排序,默认为升序,"<=",并输出排序后数组sort(a, a + SIZE);Print_Array(a, SIZE);//STL排序,自定义为降序,">=",并输出排序后数组sort(a, a + SIZE,cmp);Print_Array(a, SIZE);return 0;}




当然了,当不再限定 测试用例的数据类型时,应该使用 泛型  编程,而 标准库STL里的 sort()已经是通过模板实现了的,我们只需要修改输出函数。

基本数据类型可以直接输出,构造数据类型要先自己重载输出运算符。


#include <iostream>#include <algorithm>using namespace std;template<typename T>void Print_Array(T a[], int n) {for (int i = 0; i < n; ++i)cout << '\t' << a[i] << " ";cout << endl;}intmain() {//使用硬编码方式生成小数组数据const int SIZE = 10;inta[SIZE] = { 1,3,5,7,9,2,4,6,8,10 };double d[SIZE] = { 1.2,1.5,1.3,1.9,1.4,6.4,6.9,9.6,4.6,3 };//STL排序,默认为升序,"<=",并输出排序前后数组Print_Array(a, SIZE);sort(a, a + SIZE);Print_Array(a, SIZE);Print_Array(d, SIZE);sort(d, d + SIZE);Print_Array(d, SIZE);return 0;}


运行结果:





31/07/2017添加内容:

关于cmp函数的通用写法(泛型),如是

template<typename T>boolcmp(T& a, T& b) {returna > b;}

在使用的时候注意类型匹配就好了,可以是编译器自带的基本数据类型,也可以是用户自定义的构造数据类型,均可。

比如对int型数组a进行降序排序,则可写成 

sort (a,a+n,cmp<int> );

其他同理。


另外说明,模板函数也可以直接在模板中使用,比如这个cmp也可以直接在模板函数中用到,我会在后边的文章里提到。

// 假设形参为 (T&a,int n)sort ( a,a+n,cmp<T> );

这是可以通过的。



喂丸待续……