Before few days I asked about if I implemented operator++(int) correctly and this was the code.
1 2 3 4 5 6 7 8 9 10 11 12
class INT {
int i;
public:
INT(int ii) : i{ ii } {}
operatorint() { return i; }
INT& operator++() { ++i; return *this; }
INT operator++(int) { int temp = i; ++i; return temp; } //is this the way to go?
INT& operator--() { --i; return *this; }
INT operator--(int) { int temp = i; --i; return temp; } //is this the way to go?
};
I got the answer that it was correct and it behaved well. However now I'm continuing to read my book and I see this "unrelated" example about for_each implementation
1 2 3 4 5 6
template<typename Iter, typename Fct>
Fct for_each(Iter b, Iter e, Fct f)
{
while(b != e) f(*b++);
return f;
}
In this code function object was trying to change all the elements of vector by adding them some number what function object holds.
But if my operator++(int) implementation was correct b++ is only giving temporary copy of element I wanted to increase not the actual element. So as I see it - this for_each() with my kind of ++(int) implementation wouldn't do a thing to vector's elements.
So is my ++ implementation wrong or what exactly is happening here?
But if my operator++(int) implementation was correct b++ is only giving temporary copy of element I wanted to increase not the actual element. So as I see it - this for_each() with my kind of ++(int) implementation wouldn't do a thing to vector's elements.
The only thing that's being incremented here is an iterator.
In this code function object was trying to change all the elements of vector by adding them some number what function object holds.
Incorrect. What for_each() does is call the parameter function once for each element between b and e. What's confusing you is the order of operations of *b++. That expression is equivalent to *(b++), not (*b)++. The iterator itself, not what it point to, is being incremented.
I would also like to note that a more canonical implementation of postfix increment would be
1 2 3 4 5
T operator++(int){
T ret = *this;
++*this;
return ret;
}
This implementation is valid for any class that correctly implements prefix increment and a copy constructor.