(原創) 如何使用Function Object? (C/C++) (STL)
很多STL algorithm都是_if結尾的,讓我們可以帶function進去,若配合function object,可讓function更有彈性!!
以下的範例想利用count_if() algorithm得知vector大於n的有幾個?
1/*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : FunctionObjectSimple.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use use Function Object
7Release : 01/18/2007 1.0
8*/
9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13using namespace std;
14
15bool biggerThan3(int);
16
17// Function Object
18struct biggerThan {
19 int n;
20 biggerThan(int n) : n(n) {} // Constructor
21 bool operator() (int val) { return val > n; }
22};
23
24int 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
33bool biggerThan3(int val) {
34 return val > 3;
35}
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : FunctionObjectSimple.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use use Function Object
7Release : 01/18/2007 1.0
8*/
9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13using namespace std;
14
15bool biggerThan3(int);
16
17// Function Object
18struct biggerThan {
19 int n;
20 biggerThan(int n) : n(n) {} // Constructor
21 bool operator() (int val) { return val > n; }
22};
23
24int 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
33bool biggerThan3(int val) {
34 return val > 3;
35}
執行結果
2
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帶多少都可以,當然更有彈性了。
See Also
(原創) 如何正確的使用迴圈(使用for_each)? (中級) (C++) (STL) (OO C++) (Template C++)
(原創) 如何為程式碼加上行號? (C/C++) (STL)