欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sort函数的第三个参数cmp

程序员文章站 2024-02-23 14:06:34
...

sort 函数的第三个参数 cmp

案例1:

#include<iostream>  
#include<algorithm>		//因为用了sort()函数  
#include<functional>	//因为用了greater<int>()  
using namespace std;  
  
void main()  
{  
    int a[]={3,1,4,2,5};  
    int i;  
    int len=sizeof(a)/sizeof(int);//这里切记要除以sizeof(int)!  
  
    sort(a ,a + len, greater<int>());//内置类型的由大到小排序  
    for(i=0;i<len;i++)  
        cout<<a[i]<<" ";  
    cout<<"\n";  

    sort(a, a + len, less<int>());        //内置类型的由小到大排序  
    for(i=0;i<len;i++)  
        cout<<a[i]<<" ";  
	system("pause");
} 

案例2:

#include <iostream>
#include<vector>
#include <algorithm> 
using namespace std;  
  
//下面的比较函数的返回值为0或者1   
bool cmp1(int m, int n)  
{  
     return m>n;	//降序排列
}  

bool cmp2(int m, int n)  
{  
     return m<n;	//升序排列
}
int main()  
{  
    int a[10] = {8, 6, 9, 4, 21, 1, 1, 3, 78, -5};  
    sort(a, a+10, cmp1);  

    for (int i=0; i<10; ++i)  
        cout<<a[i]<<" ";  
    cout<<endl<<endl;  
	sort(a, a+10, cmp2);  

    for (int i=0; i<10; ++i)  
        cout<<a[i]<<" ";  
    cout<<endl<<endl;

	stable_sort(a,a+10,cmp1);
	for (int i=0; i<10; ++i)  
        cout<<a[i]<<" ";  
    cout<<endl<<endl;

	stable_sort(a,a+10,cmp2);
	for (int i=0; i<10; ++i)  
        cout<<a[i]<<" ";  
    cout<<endl<<endl;

    system("pause"); 
	return 0;
}