-3

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 int counter in one of the two public classes (necessary for another function). However, std::find_if doesn't seem to allow me to modify nor assign this counter variable.

Following is the std::find_if 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;
            }
            else
                return false;
        }
    );
}

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

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

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
dendritic
  • 199
  • 1
  • 10

1 Answers1

5

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.

Together:

[&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.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74