前言
C和C++里面有非常多令人迷惑的特性,operator()
就是其中一个。看完本文之后你会知道,他的本质其实就只是一个匿名函数,C++开发者利用这个畸形的办法实现了类似java里Comparable
接口的功能。
第一次见到这个东西的时候是学算法的时候,需要各种调sort()
。为了实现逆序排列,我们都会调用一个sort(vec.begin(), vec.end(), std::greater<int>())
的东西。
随着题目难度的增加,我们需要对自己定义的class
或者struct
进行排序,比如对二维点进行排序。这个时候如果想自己定义决定以x坐标作为排序的标准,就头疼了。
我们知道,std::sort()
会利用元素自身的小于符号<
进行排序。
因此有一种比较简单的解决方法是重载小于符号<
:
class MyPoint{
int x, y;
bool operator<(const MyClass& other)const{
return x < other.x;
}
};
注意这两个const
不能省略,这是sort
对于重载<
的要求。
这样就可以进行逆序排列了,下面这个例子是一个类似于HelloWorld的例子:
#include<iostream>
#include<algorithm>
using namespace std;
class MyPoint{
public:
int x,y;
MyPoint(int x, int y){
this->x = x;
this->y = y;
}
bool operator<(const MyPoint& other)const{
return x < other.x;
}
};
int main(){
MyPoint points[] = {
MyPoint(2,1), MyPoint(1,2)};
sort(points, points+2);
for(MyPoint& p : points){
cout << p.x << endl