set upper_bound() function in C++ STL

• Difficulty Level : Easy
• Last Updated : 23 Jan, 2020

The set::upper_bound() is a built-in function in C++ STL which 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 next of last element (which can be identified using set end() function) in the set container.

Syntax:

set_name.upper_bound(key)

Parameters: This function accepts a single mandatory parameter key which specifies the element whose upper bound is to be 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 points to std::end() which points to the element next to the last element of the set.

Example 1: Below program illustrate the above function:

 // CPP program to demonstrate the// set::upper_bound() function#include using namespace std;int main(){    set s;      // Function to insert elements    // in the set container    s.insert(1);    s.insert(4);    s.insert(2);    s.insert(5);    s.insert(6);      cout << "The set elements are: ";    for (auto it = s.begin(); it != s.end(); it++)        cout << *it << " ";      // when 2 is present    // points to next element after 2    auto it = s.upper_bound(2);    cout << "\nThe upper bound of key 2 is ";    cout << (*it) << endl;      // when 3 is not present    // points to next greater after 3    it = s.upper_bound(3);    cout << "The upper bound of key 3 is ";    cout << (*it) << endl;      return 0;}
Output:
The set elements are: 1 2 4 5 6
The upper bound of key 2 is 4
The upper bound of key 3 is 4

Example 2: Below is a better code that also checks if the given element is greater than or equal to the greatest.

 // CPP program to demonstrate the// set::upper_bound() function#include using namespace std;int main(){    set s;      // Function to insert elements    // in the set container    s.insert(1);    s.insert(4);    s.insert(2);    s.insert(5);    s.insert(6);      int key = 8;    auto it = s.upper_bound(key);    if (it == s.end())        cout << "The given key is greater "                "than or equal to the largest element \n";    else        cout << "The immediate greater element "             << "is " << *it << endl;      key = 3;    it = s.upper_bound(key);    if (it == s.end())        cout << "The given key is greater "                "than or equal to the largest element \n";    else        cout << "The immediate greater element "             << "is " << *it << endl;      return 0;}
Output:
The given key is greater than or equal to the largest element
The immediate greater element is 4

My Personal Notes arrow_drop_up