《C++必知必会》还真是不错,上一章讲到用函数对象替换函数指针,今天翻了翻,又看到讲到STL函数对象,其实道理和上一章也差不多,唯一不同的是,如果用STL函数对象,必须记得,这些函数对象都是继承标准函数对象:std::binary_function(二元函数)、std::unary_function(一元函数)。还是重载operator()操作符。这样的STL函数,可以成为内联函数,并且可以用标准库的算法,还是有必要学习一下的。
下面的例子是 根据书上的内容写的,PopLess是一个比较大小的函数,IsTen更简单了,就是判断类的id是不是10。看看吧,就当开卷有益了。
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include<time.h>
using namespace std;
class State
{
//a class which has id as its member
public:
State() : m_id(0) {}
void set_id( int id ) { m_id = id; }
int id() const { return m_id; }
private:
int m_id;
};
struct PopLess : public std::binary_function<State, State, bool>
{
bool operator() ( const State &a, const State &b ) const
{ return a.id() < b.id(); }
};
struct IsTen : public std::unary_function<State, bool>
{
bool operator() ( const State &a ) const
{ return a.id() == 10; }
};
int main(int argc, char *argv[])
{
State st[10];
srand((int)time(0));
cout << "create st.............." << endl;
for( int ix = 0; ix < 10; ix++ )
{
int id = 1+(int)(10.0*rand()/(RAND_MAX+1.0));
st[ix].set_id( id );
cout << st[ix].id() << endl;
}
cout << "create over............." << endl;
sort( st, st+10, PopLess() );
cout << "after sort st.............." << endl;
for( int ix = 0; ix < 10; ix++ )
{
cout << st[ix].id() << endl;
}
cout << "display over............." << endl;
State *tenState = find_if( st, st+10, IsTen() );
if( tenState != st+10 )
{
cout << "find 10" << endl;
}
else
{
cout << "can't find 10" << endl;
}
system("PAUSE");
return 0;
}