函數對象\
函數對象有三種類型:關係、邏輯、運算。爲使用函數對象,應包含<functional>頭文件。
想了解C++中定義的函數對象,看這個鏈接:http://msdn.microsoft.com/zh-cn/library/vstudio/86ke4swd.aspx
1.關係類型的函數對象:
equal_to<T> 測試是否相等
not_equal_to<T> 測試是否不相等
greater<T> 測試是否大於
greater_equal<T>
less<T> 測試是否小於
less_equal<T>
2.邏輯類型的函數對象:
logical_end<T>
logical_not<T>
logical_or<T>
3.算術類型的函數對象:
divides<T>
modulus<T>
negate<T>
函數對象就是一個重載了操作符()的對象,例如C++中greater的定義:
template<class Type>
struct greater : public binary_function <Type, Type, bool>
{
bool operator()(
const Type& _Left,
const Type& _Right
) const;
};
equal_to對象:
template<class Type>
struct equal_to : public binary_function<Type, Type, bool>
{
bool operator()(
const Type& _Left,
const Type& _Right
) const;
};
logical_and對象:
template<class Type>
struct logical_and : public binary_function<Type, Type, bool>
{
bool operator()(
const Type& _Left,
const Type& _Right
) const;
};
一個使用equal_to的例子:
// functional_equal_to.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
int main( )
{
vector <double> v1, v2, v3 ( 6 );
vector <double>::iterator Iter1, Iter2, Iter3;
int i;
for ( i = 0 ; i <= 5 ; i+=2 )
{
v1.push_back( 2.0 *i );
v1.push_back( 2.0 * i + 1.0 );
}
int j;
for ( j = 0 ; j <= 5 ; j+=2 )
{
v2.push_back( - 2.0 * j );
v2.push_back( 2.0 * j + 1.0 );
}
cout << "The vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
cout << "The vector v2 = ( " ;
for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
cout << *Iter2 << " ";
cout << ")" << endl;
// Testing for the element-wise equality between v1 & v2
transform ( v1.begin( ), v1.end( ), v2.begin( ), v3.begin ( ),
equal_to<double>( ) );
cout << "The result of the element-wise equal_to comparison\n"
<< "between v1 & v2 is: ( " ;
for ( Iter3 = v3.begin( ) ; Iter3 != v3.end( ) ; Iter3++ )
cout << *Iter3 << " ";
cout << ")" << endl;
}