C++ Standard Library C++ STL Library

C++ map - upper_bound() Function



The C++ map::upper_bound function returns an iterator pointing to the first element in the map container whose key is considered to go after the specified value. If all keys of the map are considered to go before the specified value, then the iterator points to map::end.

Syntax

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

Parameters

k Specify key to compare.

Return Value

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

Time Complexity

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

Example:

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

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

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

  itlower = MyMap.lower_bound(102);
  itupper = MyMap.upper_bound(104);
  MyMap.erase(itlower, itupper);

  cout<<"MyMap contains: \n ";
  for(it = MyMap.begin(); it != MyMap.end(); ++it)
     cout<<it->first<<"  "<<it->second<<"\n ";
  return 0;
}

The output of the above code will be:

MyMap contains: 
 101  John
 105  Ramesh

❮ C++ <map> Library