如何使用Function Object? (C/C++) (STL)

來源:互聯網
上載者:User

很多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
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帶多少都可以,當然更有彈性了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.