c++:vector sort()排序
sort()函数:sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,如果没有的话,默认以非降序排序。实例:#include <iostream>#include <vector>#include<algorithm>usi
文章共236字 · 阅读需要大约1分钟
一键AI生成摘要,助你高效阅读
问答
·
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
更多推荐
已为社区贡献1条内容
所有评论(0)