Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Quốc Cường Avatar asked Dec 18 '25 06:12

Quốc Cường


1 Answers

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.

like image 157
templatetypedef Avatar answered Dec 20 '25 21:12

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!