STL排序方法( 转)

//适合读者:STL初学者

//#include<algorithm>
//快速排序sort()  (平均O(NlogN) 
//稳定排序stable_sort() (最好O(NlogN),最坏O(N(logN)^2) 用法与sort()相同
//堆排序s ort_heap()  (O(NlogN)) 用法同sort(),要先make_heap()或push_heap()
/************目录************
用法一:内置类型的由小到大排序:使用默认比较函数(less<T>())
 sort(a,a+len); //a:数组名,len:数组长度=sizeof(arrray)/sizeof(*array)

用法二:内置类型的由大到小排序:使用内置比较函数(greater<T>())
 sort(a,a+len,greater<int>()); //greater<Type>():#include<functional>

用法三:自定义类型对象数组的由大到小排序:使用游离比较函数(myGreater(Type&, Type&)
 bool myGreater(const Type& a, const Type& b){ return a>b;}
 sort(a,a+len,myGreater); //自定义类型对象数组的由大到小排序
 堆排序版本:
 bool myGreater(const Type& a, const Type& b){ return a>b;}
 make_heap(a,a+len,myGreater);
 sort_heap(a,a+len,myGreater); //参数必须完全一样!
 
用法四:指针数组的由大到小排序:使用游离比较函数(myGreater(const Type*, const Type*)
 bool myGreater(const int* a, const int* b){ return *a>*b;}
 sort(p,p+len,myGreater); //指针数组的由大到小排序,适用于索引排序
/**/
//***********例子************
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
//用法一:内置类型的由小到大排序:使用默认比较函数(less<T>())
/*void main()
{
 int a[]={3, 1,4,2,5};
 int len=sizeof(a)/sizeof(int);
 sort(a,a+len); //默认:内置类型的由小到大排序
 for (int i=0; i<len; i++)
  cout<<a[i]<<'/t';
 cout<<endl;
}
/**/
//用法二:内置类型的由大到小排序:使用内置比较函数(greater<T>())
/*void main()
{
 int a[]={3, 1,4,2,5};
 int len=sizeof(a)/sizeof(int);
 sort(a,a+len,greater<int>()); //内置类型的由大到小排序
 for (int i=0; i<len; i++)
  cout<<a[i]<<'/t';
 cout<<endl;
}
/**/
//用法三:自定义类型对象数组的由大到小排序:使用游离比较函数(myGreater(Type&, Type&)
/*bool myGreater(int& a, int& b){ return a>b;}
void main()
{
 int a[]={3, 1,4,2,5};
 int len=sizeof(a)/sizeof(int);
 sort(a,a+len,myGreater); //自定义类型的由大到小排序
 for (int i=0; i<len; i++)
  cout<<a[i]<<'/t';
 cout<<endl;
}
/**/
//sort_heap版本:
bool myGreater(int& a, int& b){ return a>b;}
void main()
{
 int a[]={3, 1,4,2,5};
 int len=sizeof(a)/sizeof(int);
 make_heap(a,a+len,myGreater);
 sort_heap(a,a+len,myGreater); //自定义类型的由大到小排序
 for (int i=0; i<len; i++)
  cout<<a[i]<<'/t';
 cout<<endl;
}
/**/

//用法四:自定义类型指针数组的由大到小排序:使用游离比较函数(myGreater(Type&, Type&)
/*bool myGreater(int* a, int* b){ return *a>*b;}
void main()
{
 int a[]={3, 1,4,2,5};
 int* p[5];
 for(int i=0;i<5;i++) p[i]=&a[i];
 int len=sizeof(a)/sizeof(int);
 sort(p,p+len,myGreater); //自定义类型的由大到小排序
 for (i=0; i<len; i++)
  cout<<a[i]<<'/t';
 cout<<endl;
 for (i=0; i<len; i++)
  cout<<*p[i]<<'/t';
 cout<<endl;
}
/**/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值