|
发表于 2023-2-21 19:35:32
|
显示全部楼层
sort函数的第2个参数要求是一个可调用的对象
这可以是一个匿名函数,也可以是命名的函数,还可以是一个有operator()的类对象
bool operator()(const int v1,const int v2)
这个应该不是重载函数吧,这个是成员函数,不是静态的
下面是一个关于可调用对象的例子
- sh-5.1$ cat main.cpp
- #include <iostream>
- #include <functional>
- bool func(int a, int b, std::function<bool (int a, int b)> f) {
- return f(a, b);
- }
- bool equal(int a, int b) {return a == b;}
- class less_t {
- public:
- bool operator()(int a, int b) {return a < b;}
- };
- int main() {
- std::cout << func(1, 2, [](int a, int b) {return a > b;}) << std::endl;
- std::cout << func(1, 2, equal) << std::endl;
- std::cout << func(1, 1, equal) << std::endl;
- std::cout << func(1, 2, less_t()) << std::endl;
- std::cout << less_t()(1, 2) << std::endl;
- std::cout << less_t()(2, 1) << std::endl;
- return 0;
- }
- sh-5.1$ ./main
- 0
- 0
- 1
- 1
- 1
- 0
- sh-5.1$
复制代码 |
|