q0987
q0987

Reputation: 35982

How does the boost::bind work with std::greater and std::less_equal

The following code is designed to count the number of elements that satisfy the following condition:

(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 decompose the above statement as follows:

boost::bind(std::greater<int>(),_1,5) is used for i > 5

boost::bind(std::less_equal<int>(),_1,10) is used for i <=10.

The problem I have is how to understand the above code because if I wrote the code and I will write the following:

boost::bind(std::greater<int>(),_2,5) is used for i > 5 boost::bind(std::less_equal<int>(),_2,10) is used for i <=10.

The function std::greater needs two parameters (i.e. x and y) and makes sure that x > y. So I thought we need to bind y with 5 so that we can find all Xs. Of course, my thought is wrong.

Can someone explain for me? Thank you

Upvotes: 2

Views: 1510

Answers (1)

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

The placeholders _1, _2, etc. designate the parameters of the functor the specific (inner-most) bind call returns, not for the full expression you might be building. I.e. for:

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

... the bind returns a functor that passes the first parameter it receives as the first argument to the greater<int> functor.

Upvotes: 2

Related Questions