gpt4 book ai didi

c++ - boost::bind 如何与 std::greater 和 std::less_equal 一起工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:56:42 27 4
gpt4 key购买 nike

下面的代码是用来统计满足以下条件的元素的个数:

(i > 5) && (i <=10)

std::vector<int> ints;
..
int count=std::count_if(
ints.begin(),
ints.end(),
boost::bind( // # bind 1
std::logical_and<bool>(),
boost::bind(std::greater<int>(),_1,5), // # bind 2
boost::bind(std::less_equal<int>(),_1,10))); // # bind 3

template <class T> struct greater : binary_function <T,T,bool> {
bool operator() (const T& x, const T& y) const
{return x>y;}
};

我把上面的语句分解如下:

boost::bind(std::greater<int>(),_1,5)用于i > 5

boost::bind(std::less_equal<int>(),_1,10)用于i <=10 .

我遇到的问题是如何理解上面的代码,因为如果我写了代码,我会写如下:

boost::bind(std::greater<int>(),_2,5)用于i > 5 boost::bind(std::less_equal<int>(),_2,10)用于i <=10 .

函数std::greater需要两个参数(即 xy )并确保 x > y .所以我认为我们需要绑定(bind) y5这样我们就可以找到所有Xs .当然,我的想法是错误的。

有人可以为我解释一下吗?谢谢

最佳答案

占位符 _1 , _2等指定仿函数的参数具体(最内层)bind调用返回,而不是您可能正在构建的完整表达式。 IE。对于:

boost::bind(std::greater<int>(),_1,5)

... bind返回一个仿函数,将它接收到的第一个参数作为第一个参数传递给 greater<int>仿函数。

关于c++ - boost::bind 如何与 std::greater 和 std::less_equal 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8707671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com