0%

函数 -> 函数模板 struct仿函数 -> struct仿函数模板

2020年5月16日 下午11:50

总结:

  1. 对于algorithm中的两个函数:
    1. sort
    2. for_each
  2. 有两种思路:
    1. 函数 -> 函数模板
    2. struct仿函数 -> struct仿函数模板
  3. 这种做算法题的时候容易用上,所以还是稍微记忆一下好!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Demo9-3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <algorithm>
#include <iostream>
using namespace std;
// C++方式
bool MySort(int a, int b)
{
return a < b;
}

void Display(int a)
{
cout << a << " ";
}

// C++泛型
template<class T>
inline bool MySortT(T const& a, T const& b)
{
return a < b;
}

template<class T>
inline void DisplayT(T const& a)
{
cout << a << " ";
}

// C++仿函数
struct SortF
{
bool operator() (int a, int b)
{
return a < b;
}
};
struct DisplayF
{
void operator() (int a)
{
cout << a << " ";
}
};

// C++仿函数模板
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()
{
// C++方式
int arr[] = { 4, 3, 2, 1, 7 };
sort(arr, arr + 5, MySort);
for_each(arr, arr + 5, Display);
cout << endl;

// C++泛型
int arr2[] = { 4, 3, 2, 1, 7 };
sort(arr2, arr2 + 5, MySortT<int>);
for_each(arr2, arr2 + 5, DisplayT<int>);
cout << endl;


// C++仿函数
int arr4[] = { 4, 3, 2, 1, 7 };
sort(arr4, arr4 + 5, SortF());
for_each(arr4, arr4 + 5, DisplayF());
cout << endl;

// C++仿函数模板
int arr3[] = { 4, 3, 2, 1, 7 };
sort(arr3, arr3 + 5, SortTF<int>() );
for_each(arr3, arr3 + 5, DisplayTF<int>());
cout << endl;

return 0;
}