Alex Rivera | Logout

Is it ok to mutate objects with std::for_each?

Asked 2009-04-04T17:56:27.360
9

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())

Edit
Report

1 Answer

3

If in doubt use std::transform as it will convey even to the casual reader of your code that you intend to modify something.

answered 2009-04-06T02:33:41.493

Your Answer