【C++】STL -- 仿函数的定义与使用
本篇文章主要讲解仿函数的定义及其使用
目录
1 仿函数的定义
2 仿函数的使用
3 总结
1 仿函数的定义
所谓的仿函数,其实就是在一个类里面重载了 () 这个运算符,所以看上去就像使用了函数一样,其实是该类调用了 operator() 这个函数,如:
#include<iostream>using namespace std;template<class T>
class Greater
{
public:bool operator()(const T& x, const T& y){return x > y;}
};int main()
{//创建一个仿函数类的对象Greater<int> g1;//看上去像是函数调用,其实是 g1.operator()(1, 2)cout << g1(1, 2) << endl;int x = 1, y = 2;cout << g1(x, y) << endl;return 0;
}
输出结果:
0
0
2 仿函数的使用
其实在 C++ 中,本来就为我们定义了两个仿函数的类,分别是 greater<T> 和 less<T>:
#include<iostream>using namespace std;int main()
{greater<int> g1;less<int> l1;cout << g1(1, 2) << endl;cout << l1(1, 2) << endl;return 0;
}
输出结果:
0
1
C++ 中仿函数的存在,其实就是 C 语言中普通函数的优化,比起普通函数,其本质就是用类来封装函数的行为,这就使得类似于函数的仿函数有了类的一些特性,比如继承与多态等等,当然其存在就是更多是为了满足 STL 的需求与实现 lambda 匿名函数(这里先不讲解匿名函数)。我们就通过一个算法库中的 sort 排序函数来讲解仿函数的使用。
sort 函数:
sort 函数底层使用的是快速排序,并且其在 algorithm 头文件下,使用之前要包含一下;sort 有两个重载,前两个参数都是一个容器的迭代器范围(数组的指针也可以),最后一个参数默认是 less<T>(),所以 sort 函数默认是升序排序的,如果你想要实现降序排序,就可以传 greater<T>():
#include<iostream>
#include<algorithm>
#include<vector>using namespace std;int main()
{vector<int> v1 = { 1, 3, 2, 5, 9, 7, 6, 10 };//默认是升序排序sort(v1.begin(), v1.end());for (auto& x : v1)cout << x << ' ';cout << endl;//如果想要实现降序,那就传 greater<int>()sort(v1.begin(), v1.end(), greater<int>());for (auto& x : v1)cout << x << ' ';cout << endl;//数组也可以进行排序和范围 forint arr[] = { 1, 3, 2, 5, 9, 7, 6, 10 };size_t n = sizeof(arr)/sizeof(arr[0]);sort(arr, arr + n);for (auto& x : arr)cout << x << ' ';cout << endl;return 0;
}
输出结果:
1 2 3 5 6 7 9 10
10 9 7 6 5 3 2 1
1 2 3 5 6 7 9 10
当然,在 sort 函数中你也可以传自己写的一个仿函数:
#include<iostream>
#include<algorithm>
#include<vector>using namespace std;template<class T>
class Greater
{
public:bool operator()(const T& x, const T& y){return x > y;}
};int main()
{vector<int> v1 = { 1, 3, 2, 5, 9, 7, 6, 10 };sort(v1.begin(), v1.end(), Greater<int>());for (auto& x : v1)cout << x << ' ';cout << endl;return 0;
}
输出结果:
10 9 7 6 5 3 2 1
3 总结
仿函数虽然作为 STL 六大组件之一,但是其本身并不是特别复杂,学起来还是比较简单的。仿函数并不是一个单独的模块,主要是为了 STL 中其他组件服务的;另外,仿函数还弥补了 C 语言中函数的一些缺点,是函数的优化版本。