Advertisement
homer512

reverse_iterator gotcha

Jul 20th, 2013
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <list>
  2. #include <cassert>
  3.  
  4. template<class reverse_iterator>
  5. typename reverse_iterator::iterator_type reverse_to_normal(reverse_iterator i)
  6. {
  7.   ++i; // look at reverse_iterator documentation why this is necessary
  8.   return i.base();
  9. }
  10.  
  11. int main()
  12. {
  13.   std::list<int> list; /* same behavior with std::set */
  14.  
  15.   /* Let's fill our container a bit */
  16.   list.push_back(1);
  17.   list.push_back(2);
  18.  
  19.   std::list<int>::reverse_iterator back1 = list.rbegin();
  20.   std::list<int>::iterator back2 = reverse_to_normal(back1);
  21.   assert(*back1 == 2);
  22.   assert(*back2 == *back1); /* so far, so good */
  23.  
  24.   /* Let's fill our container a bit more. set and list guarantee that iterators
  25.    * stay valid so there is no harm in continuing to use back1 and back2, right?
  26.    */
  27.   list.push_back(3);
  28.   assert(*back2 == *back1); /* fails. back1 now points to 3, back2 is still ok */
  29.  
  30.   /* Lesson learned: Iterator validity only applies to forward iterators */
  31.   return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement