C++ Standard Library C++ STL Library

C++ multimap - lower_bound() Function



The C++ multimap::lower_bound function returns an iterator pointing to the first element in the multimap container whose key is not considered to go before the specified value (it could be either same or goes after the specified value). If all keys of the multimap are considered to go before the specified value, then the iterator points to multimap::end.

Syntax

iterator lower_bound (const key_type& k);
const_iterator lower_bound (const key_type& k) const;
iterator lower_bound (const key_type& k);
const_iterator lower_bound (const key_type& k) const;

Parameters

k Specify key to compare.

Return Value

An iterator pointing to the first element in the multimap container whose key is not considered to go before the specified value, or multimap::end if all elements of the multimap is considered to go before the specified value.

Time Complexity

Logarithmic i.e, Θ(log(n))

Example:

In the example below, the multimap::lower_bound function is used with multimap::upper_bound to specify the lower and upper bound in the multimap called MyMMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  multimap<string, string> MyMMap;
  multimap<string, string>::iterator it, itlower, itupper;

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

  itlower = MyMMap.lower_bound("CAN");
  itupper = MyMMap.upper_bound("JPN");
  MyMMap.erase(itlower, itupper);

  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: 
 USA  New York
 USA  Washington

❮ C++ <map> Library