Unexpected result decrementing end of range iterator in call to transform algorithm
I found this piece code on the following site:
I predicted the outcome as being 01230 as I thought the prefix decrement operator on iterator ce would prevent the final element of the list from being transformed.
I was wrong, the correct output is 01234.
So, I removed the decrement prefix and ran the test again, expecting a different result. It wasn't! The result was still 01234.
Only when I decremented ce twice did I get the result I initially expected, 01230.
Can someone explain why the first decrement of ce appears to have no effect?
typedef std::list<int> L;
typedef L::const_iterator CI;
CI cb = l.begin(), ce = l.end();
typedef L::iterator I;
I b = l.begin();
std::transform(cb, --ce, ++b, std::bind2nd(std::plus<CI::value_type>(), 1));
std::copy(l.begin(), l.end(), std::ostream_iterator<CI::value_type>(std::cout));
std::cout << std::endl;
Hint: Modify line 18 to
// std::transform(cb, --ce, ++b, std::bind2nd(std::plus<CI::value_type>(), 1));
std::transform(cb, ce, ++b, std::bind2nd(std::plus<CI::value_type>(), 1));
and we get undefined behaviour.
Yeah I see it now!
It threw me because the 'undefined behaviour' on my machine was to print the same result. It didn't crash or give any run-time error.
Topic archived. No new replies allowed.