algorithm 头文件参考

定义执行算法的 C++ 标准库容器模板函数。

备注

<algorithm> 库还使用该 #include <initializer_list> 语句。


目录

sort将指定范围中的元素按非降序顺序排列,或根据二元谓词指定的排序条件排列。


sort将指定范围中的元素按非降序顺序排列,或根据二元谓词指定的排序条件排列。

const _RanIt _First, const _RanIt _Last

int main()
{
  int num[55] = { 0 };
  num[0] = 1;
  num[1] = 11;
  num[2] = 5;
  num[3] = 8;
  num[5] = 12;
  num[6] = 19;
  sort(num, num + 6);
  for (int i = 0; i <=6; i++)
  {
    cout << num[i] << "";
  }
  cout << endl;
  return 0;
}

const _RanIt _First, const _RanIt _Last, _Pr _Pred

_Pr _Pred

用户定义的谓词函数对象,定义排序中连续元素要满足的比较条件。 该二元谓词采用两个参数,并且,如果两个参数按顺序排序,将返回 true,否则将返回 false。 该比较器函数必须对序列中的元素对进行严格弱排序。

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

int main()
{
  int num[55] = { 0 };
  num[0] = 1;
  num[1] = 11;
  num[2] = 5;
  num[3] = 8;
  num[5] = 12;
  num[6] = 9;
  //greater<int>() 降序的谓语 按降序排序
  sort(num, num + 6,greater<int>());
  sort(num, num + 6,cmp);
  for (int i = 0; i <=6; i++)
  {
    cout << num[i] << "";
  }
  cout << endl;
  return 0;
}

sort自定义类型排序

自定义排序 必须给一个排序方法 ,或者你必须给他重载一个 < 否则会报错

操作符重载

也可以 在类中进行操作符重载

bool  operator< (const xxx& b)const {

return this->s > b.s;

}

#include <iostream>
#include <string>
#include <algorithm>
using   namespace std;

struct xxx
{
  string name;
  int num, age, s;

};
// 3x4 =12  20位4的倍数32 

//如果
bool cmp(const xxx& a, const xxx& b) {
  return a.s > b.s;
}

int main()
{
  xxx a_abs64[205];
  a_abs64[0].name = "xxxx";
  a_abs64[0].num = 1;
  a_abs64[0].age = 18;
  a_abs64[0].s = 100;
  a_abs64[1].name = "aaa";
  a_abs64[1].num = 2;
  a_abs64[1].age = 9;
  a_abs64[1].s = 90;
  a_abs64[2].name = "bbbb";
  a_abs64[2].num = 3;
  a_abs64[2].age = 22;
  a_abs64[2].s = 80;
  sort(a_abs64, a_abs64 + 2, cmp);
  //自定义排序 必须给一个排序方法 ,或者你必须给他重载一个<
  for (int i = 0; i <= 2; i++)
  {
    cout << a_abs64[i].num << "  " << a_abs64[i].name << "" << " " << a_abs64[i].s << endl;
  }
  return 0;
}
posted @ 2022-06-29 13:52  Aquiet  阅读(300)  评论(0编辑  收藏  举报