dendritic dendritic - 1 year ago 149
C++ Question

error: expression must be a modifiable lvalue when using find_if

I have two vectors of classes that contain mainly strings, and I'm trying to keep track of how many times there was a match between two vectors. I kept an

counter in one of the two public classes (necessary for another function). However,
doesn't seem to allow me to modify nor assign this counter variable.

Following is the
search algorithm:

for (Vector1& v1 : vector1) {
auto res = find_if(vector2.begin(), vector2.end(),
[=](Vector2 v2) {
if (v2.code == v1.code) {
v1.counter++; // <-- where the error occurs
return true;
return false;

I can't seem to figure out why this happens; my speculation is that the third parameter for the
algorithm takes in a
value. But that shouldn't affect my
, right?

I used nested ranged for-loops instead, and it works perfectly. However, I'd like to try using this
algorithm instead...

Answer Source

You have a problem with capture/pass by value/reference.

It should be [&] or [&v1] - variables captured by value are non-mutable by default, and lambda's operator() is const. You could use the mutable keyword to fix the error, which makes operator() non-const, but you wouldn't see the changes made to v1 anyways.

Additionally, you should be passing by Vector2 const& v2, auto const& or auto && in sake of avoiding making a copy.


[&v1](Vector2 const& v2) { ... }

I'd like to try using this find_if algorithm instead...

But that's not what it's for. If you aren't going to use the returned iterator, don't do it. You should be getting a warning. Use loops for simple iteration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download