VOOZH about

URL: https://www.geeksforgeeks.org/cpp/upper_bound-in-cpp/

⇱ upper_bound in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

upper_bound in C++

Last Updated : 19 Jan, 2026

upper_bound is a Standard Template Library (STL) function used to find the first element that is strictly greater than a given value in a sorted range. It is commonly used for efficient searching and range queries in sorted containers.

Example: Basic Usage with Vector


Output
40

Explanation:

  • The vector is already sorted
  • upper_bound(30) skips 10, 20, 30
  • Returns iterator pointing to 40
  • Dereferencing the iterator prints 40

Syntax

iterator upper_bound(iterator first, iterator last, const T& value);

Parameters

  • first: Iterator to the first element of the range
  • last: Iterator to one past the last element of the range
  • value: The value to compare against
  • comp (optional): Custom comparison function

Return Value

  • Returns an iterator to the first element greater than value
  • Returns last if no such element exists

Note: The behavior of std::upper_bound() is undefined if the range is not sorted

The below examples demonstrate some of its common uses.

Example 1: Find Upper Bound in an Array


Output
40

Explanation: This code uses upper_bound() to find and print the first element in the sorted array that is strictly greater than 30, which is 40.

Example 2: Use upper_bound() with Custom Comparator


Output
banana

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.

Example 3: Check for an Element in a Sorted Vector


Output
40 is found.

Explanation: upper_bound() returns the iterator just after the matching value; to check if the value exists, decrement the iterator and compare.

Example 4: Count Elements Smaller and Larger than a Value


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.


Output
set::upper_bound -> 6
std::upper_bound -> 6

Explanation:

  • set::upper_bound() uses the Red-Black Tree structure of set, giving O(log n) time complexity.
  • std::upper_bound() cannot perform binary search efficiently on set because it lacks random-access iterators, resulting in O(n) traversal.
  • Both return the same value, but performance differs significantly.


Comment