仿函数一般不会单独使用,主要是为了搭配STL算法使用

    函数指针不能满足STL对抽象性的要求,不能满足软件积木的要求,无法和STL其他组件搭配

    本质就是类重载了一个operate(),创建一个行为类似函数的对象

    1. #include <algorithm>
    2. #include <iostream>
    3. using namespace std;
    4. //模板编程
    5. template <class T>
    6. inline bool MySortT(T const &a, T const &b){
    7. return a>b;
    8. }
    9. template <class T>
    10. inline void DisplayT(T const &a){
    11. cout << a << " ";
    12. }
    13. //仿函数
    14. struct SortF{
    15. bool operator()(int a, int b){
    16. return a > b;
    17. }
    18. };
    19. struct DisplayF{
    20. void operator()(int a){
    21. cout << a << " ";
    22. }
    23. };
    24. //c++仿函数模板
    25. template <class T>
    26. struct SortTF{
    27. inline bool operator()(T const &a, T const &b) const {
    28. return a > b;
    29. }
    30. };
    31. template <class T>
    32. struct DisplayTF{
    33. inline void operator()(T const &a) const {
    34. cout << a << " ";
    35. }
    36. };
    37. int main(){
    38. int arr[] = {4,3,4,1,5};
    39. //泛型
    40. sort(arr, arr + 5, MySortT<int>);
    41. for_each(arr, arr+5, DisplayT<int>);
    42. cout << endl;
    43. //仿函数
    44. sort(arr, arr + 5, SortF());
    45. for_each(arr, arr+5, DisplayF());
    46. cout << endl;
    47. //仿函数模板
    48. sort(arr, arr + 5, SortTF<int>());
    49. for_each(arr, arr+5, DisplayTF<int>());
    50. cout << endl;
    51. return 0;
    52. }