c++ sort函数自定义排序

在网上查阅sort函数自定义排序资料,在写比较函数cmp时不明白为啥都要写到结构体里,也不明白a<b为啥是升序,a>b为啥是降序

struct cmp{  
    bool operator ()(const int a , const int b)  
    {  
        return a < b ;           // 从小到大,反过来就是从大到小   
    }  
}; 

在查看了官网后得到了结论
在这里插入图片描述
这里很好地解答了两个问题。

1. 为什么结构体可以传入sort函数?
sort函数的第三个参数可以是函数对象也可以是函数指针。何为函数对象?简而言之,重载了运算符()的类的对象就是一个函数对象。我们可以像调用一个函数一样去调用对象,如下

#include <iostream>
using namespace std;
class CAverage
{
public:
    double operator()(int a1, int a2, int a3)
    {  //重载()运算符
        return (double)(a1 + a2 + a3) / 3;
    }
};
int main()
{
    CAverage average;  //能够求三个整数平均数的函数对象
    cout << average(3, 2, 3);  //等价于 cout << average.operator(3, 2, 3);
    return 0;
}

average 是一个对象,average(3, 2, 3) 实际上就是 average.operator(3, 2, 3),这使得 average 看上去像函数的名字,故称其为函数对象。

2. 为什么a<b为啥是升序,a>b是降序?
官网给出的答案是返回值operator(int a, int b){return a<b}若返回true则a在b前,若为false则b在a前。所以若a=10 b=5,则返回false,排序为5 10,若a=5 b=10返回true,排序也为5 10。由此看来若operator(int a, int b){return a<b},则为升序排列。若operator(int a, int b){return a>b},则为降序排列。
下附上官网例程

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
 Edit & Run

猜你喜欢

转载自blog.csdn.net/qq_37340588/article/details/107122792