STL函数对象

《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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值