很多STL algorithm都是_if結尾的,讓我們可以帶function進去,若配合function object,可讓function更有彈性!!
以下的範例想利用count_if() algorithm得知vector大於n的有幾個?
1
/*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : FunctionObjectSimple.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use use Function Object
7
Release : 01/18/2007 1.0
8
*/
9
#include <iostream>
10
#include <vector>
11
#include <algorithm>
12
13
using namespace std;
14
15
bool biggerThan3(int);
16
17
// Function Object
18
struct biggerThan {
19
int n;
20
biggerThan(int n) : n(n) {} // Constructor
21
bool operator() (int val) { return val > n; }
22
};
23
24
int main() {
25
int ia[] = {1, 2, 3, 4, 5};
26
vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
27
int i = count_if(ivec.begin(), ivec.end(), biggerThan3);
28
cout << i << endl;
29
int j = count_if(ivec.begin(), ivec.end(), biggerThan(3));
30
cout << j << endl;
31
}
32
33
bool biggerThan3(int val) {
34
return val > 3;
35
}
/* 2
(C) OOMusou 2007 http://oomusou.cnblogs.com3

4
Filename : FunctionObjectSimple.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Demo how to use use Function Object7
Release : 01/18/2007 1.08
*/9
#include <iostream>10
#include <vector>11
#include <algorithm>12

13
using namespace std;14

15
bool biggerThan3(int);16

17
// Function Object18
struct biggerThan {19
int n;20
biggerThan(int n) : n(n) {} // Constructor21
bool operator() (int val) { return val > n; }22
};23

24
int main() {25
int ia[] = {1, 2, 3, 4, 5};26
vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));27
int i = count_if(ivec.begin(), ivec.end(), biggerThan3);28
cout << i << endl;29
int j = count_if(ivec.begin(), ivec.end(), biggerThan(3));30
cout << j << endl;31
}32

33
bool biggerThan3(int val) {34
return val > 3;35
}
執行結果
2
2
若沒有function object,我們就只能帶一個function name進去,由於其signature是固定的,所以只能帶進如33行那樣固定n的function,但STL algorithm還允許我們帶function object進去,若能用function object,就很有彈性了,18~22行將function包成function object,當然用class也行,但若用struct可以省去public:字眼,首先用constructor接下參數,然後對() operator做overload,這樣29行就可以帶參數進去,無論n帶多少都可以,當然更有彈性了。


biggerThan(
浙公网安备 33010602011771号