for_each accepts InputIterators :
//from c++ standard template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function f);
is it ok to change the object in Function f, like this :
struct AddOne { void operator()(int & x){x = x + 1;} }; std::vector<int> vec(10); std::for_each(vec.begin(),vec.end(),AddOne());
This code works in VC++2008 and also with GCC, but is it also portable (legal) code ?
(InputIterators are only guaranteed to be usable as rvalue, in this case they are used as lvalue in AddOne’s operator())
Read this article.
To be pedantic:
for_eachis a non-modifying sequence operation. The intent is not to modify the sequence. However, it is okay to modify the input sequence when usingfor_each.