1、bind1st和bind2end

  bind1st和bind2end是C++中的函数绑定器,它可以将一个变量绑定至一个二元函数对象,从而获得一个一元函数对象。使用需要包含头文件<functional>

  比如我们使用find_if()查找容器中大于100的元素,使用函数和函数对象的方法是如下:

bool GreaterThan(const int& i)
{
    return i > 100;
}

class CGreaterThan
{
public:
    bool operator()(const int&i)
    {
        return i > 100;
    }
};

int main()
{
    vector<int> v = list_of(5) (2) (101) (3);
    auto iter = find_if(v.begin(), v.end(), /*GreaterThan*/CGreaterThan());
    if (iter != v.end())
        cout << *iter << endl;

    return 0;
}
View Code

   而使用函数绑定器的话就不用我们自定义函数或函数对象,如下所示:

#include <functional>
int main()
{
    vector<int> v = list_of(5) (2) (101) (3);
    int x = 100;
    auto iter = find_if(v.begin(), v.end(), bind2nd(greater<int>(), x));
    if (iter != v.end())
        cout << *iter << endl;

    return 0;
}
View Code

相关文章:

  • 2021-09-17
  • 2021-05-21
  • 2021-11-25
  • 2021-12-19
  • 2022-02-03
  • 2021-06-17
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-01
  • 2021-10-07
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
  • 2021-08-07
相关资源
相似解决方案