-1

I'm taking a course to learn C++ and as a part of this course, some example code was provided (which works in the instructor's video). However, one part of a program is giving me issue.

And searching SO, I realize I can use a reverse iterator; however, I was hoping someone could explain why the code below throws a runtime error in VS C++, but not in Linux (with g++).

#include <iostream>
#include <vector>
using namespace std;

int main( int argc, char ** argv ) {
        vector<int> vi1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        vector<int>::iterator it;   // vector iterator

        // bidirectional iterator -- iterate forward or backward
        // allows it--
        cout << "bidirectional iterator:" << endl;
    for(auto it = vi1.end() - 1; it >= vi1.begin(); --it) {
                cout << *it << " ";
        }
        cout << endl;

        return 0;
}

Edit:

Added error message

enter image description here

user1543042
  • 3,422
  • 1
  • 17
  • 31

1 Answers1

2

During the last iteration of the loop, it is decremented to be before the start of its container, vi1. This results in an out-of-bounds iterator. The debug build with Visual Studio will detect this and show you the error you get. A release build will not detect this problem.

While it doesn't result in a crash in this instance, decrementing an iterator before the first element can cause crashes or other Undefined Behavior with other container types. Trying to dereference such an iterator is also Undefined Behavior.

rbegin() and rend() are the standard library methods that return reverse iterators.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56