map upper_bound() function in C++ STL
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 the iterator returned points to the number of elements in the map container as key and element=0.
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; } |
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
Recommended Posts:
- Function Overloading vs Function Overriding in C++
- What happens when a virtual function is called inside a non-virtual function in C++
- div() function in C++
- exp() function C++
- log() function in C++
- fma() function in C++
- scalbn() function in C++
- wmemmove() function in c++
- c16rtomb() function in C/C++
- c32rtomb() function in C/C++
- wcsstr() function in C++ with example
- mbrtowc() function in C/C++
- wcsrchr() function in C/C++
- wcspbrk() function in C/C++
- difftime() function in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



