#include <vector>
#include <algorithm>
#include <functional>
template< class iterator, class predicate, class doer>
void for_each_if( iterator itFirst, iterator itLast, predicate pred, doer do_it)
{
while ( itFirst != itLast)
{
if ( pred( *itFirst)) do_it( *itFirst);
++itFirst;
}
}
void print( int i) { std::cout << i << " "; }
int _tmain(int argc, _TCHAR* argv[])
{
int aNumbers[] = { 10, 5, 89, 9, 30, -2, -8, 7, 33, 25, 30, 76, 0, 2};
int nCount = sizeof( aNumbers) / sizeof( aNumbers[ 0]);
// a < b
std::cout << "\nNumbers less than 30: ";
for_each_if( aNumbers, aNumbers + nCount,
std::bind2nd( std::less< int>(), 30), print);
std::cout << "\nNumbers bigger than 30: ";
// a > b
for_each_if( aNumbers, aNumbers + nCount,
std::bind1st( std::less< int>(), 30), print);
std::cout << "\nNumbers less or equal than 30: ";
// a <= b <=> !(a > b)
for_each_if( aNumbers, aNumbers + nCount,
std::not1( std::bind1st( std::less< int>(), 30)), print);
std::cout << "\nNumbers bigger or equal than 30: ";
// a >= b <=> !(a < b)
for_each_if( aNumbers, aNumbers + nCount,
std::not1( std::bind2nd( std::less< int>(), 30)), print);
return 0;
}
call operator()和构造函数以及仿函数(仿函数不是函数,而是一个类,这个类重载了()操作符)
class A
{
public:
A()
{
m_a = 0;
}
A(int args)
{
m_a = args;
}
bool operator()(int a)
{
std::cout << a;
return false;
}
private:
int m_a;
};
就这个类来说:
call operator() 的方法:
1 A a(12);//call con
a(13);//call ()
a.operator()(13);//call ()
2 A* p_a = new A;
p_a(13);//错的
(*p_a)(13);//call ()
p_a->operator()(13);//call ()
struct A
{
int n_;
int add(int args){return n_+= args;}
int test(){return n_;}
};
A a(10);
int n1 = mem_fun_ref(&A::test)(a);
int n2 = mem_fun_ref(&A::add)(a,100);//重载() 时候用到得参数 ,奇特吧
直接上代码是最直接的 ,胜过很多的文字
仿函数就是实现了operator() ,没有其他很特别的,类似上面的,一般函数如print 调用直接是函数名,仿函数需加上括号
代码多看多想多写。。。