I just read in the C++ standard that std::for_each
is a non-modifying sequence operation, along with find
, search
and so on. Does that mean that the function applied to each element should not modify them? Why is that? What could possibly go wrong?
Here is a sample code, where the sequence is modified. Can you see anything wrong with it?
void foo(int & i)
{
i = 12;
}
int main()
{
std::vector<int> v;
v.push_back(0);
std::for_each(v.begin(), v.end(), foo);
// v now contains 12
}
I suspect this to be just an interpretation issue, but I wanted to have your opinion about that.
PS: I know I could use std::transform
instead of for_each
, but that's not the point.