函數對象
(轉)
函數指針的一種替代策略是Function object(函數對象)。
函數對象與函數指針相比較有兩個方面的優點:首先如果被重載的調用操作符是inline函數則編譯器能夠執行內聯編譯,提供可能的性能好處;其次函數對象可以擁有任意數目的額外數據,用這些數據可以緩沖結果,也可以緩沖有助于當前操作的數據。
函數對象是一個類,它重載了函數調用操作符operator() ,該操作符封裝了一個函數的功能。典型情況下函數對象被作為實參傳遞給泛型算法,當然我們也可以定義獨立的函數對象實例。
來看下面的二個例子: 比較理解會更好些:
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
class Sum {
int val;
public:
Sum(int i) :val(i) { }
//當在需要int的地方,Sum將自動轉換為int類型
//這里是為了方便cout<<Sum的實例;
operator int() const { return val; }
//寫在類中的函數代碼一般默認為內聯代碼
int operator()(int i) { return val+=i; }
};
void f(vector<int> v)
{
Sum s = 0; //Sum s = 0等價于Sum s(0),不等價于Sum s;s = 0;
//對vector<int>中的元素求和
//函數對象被作為實參傳遞給泛型算法
s = for_each(v.begin(), v.end(), s);
cout << "the sum is " << s << "\n";
//更簡單的寫法,定義獨立的函數對象實例
cout << "the sum is " << for_each(v.begin(), v.end(), Sum(0)) << "\n";
}
int main()
{
vector<int> v;
v.push_back(3); v.push_back(2); v.push_back(1);
f(v);
system("pause");
return 0;
}
-----------------------------------------------
#include <iostream>
#include <list>
#include <algorithm>
#include "print.hpp"
using namespace std;
// function object that adds the value with which it is initialized
class AddValue {
private:
int theValue; // the value to add
public:
// constructor initializes the value to add
AddValue(int v) : theValue(v) {
}
// the ``function call'' for the element adds the value
void operator() (int& elem) const {
elem += theValue;
}
};
int main()
{
list<int> coll;
// insert elements from 1 to 9
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
PRINT_ELEMENTS(coll,"initialized: ");
// add value 10 to each element
for_each (coll.begin(), coll.end(), // range
AddValue(10)); // operation
PRINT_ELEMENTS(coll,"after adding 10: ");
// add value of first element to each element
for_each (coll.begin(), coll.end(), // range
AddValue(*coll.begin())); // operation
PRINT_ELEMENTS(coll,"after adding first element: ");
}
-------------------------------------------------------------------------
operator()中的參數為container中的元素
---------------------------
另外的實例:
Function Objects as Sorting Criteria
Programmers often need a sorted collection of elements that have a special class (for example, a collection of persons). However, you either don't want to use or you can't use the usual operator < to sort the objects. Instead, you sort the objects according to a special sorting criterion based on some member function. In this regard, a function object can help. Consider the following example:
// fo/sortl.cpp #include <iostream> #include <string> #include <set> #include <algorithm> using namespace std; class Person { public: string firstname() const; string lastname() const; ... }; /* class for function predicate * - operator() returns whether a person is less than another person */ class PersonSortCriterion { public: bool operator() (const Person& p1, const Person& p2) const { /* a person is less than another person * - if the last name is less * - if the last name is equal and the first name is less */ return p1.lastname()<p2.1astname() || (! (p2.1astname()<p1.lastname()) && p1.firstname()<p2.firstname()); } }; int main() { //declare set type with special sorting criterion typedef set<Person,PersonSortCriterion> PersonSet; //create such a collection PersonSet coll; ... //do something with the elements PersonSet::iterator pos; for (pos = coll.begin(); pos != coll.end();++pos) { ... } ... }
//fo/foreach3.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; //function object to process the mean value class MeanValue { private: long num; //number of elements long sum; //sum of all element values public: //constructor MeanValue() : num(0), sum(0) { } //"function call" //-process one more element of the sequence void operator() (int elem) { num++; //increment count sum += elem; //add value } //return mean value double value() { return static_cast<double>(sum) / static_cast<double>(num); } }; int main() { vector<int> coll; //insert elments from 1 to 8 for (int i=1; i<=8; ++i) { coll.push_back(i); } //process and print mean value MeanValue mv = for_each (coll.begin(), coll.end(), //range MeanValue()); //operation cout << "mean value: " << mv.value() << endl; }
posted on 2005-12-14 16:53 夢在天涯 閱讀(4851) 評論(1) 編輯 收藏 引用 所屬分類: CPlusPlus 、STL/Boost

