C++ Standard Library C++ STL Library

C++ multimap - rbegin() Function



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

C++ rbegin rend

Note: Multimap 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 multimap::rbegin function returns the reverse iterator pointing to the last element of the multimap MyMMap.

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

  MyMMap.insert(pair<string, string>("USA", "New York"));
  MyMMap.insert(pair<string, string>("USA", "Washington"));  
  MyMMap.insert(pair<string, string>("CAN", "Toronto"));
  MyMMap.insert(pair<string, string>("CAN", "Montreal"));
  MyMMap.insert(pair<string, string>("IND", "Delhi"));

  rit = MyMMap.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:

USA => Washington
USA => New York
IND => Delhi

Example:

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

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

  MyMMap.insert(pair<string, string>("USA", "New York"));
  MyMMap.insert(pair<string, string>("USA", "Washington"));  
  MyMMap.insert(pair<string, string>("CAN", "Toronto"));
  MyMMap.insert(pair<string, string>("CAN", "Montreal"));
  MyMMap.insert(pair<string, string>("IND", "Delhi"));

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

  return 0;
}

The output of the above code will be:

MyMMap contains:
 USA => Washington
 USA => New York
 IND => Delhi
 CAN => Montreal
 CAN => Toronto

❮ C++ <map> Library