仿函数 functor
- 仿函数一般不会单独使用,主要是为了搭配STL算法使用。补充STL算法的很好的方式
- 函数指针不能满足STL对抽象性的要求,不能满足软件积木的要求无法和STL其他组件搭配:
- 本质就是类重载了一个operator(),创建一个行为类似函数的对象
#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <stack>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;
void Display(int a) {
cout << a << " ";
}
bool MySort(int a, int b)
{
return a > b;
}
template<class T>
inline void DisplayT(T const& a) {
cout << a << " ";
}
template<class T>
inline bool MySortT(T const& a, T const& b)
{
return a > b;
}
struct SortF
{
bool operator()(int a, int b)
{
return a > b;
}
};
struct DisplayF
{
void operator()(int a)
{
cout << a << " ";
}
};
template<class T>
struct SortTF
{
inline bool operator() (T const& a, T const& b) const
{
return a > b;
}
};
template<class T>
struct DisplayTF
{
inline void operator() (T const& a) const
{
cout << a << " ";
}
};
int main() {
int arr[] = { 4,3,2,1,5 };
sort(arr, arr + 5, MySort);
for_each(arr, arr + 5, Display);
cout << endl;
int arr2[] = { 4,3,2,1,5 };
sort(arr2, arr2 + 5, MySortT<int>);
for_each(arr2, arr2 + 5, DisplayT<int>);
cout << endl;
int arr3[] = { 4,3,2,1,5 };
sort(arr3, arr3 + 5, SortF());
for_each(arr3, arr3 + 5, DisplayF());
cout << endl;
int arr4[] = { 4,3,2,1,5 };
sort(arr4, arr4 + 5, SortTF<int>());
for_each(arr4, arr4 + 5, DisplayTF<int>());
cout << endl;
return 0;
}