C++ Standard Library C++ STL Library

C++ multimap - begin() Function



The C++ multimap::begin function returns the iterator pointing to the first element of the multimap. Please note that, Multimap is an ordered data container which implies all its elements are ordered all the time.

C++ begin end

Syntax

iterator begin();
const_iterator begin() const;
iterator begin() noexcept;
const_iterator begin() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to the beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_iterator, else returns an iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the multimap::begin function returns the 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>::iterator it;

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

  it = MyMMap.begin();
  cout<<it->first<<" => "<<it->second<<"\n";
  it++;
  cout<<it->first<<" => "<<it->second<<"\n";
  it++;
  cout<<it->first<<" => "<<it->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::begin function is used with multimap::end 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>::iterator it;

  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(it = MyMMap.begin(); it != MyMMap.end(); ++it)
     cout<<it->first<<" => "<<it->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