A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/set-upper_bound-function-in-c-stl/ below:

Set upper_bound() in C++ STL

Set upper_bound() in C++ STL

Last Updated : 11 Jul, 2025

In C++, the set upper_bound() is a built-in method used to find the first element in the set that is just greater than the given value. In this article, we will learn about set upper_bound() function in C++.

Let’s take a quick look at a simple illustration of the function:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    set<int> s = {1, 3, 5, 6, 7};

    // Finding  upper bound of 3
    cout << *s.upper_bound(3);
  
    return 0;
}

Explanation: In the above code, we found the upper bound 5 which is just greater than 3 in the given set s.

This article covers the syntax, usage, and common examples of set upper_bound() method in C++:

Syntax of set upper_bound()

The set upper_bound() is the member method of std::set class defined inside <set> header file.

s.upper_bound(k);

Parameters Return Value Examples of upper_bound()

The following examples demonstrate the use of set upper_bound() function in different cases.

Find Upper Bound in Set of Strings C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    set<string> s = {"hello", "geeks",
                     "welcome"};

    // Finding upper bound of string "hello"
    cout << *s.upper_bound("hello");

    return 0;
}
Find Not Existing Upper Bound C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    set<int> s = {1, 5, 3, 7, 6};

    // Finding upper bound of 7 in s
    auto it = s.upper_bound(7);
    if (it != s.end())
        cout << *it;
    else
        cout << "Upper Bound Not Exists.";
    return 0;
}

Output
Upper Bound Not Exists.

Explanation: In the above code, we are trying to find the upper bound of 7 and all the elements are less than or equal to the 7 in the set container. Hence the upper bound of 7 does not exist in the given set container.

Check if an Element Exists in the Set C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    set<int> s = {1, 5, 3, 7, 6};

    // Finding upper bound of 7 in s
    auto it = --s.upper_bound(7);
    if (*it == 7)
        cout << "Exists.";
    else
        cout << "Not Exists.";
    return 0;
}

Explanation: As set is sorted, if the given value exists in the set, the set upper_bound() will return the iterator to the element next to the given element. This iterator can be decremented to point to the given element in the set.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4