STL_算法_中使用的函数对象

写在前面:

  STL算法中的 函数对象的功能:

    (1)、都是提供一种比较的函数,比较相邻的左右两个值的 相等/大小 等的关系,

    (2)、返回值都是bool :该返回值 貌似是指明 遍历元素是否还要继续往下进行,返回true==>继续下一组相邻元素的比较,返回false==>中断下一组相邻元素的比较。

 

 

1、

例如:

binary_search(?, ?, ?, ?); 

中的 第4个参数 是一个函数对象。

 

然后,第4个参数 可以传入下面3中样式的值:

1.1、

类似这样:

bool CompareInt (const int& _iLeft, const int& _iRight)
{
    return _iLeft < _iRight;
}

  可以这样写:binary_search(?, ?, ?, CompareInt); 

  ZC: 这里直接传的是 函数指针

 

1.2、(C++ 中 struct 和 class 是一回事)

1.2.1、

类似这样:

struct CompareFunctor
{
public:
    bool operator() (const int& _iLeft, const int& _iRight)
    {
        return (_iLeft < _iRight);
    }
};

  可以这样写:binary_search(?, ?, ?, CompareFunctor()); 

  ZC: 这里传的是 struct的对象

 

1.2.2、

类似这样:

class CompareFunctor
{
public:
    bool operator() (const int& _iLeft, const int& _iRight)
    {
        return (_iLeft < _iRight);
    }
};

  可以这样写:binary_search(?, ?, ?, CompareFunctor()); 

  ZC: 这里传的是 类对象

 

2、

 

posted @ 2016-03-08 16:28  CppSkill  阅读(323)  评论(0编辑  收藏  举报