I learned something interesting today
So it's time to learn something even more interesting: your code has Undefined Behavior, because the precondition for using the subscript operator is that the index is smaller than the size of the vector.
Per Table 101 of the C++11 Standard, the expression a[n]
is equivalent to *(a.begin() + n)
. Since v.begin() + 2
is an iterator to a position beyond the end of the container v
, dereferencing it results in Undefined Behavior.