Unexpected result decrementing end of range iterator in call to transform algorithm

Hi

I found this piece code on the following site:
http://www.interqiew.com/ask?ta=tqcpp01&qn=5

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?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <cstdio>

int main()
{
  typedef std::list<int> L;
  L l(5);

  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;

  return 0;
}

Hint: Modify line 18 to

1
2
// 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.

Thanks
Topic archived. No new replies allowed.