1

I find a very strange output in C++ when I try to use vector's reverse_iterator to do a traverse. My code is simple and like this:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    vector<int>::reverse_iterator it = v.rbegin();
    cout << *it++ << " " << *it++;
    return 0;
}

The output is 2 3. I can't figure out what happened in it. Can anyone help me out?

Liberty
  • 35
  • 8

1 Answers1

6

I don't know how long you've been doing C++, but again, Welcome to C++ :-) ...

You have just entered the world of Undefined Behaviors and sequence points

You should break your code down into:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    vector<int>::reverse_iterator it = v.rbegin();
    cout << *it;
    it++; 
    cout << " " << *it;
    return 0;
}

It works now... :-)

Let me explain give you a brief overview of what is happening in your original code...

This line

cout << *it++ << " " << *it++;

Whether the first it will be incremented before the second is unspecified.

Remember, post-increment operator returns a copy of the iterator and increments the original iterator. You had it twice in the same statement, So, what you were most likely having was that it was incremented twice before the latest copy was dereferenced first, then the former copy dereferenced second

Also see the beautiful answers to this Stackoverflow question Undefined behavior and sequence points

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68