Search code examples
c++vectorstliterator

What is the difference between begin () and rend ()?


I have a question in iterators about the difference between begin() and rend().

#include <iostream>
#include <array>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> v1;
    v1 = {9,2,6,4,5};
    cout<<*v1.begin();
    cout<<*v1.rend();
    return 0;
}

cout<<*v1.begin(); returns 9

but cout<<*v1.rend(); returns a number that is not 9

Why are there such different results?


Solution

  • In C++, ranges are marked by a pair of iterators marking the beginning of the range and a position one past the end of the range. For containers, the begin() and end() member functions provide you with a pair of iterators to the first and past-the-end positions. It’s not safe to read from end(), since it doesn’t point to an actual element.

    Similarly, the rbegin() and rend() member functions return reverse iterators that point, respectively, to the last and just-before-the-first positions. For the same reason that it’s not safe to dereference the end() iterator (it’s past the end of the range), you shouldn’t dereference the rend() iterator, since it doesn’t point to an element within the container.