STL sort()
2015-12-15 10:26
381 查看
标准模版库中sort函数包含在头文件 <algorithm> 中,std::sort();
1、默认情况下是对 [first,last)区间的元素采用由小到大的方式排列(利用元素类型的<运算符来实现)
2、排序的区间可以必须是通过迭代器遍历的(数组下标也算),迭代器的类型为随机迭代器;
stl set map 使用红黑树 avl树作为底层数据结构的实现,不支持随机迭代器,所以不能使用sort来排序;
自己定义的数据结构支持这种随机迭代器时,也可以使用sort()算法来排序
3、排序是通过多次内存的copy来实现的,所以链表不能使用stl 算法sort来对其排序(next指针修改问题)(链表有自己的sort函数);
4、算法中的sort的时间复杂度:
stl <algorithm> 中的sort算法实现,采用快排的思想,平均的时间复杂度是 N*log2(N);
算法中还提供了其他的集中排序函数 sort_heap() stable_sort()(长度相同的维持原序), 时间复杂度都在 N*log2(N)
5、可以自定义比较函数(谓词),也可以调用stl内提供的比较函数,less<T>() 、greater<T>()
sort() 函数实例:
default (1) template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); custom (2) template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);说明:
1、默认情况下是对 [first,last)区间的元素采用由小到大的方式排列(利用元素类型的<运算符来实现)
2、排序的区间可以必须是通过迭代器遍历的(数组下标也算),迭代器的类型为随机迭代器;
stl set map 使用红黑树 avl树作为底层数据结构的实现,不支持随机迭代器,所以不能使用sort来排序;
自己定义的数据结构支持这种随机迭代器时,也可以使用sort()算法来排序
3、排序是通过多次内存的copy来实现的,所以链表不能使用stl 算法sort来对其排序(next指针修改问题)(链表有自己的sort函数);
4、算法中的sort的时间复杂度:
stl <algorithm> 中的sort算法实现,采用快排的思想,平均的时间复杂度是 N*log2(N);
算法中还提供了其他的集中排序函数 sort_heap() stable_sort()(长度相同的维持原序), 时间复杂度都在 N*log2(N)
5、可以自定义比较函数(谓词),也可以调用stl内提供的比较函数,less<T>() 、greater<T>()
sort() 函数实例:
#include <iostream> #include <algorithm> using namespace std; bool compare(int x,int y) { return x<y?true:false; } int arr[5] = {3,2,5,8,4}; int main() { int i = 0; for(i=0;i<5;i++) cout<<arr[i]<<" "; cout<<endl; sort(arr,arr+5,compare); for(i=0;i<5;i++) cout<<arr[i]<<" "; return 0; }
相关文章推荐
- 开启或者关闭软键盘的工具类
- Android处理日期
- Ubuntu下远程访问MySQL数据库
- 最好的Python机器学习库
- 避免HttpClient的”javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated”异常
- pdf转png
- CSS3 Box-shadow
- 采用dlopen、dlsym、dlclose加载动态链接库
- [Leetcode]Populating Next Right Pointers in Each Node
- Android Studio基础之生成Apk(六)-学习篇
- Can't use Subversion command line client: svn.
- What We Talk About When We Talk About Distributed Systems
- Assert和Enumeration的用法
- 12月12日全球域名商保有量及市场份额排行榜16强
- Win10/UWP开发—凭据保险箱PasswordVault
- String与InputStream相互转换
- OS X EL Capitan U盘安装制作
- Drools6.1规则引擎环境搭建
- Linux多线程编程小结
- 设置 textarea 默认滑动到底部