C++ Standard Library C++ STL Library

C++ multimap - cbegin() Function



The C++ multimap::cbegin function returns the constant iterator (const_iterator) pointing to the first element of the multimap.

C++ cbegin cend

Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the content it points to, even if the multimap element is not itself constant.

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

Syntax

const_iterator cbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the beginning of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the multimap::cbegin function returns the const_iterator pointing to the first element of the multimap called MyMMap.

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

  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"));

  cit = MyMMap.cbegin();
  cout<<cit->first<<" => "<<cit->second<<"\n";
  cit++;
  cout<<cit->first<<" => "<<cit->second<<"\n";
  cit++;
  cout<<cit->first<<" => "<<cit->second<<"\n";
  return 0;
}

The output of the above code will be:

CAN => Toronto
CAN => Montreal
IND => Delhi

Example:

Lets see another example of multimap where multimap::cbegin function is used with multimap::cend 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>::const_iterator cit;

  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(cit = MyMMap.cbegin(); cit != MyMMap.cend(); ++cit)
    cout<<cit->first<<" => "<<cit->second<<"\n ";

  return 0;
}

The output of the above code will be:

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

❮ C++ <map> Library