Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the rbegin and the end function in standard library

Tags:

c++

iterator

stl

I have an implementation of a map where the ID is being stored as value and marks as key. This enables me to take advantage of the auto sorting in maps and lets me identify the ID of the element with highest marks.

for(map<int, int>::iterator i = marks.begin(); i != marks.end(); ++i)
    cout << i->first << "\t" << i->second << endl;
cout << marks.rbegin()->second << endl;
cout << marks.end()->second << endl;

produces this output:

312 3
420 4
512 2
752 1
1
420

The input sequence was the increasing order of values. Why does end() not display "1" but instead displays the key of the last pair inputted? What's the difference between rbegin() and end()?

like image 416
Naman Avatar asked Feb 08 '17 18:02

Naman


People also ask

What is Rbegin?

The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.

What is Rbegin Rend?

rbegin() returns a reverse iterator to the last character of the original input string, and rend() returns a reverse iterator to the character preceding the first character of the original input string (i.e. one past the "end" of the string).

What is rend () in C++?

The rend() function is an inbuilt function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first key-value pair in the map(which is considered its reverse end).

What is used to return a reverse iterator to the end of the container for iterating backward through the container?

rbegin() return an iterator with a reverse operator++ ; that is, with a reverse_iterator you can iterate through a container going backward.


1 Answers

rbegin is actually the last element of your container. end is one past the end of the container.

So marks.end()->second is undefined behavior.

like image 151
Cory Kramer Avatar answered Oct 20 '22 09:10

Cory Kramer