posts - 267,  comments - 1127,  trackbacks - 0

//适合读者: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;
}
/**/

---
本文章使用开源内容管理kicoy发布

posted on 2006-06-14 13:51 踏雪赤兔 阅读(548) 评论(1)  编辑 收藏 引用 所属分类: 零件仓库

FeedBack:
# re: STL排序方法(原创)
2008-08-23 10:11 | vangogh
吧错,吧错..  回复  更多评论
  


标题  
姓名  
主页
验证码 *
内容(提交失败后,可以通过“恢复上次提交”恢复刚刚提交的内容)
 
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
[使用Ctrl+Enter键可以直接提交]
 
相关链接:




百度空间| 见闻日记| 编程感悟
我的twitter


LOGO

自我介绍:我系鸣仔,喜爱研究算法,曾是中大ACM队员。 发QQ消息


添加到收藏夹 Locations of visitors to this page

常用链接

随笔分类(290)

随笔档案(267)

文章分类(38)

相册

收藏夹(54)

与博主互动

博客手拉手

搜索

  •  

积分与排名

  • 积分 - 130538
  • 排名 - 5

最新评论

阅读排行榜

评论排行榜

60天内阅读排行