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()
?
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.
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).
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).
rbegin() return an iterator with a reverse operator++ ; that is, with a reverse_iterator you can iterate through a container going backward.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With