100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > c++:vector sort()排序

c++:vector sort()排序

时间:2024-03-29 05:31:20

相关推荐

c++:vector sort()排序

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。