std::sort:
将给定区间数据进行排序,默认由小到大.
#include <iostream>
#include <functional> //函数对象
#include <algorithm> //泛型算法库
#include <vector>
#include <ctime>
//自定义的std::greater 类
class SortCom{
public:
bool operator()(const int &left, const int &right)const{
return left > right;
}
};
template <typename T>
void ShowContainer(T& con){
#if 0
typename T::iterator it = con.begin();
for (; it != con.end();++it){
std::cout << *it << " ";
}
std::cout << std::endl;
#endif
for (auto it : con){
std::cout << it <<" ";
}
std::cout << std::endl;
//迭代器遍历或者for each语法
}
int main(){
std::vector<int> vec;
vec.reserve(10);
srand(time(nullptr));
for (int i = 0; i < 10; ++i){
vec.push_back(rand()%20);
}
ShowContainer(vec);
std::sort(vec.begin(),vec.end());//默认从小到大,operator<
ShowContainer(vec);
std::sort(vec.begin(),vec.end(),std::greater<int>());
//从大到小,传入含有operator()的greater类的实例
ShowContainer(vec);
std::sort(vec.begin(),vec.end(),std::less<int>());
//从小到大,传入含有operator()重载方法的less类的对实例
ShowContainer(vec);
std::sort(vec.begin(), vec.end(), SortCom());
//传入含有自定义的比较方法对象
ShowContainer(vec);
return 0;
}
时间复杂度:
平均 O(N·log(N)) 次比较,其中 N = std::distance(first, last) (C++11 前)
O(N·log(N)) 次比较,其中 N = std::distance(first, last) (C++11 起)
参考链接:
c++ std::sort