Open In App

upper_bound in C++

Last Updated : 10 Oct, 2025
Comments
Improve
Suggest changes
144 Likes
Like
Report

In C++, the std::upper_bound() is a built-in function used for a sorted container and a given value. It finds the position of the first element that is strictly greater than the specified value. It is defined inside the <algorithm> header file.

  • Works on sorted containers or ranges in ascending order (like sorted arrays, vectors, or deques). Using it on an unsorted range can give incorrect results.
  • Performs binary search internally, giving O(log n) time complexity and O(1) ausxiliary space.
  • Returns an iterator pointing to the first element greater than the key; if no such element exists, it returns the end iterator.
  • For associative containers like set and map, you can use the container’s member upper_bound, which is usually more efficient.
  • Example : Input vector = {5, 15, 25, 35, 45}, key = 28, Output: 35 (First element strictly greater than 28).
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v = {10, 20, 30, 40, 50};

    // Finding upper bound for value 30 in vector v
    cout << *upper_bound(v.begin(), v.end(), 30);

    return 0;
}

Output
40

Syntax of upper_bound()

std::upper_bound (first, last, val, comp);

Parameters

  • first: Iterator to the first element in the range.
  • last: Iterator to the element just past the last element in the range (the usual end() iterator).
  • val: Value to compare against elements in the range.
  • comp (optional): Binary comparison function that returns true if the first argument is less than the second (by default, uses <). If you provide comp, upper_bound finds the first element x such that comp(val, x) is false.

Return Value

  • Returns an iterator to the first element strictly greater than val.
  • Returns the end iterator if all elements are smaller than or equal to val.

Note: The behavior of std::upper_bound() is undefined if the range is not sorted (or not properly partitioned according to the comparison function).

  • std::upper_bound() is useful for efficiently finding elements in sorted ranges using binary search.

More Examples of std::upper_bound()

The std::upper_bound() function is an interesting function that can be used for number of applications. The below examples demonstrate some of its common uses.

Find Upper Bound in an Array

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int arr[5] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Finding upper bound for value 30 in array arr
    cout << *upper_bound(arr, arr + n, 30);

    return 0;
}

Output
40

Time Complexity: O(log n), where n is the number of elements in the array.
Auxiliary Space: O(1).

Use upper_bound() with Custom Comparator

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

bool comp(const string &a, const string &b)
{
    return lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(),
                                   [](char c1, char c2) { return tolower(c1) < tolower(c2); });
}

int main()
{
    vector<string> v = {"Apple", "banana", "Cherry", "date", "Elderberry"};

    // Finding upper bound of "Avocado"
    auto ub = upper_bound(v.begin(), v.end(), "Avocado", comp);

    if (ub != v.end())
        cout << *ub;
    else
        cout << "Upper bound not found!";

    return 0;
}

Output
banana

Time Complexity: O(log n), where n is the number of elements in the vector.
Auxiliary Space: O(1)

Explanation: We need to use the custom comparator function to perform the case insensitive search as the default comparator treats the uppercase and lowercase differently.

Check for an Element in a Sorted Vector

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v = {10, 20, 30, 40, 50};
    int val = 40;

    // Finding the upper bound
    auto it = upper_bound(v.begin(), v.end(), val);

    // Chekcing if val exists or not
    if (it != v.begin() && *(--it) == val)
        cout << val << " is found.";
    else
        cout << val << " is NOT found.";

    return 0;
}

Output
40 is found.

Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)

Explanation: Unlike lower_bound() function, the upper_bound() function never returns the iterator to the matching value if found, it always returns the iterator to the value just after the matching value if it exists. So, to check if the given value exists, we need to decrement the iterator return by the upper_bound() and then compare.

Count Elements Smaller and Larger than a Value

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v = {10, 20, 30, 40, 50};
    int val = 30;

    // Finding the upper bound of val in v
    auto ub = upper_bound(v.begin(), v.end(), val);

    // Finding the number of smaller elements
    cout << "No. of Smaller Elements: " << ub - v.begin() << endl;

    // Finding the number of larger elements
    cout << "No. of Larger Elements: " << v.end() - ub;

    return 0;
}

Output
No. of Smaller Elements: 3
No. of Larger Elements: 2

Explanation: Counts elements based on the position returned by upper_bound().

Finding Upper Bound in a Set

It is recommended to use set::upper_bound() for set as sets do not have random access to its elements. So, the upper_bound() function have to increment it sequentially to find the middle element (part of binary search algorithm) each time leading to increased time complexity.


Upper Bound in C++ STL
Visit Course explore course icon

Explore