我们分别给数组和向量两个名称:

int a[]={1,2,3,4,5};
vector<int> v;
  1. 头文件:#include<algorithm>;
  2. 作用:将数组或向量进行排序;
  3. 默认排序方式:升序;
  4. 使用格式(数组和vector):
sort(a,a+5);
sort(v.begin(),v.end());//默认升序

sort(a,a+5,greater<int>());
sort(v.begin(),v.end(),greater<int>());//降序

bool cmp(const int & a, const int & b){
   return a%10>b%10;   //这里我们自定义为a的个位数比b大,则a在b前
} //这里的返回值的含义是a必须在b前面返回true,否则返回false;

sort(a,a+5,cmp);
sort(v.begin(),v.end(),cmp);//自定义排序规则

is_sorted()

  1. 头文件:#include<algorithm>;
  2. 作用:检查数组或者向量是否被排序好;
  3. 默认检查方式:升序;
  4. 特殊要求:需要C++11的特性;
  5. 返回值:truefalse
  6. 使用格式:
is_sorted(a,a+5);
is_sorted(v.begin(),v.end());//默认升序检查

is_sorted(a,a+5,greater<int>());
is_sorted(v.begin(),v.end(),greater<int>());//降序检查

bool cmp(const int & a, const int & b){
  return a%10>b%10; 
} 

is_sorted(a,a+5,cmp);
is_sorted(v.begin(),v.end(),cmp);//自定义排序规则

相关文章:

  • 2022-12-23
  • 2021-11-02
  • 2021-07-09
  • 2021-07-14
  • 2021-12-21
  • 2021-07-12
  • 2021-10-14
  • 2022-02-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-02
  • 2022-12-23
  • 2022-01-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案