Open In App

map upper_bound() function in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

The map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container as key and element=0.

Syntax:

map_name.upper_bound(key)

Parameters: This function accepts a single mandatory parameter key which specifies the element whose upper_bound is returned.

Return Value: The function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then returned iterator points to map_name.end(). Note that end() is a special iterator that does not store address of a valid member of a map.

Below is the implementation of the above approach:




// C++ function for illustration
// map::upper_bound() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // initialize container
    map<int, int> mp;
  
    // insert elements in random order
    mp.insert({ 12, 30 });
    mp.insert({ 11, 10 });
    mp.insert({ 15, 50 });
    mp.insert({ 14, 40 });
  
    // when 11 is present
    auto it = mp.upper_bound(11);
    cout << "The upper bound of key 11 is ";
    cout << (*it).first << " " << (*it).second << endl;
  
    // when 13 is not present
    it = mp.upper_bound(13);
    cout << "The upper bound of key 13 is ";
    cout << (*it).first << " " << (*it).second << endl;
  
    // when 17 is exceeds the maximum key, so size
        // of mp is returned as key and value as 0.
    it = mp.upper_bound(17);
    cout << "The upper bound of key 17 is ";
    cout << (*it).first << " " << (*it).second;
    return 0;
}


Output:

The upper bound of key 11 is 12 30
The upper bound of key 13 is 14 40
The upper bound of key 17 is 4 0

Last Updated : 03 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads