下面的代码用于计算满足以下条件的元素数:
(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;}
};我将上面的语句分解如下:
i > 5使用boost::bind(std::greater<int>(),_1,5)
i <=10使用boost::bind(std::less_equal<int>(),_1,10)。
我的问题是如何理解上面的代码,因为如果我编写了代码,我将编写以下代码:
boost::bind(std::greater<int>(),_2,5)用于i > 5,boost::bind(std::less_equal<int>(),_2,10)用于i <=10。
函数std::greater需要两个参数(即x和y),并确保x > y。所以我认为我们需要将y与5绑定,这样我们就可以找到所有的Xs。当然,我的想法是错误的。
有人能给我解释一下吗?谢谢
发布于 2012-01-03 11:52:58
占位符_1、_2等指定特定(最内部的) bind调用返回的函数器的参数,而不是您可能要构建的完整表达式的参数。例如:
boost::bind(std::greater<int>(),_1,5)..。bind返回一个函数器,该函数器将它接收的第一个参数作为第一个参数传递给greater<int>函数器。
https://stackoverflow.com/questions/8707671
复制相似问题