I have been fiddling around with lambda expressions to learn how they work but came across an issue. I have been trying to figure what I am doing wrong but can’t seem to. The compiler just refuses to accept this simple example:
int a = 2;
std::vector<int> vv(10);
vv[2]=2;
std::count( vv.begin(), vv.end(), [&a](int z) { return a == z; } );
I get the error
Error 1 error C2678: binary '==' : no operator found
which takes a left-hand operand of type 'int' (or there is no
acceptable conversion) e:\program files (x86)\microsoft visual studio
11.0\vc\include\xutility 3243
What am I doing wrong?
The algorithms need to know whether a predicate is based on comparing a value using equality or a unary predicate. To distinguish the two, a
_ifsuffix is used for various algorithms:find_if(),`copy_if(),count_if(), etc. The lambda is OK but it isn’t equality-comparable to thevalue_typeof the sequence. You need to usestd::count_if()when using a predicate:… or a value: