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
#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
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
#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
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
#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) {