两种方法 1、使用vector的自带sort,不用自己写比较函数,排序的标准按照vector的元素类型不同而不同:
例如:如果是vector,那么 sort(v.begin(),v.end()) 就是按照数字大小,从小到大排序,如果写成 sort(v.rbegin(),v,rend()) 就是从大到小进行排序
2、使用自己写的比较函数,再使用sort
例如:bool issaml(const int &x,const int &y)
{ return x < y}
这里最好写成const 避免出错。
然后再使用函数sort(const int &x, const int &y,issmal)
注意这里的saml没有括号。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool issmall(const int &x,const int &y);
void pri(vector<int> v,int n);
int main()
{
vector<int> v;
int n;
cin >> n;
for(int i = 0,num; i < n; ++i)
{
cin >> num;
v.push_back(num);
}
sort(v.begin(),v.end(),issmall);
pri(v,n);
return 0;
}
bool issmall(const int &x,const int &y)
{
return x < y ;
}
void pri(vector<int> v,int n)
{
for(auto beg = v.begin(); beg != v.end(); beg++)
cout << *beg << " ";
}