C++ Standard Library C++ STL Library

C++ map - rbegin() Function



The C++ map::rbegin function returns the reverse iterator pointing to the last element of the map. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the map container. Similarly, decreasing a reverse iterator results into moving to the end of the map container.

C++ rbegin rend

Note: Map is an ordered data container which implies all its elements are ordered all the time.

Syntax

reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A reverse iterator to the reverse beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_reverse_iterator, else returns an reverse_iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the map::rbegin function returns the reverse iterator pointing to the last element of the map MyMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;
  map<int, string>::reverse_iterator rit;

  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";
  MyMap[104] = "Jo";
  MyMap[105] = "Ramesh";

  rit = MyMap.rbegin();
  cout<<rit->first<<" "<<rit->second<<"\n";
  rit++;
  cout<<rit->first<<" "<<rit->second<<"\n";
  rit++;
  cout<<rit->first<<" "<<rit->second<<"\n";
  return 0;
}

The output of the above code will be:

105 Ramesh
104 Jo
103 Kim

Example:

Lets see another example of map where map::rbegin function is used with map::rend function to specify a range including all elements of the map container.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<string, int> MyMap;
  map<string, int>::reverse_iterator rit;

  MyMap["John"] = 2500;
  MyMap["Jack"] = 2600;
  MyMap["Ella"] = 2000;
  MyMap["Nora"] = 3000;
  MyMap["Adam"] = 3100;

  cout<<"MyMap contains: \n ";
  for(rit = MyMap.rbegin(); rit != MyMap.rend(); ++rit)
    cout<<rit->first<<"  "<<rit->second<<"\n ";

  return 0;
}

The output of the above code will be:

MyMap contains: 
 Nora  3000
 John  2500
 Jack  2600
 Ella  2000
 Adam  3100

❮ C++ <map> Library

5