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:
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , int > mp;
mp.insert({ 12, 30 });
mp.insert({ 11, 10 });
mp.insert({ 15, 50 });
mp.insert({ 14, 40 });
auto it = mp.upper_bound(11);
cout << "The upper bound of key 11 is " ;
cout << (*it).first << " " << (*it).second << endl;
it = mp.upper_bound(13);
cout << "The upper bound of key 13 is " ;
cout << (*it).first << " " << (*it).second << endl;
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jun, 2020
Like Article
Save Article