[Cs3] Binding
Mikhail Nesterenko
mikhail at cs.kent.edu
Wed Oct 18 09:22:12 EDT 2017
>
> I realize it is late, but I have 1 question about binders.
>
> The following code generates an error:
>
> std::vector<int> vect = {3, 22, 1, 77, 88};
>
> auto it = find_if(vect.begin(), vect.end(), bind(std::greater_equal<int>(),
> 2, _2));
>
> cout << *it << endl;
>
>
> while this does not:
>
> std::vector<int> vect = {3, 22, 1, 77, 88};
>
> auto it = find_if(vect.begin(), vect.end(), bind(std::greater_equal<int>(),
> 2, _1));
>
> cout << *it << endl;
>
>
> I would expect the first code I sent you to bind the first parameter of
> greater_equal to 2.
> The first parameter is what is compared against the second parameter,
> according to cppref.
>
> Then I would expect the integers from the vector to be used as the 2nd
> parameter, one after another, in the find_if().
>
> Essentially, finding the first element in vect that is less than 2.
>
> I realize this doesn't exactly have a practical use, but I am confused as
> to why the binding is not working.
>
> The second code snippet I sent you does what I described and finds the
> first element in vect that is less than 2.
>
> My confusion:
> Why does the placeholder need to be _1, in this situation?
_1 is the argument for the _new_ bound function. It will have one
argument so _2 is not there. Hence, your first code fragment does not
work. Below is the the variant that compiles and works.
Thanks,
--
Mikhail
----
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout; using std::endl;
using namespace std::placeholders;
int main(){
std::vector<int> vect = {3, 22, 1, 77, 88};
auto it = find_if(vect.begin(), vect.end(), bind(std::greater_equal<int>(),
_1, 2));
cout << *it << endl;
/* // or this
std::vector<int> vect = {3, 22, 1, 77, 88};
auto it = find_if(vect.begin(), vect.end(), bind(std::greater_equal<int>(),
2, _1));
cout << *it << endl;
*/
}
More information about the cs3
mailing list