Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

like image 975
qwerty Avatar asked Apr 04 '09 17:04

qwerty


2 Answers

Read this article.

To be pedantic: for_each is a non-modifying sequence operation. The intent is not to modify the sequence. However, it is okay to modify the input sequence when using for_each.

like image 74
dirkgently Avatar answered Oct 18 '22 20:10

dirkgently


You misunderstand something. Saying input iterators are only guaranteed to be usable as rvalues doesn't mean you can't get an lvalue out of an iterator somehow. So it does not mean that the result of *iterator is an rvalue. What you/for_each passes to AddOne is the result of operator* - not the iterator itself.

About for_each and a modifying function object - read this question

like image 30
Johannes Schaub - litb Avatar answered Oct 18 '22 22:10

Johannes Schaub - litb