sort()函数:sort(begin, end, cmp)
,其中begin
为指向待sort()
的数组的第一个元素的指针,end
为指向待sort()
的数组的最后一个元素的下一个位置
的指针,cmp
参数为排序准则,如果没有的话,默认以非降序排序。
实例:
#include <iostream>#include <vector>#include<algorithm>using namespace std;bool cmp(int x,int y){return x >y;}//sort默认为非降序排序int main(){vector<int>a{2,5,1,4,6};//正向排序sort(a.begin(),a.end());for(auto i:a){cout<<i<<" ";}cout<<endl;//反向排序sort(a.rbegin(),a.rend());for(auto i:a){cout<<i<<" ";}cout<<endl;//带cmp参数的排序sort(a.begin(),a.end(),cmp);for(auto i:a){cout<<i<<" ";}cout<<endl;}
结果:
-VirtualBox:~/demo/stl/vector$ ./vector 1 2 4 5 6 6 5 4 2 1 6 5 4 2 1