您的位置:首页 > 其它

STL sort()

2015-12-15 10:26 381 查看
标准模版库中sort函数包含在头文件 <algorithm> 中,std::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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: