VOOZH about

URL: https://www.geeksforgeeks.org/cpp/upper_bound-and-lower_bound-for-vector-in-cpp-stl/

⇱ std::upper_bound and std::lower_bound for Vector in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

std::upper_bound and std::lower_bound for Vector in C++ STL

Last Updated : 15 Nov, 2025

The std::upper_bound() and std::lower_bound() perform binary search on random-access STL containers and are defined in <algorithm>. Here, we focus on their use with vectors in C++ STL.

lower_bound() for Vectors

The std::lower_bound() method can be used to find the first value that is greater than or equal to given value in the vector. It needs the vector to be sorted because it implements binary search to find the value.


Output
30

upper_bound() for Vectors

The std::upper_bound() method can be used to find the first value that is greater than to given value in the vector. It needs sorted vector because it implements binary search to find the value.


Output
40

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

Examples

The below examples demonstrate the use of std::upper_bound and std::lower_bound in a vector in different scenarios

1 Finding the Lower and Upper Bound in a Part of Unsorted Vector


Output
34
56

Time Complexity: O(log n), not considering time required for sorting.
Auxiliary Space: O(1), not considering memory required for sorting.

Explanation: As we know that std::upper_bound() and std::lower_bound() doesn't works for unsorted vector, so we use std::sort() function to sort the vector. After that, we find the lower and upper bound in the desired range.

2 Checking if an Element Exists in Vector using lower_bound()


Output
56 is found.

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

Explanation

  • lower_bound() returns an iterator to the given value if it exists in the vector.
  • If the value is not present, it returns an iterator to the first element greater than the value; upper_bound() cannot be used the same way to check existence.

3 Finding the Number of Elements Smaller and Greater than a Value


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

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

Explanation

  • Lower_bound() returns an iterator to the first element ≥ the given value in a sorted vector.
  • All elements before this iterator are smaller, so subtracting v.begin() from it gives their count.

Difference Between lower_bound() and upper_bound()

  • lower_bound() returns the first element ≥ given value; upper_bound() returns the first element > given value.
  • lower_bound() can be used to check if a value exists; upper_bound() cannot.
  • For duplicates, lower_bound() points to the first occurrence, upper_bound() points just after the last occurrence.
Comment