upper_bound() in C++ STL

The C++ Standard Library consists of the header, `<algorithm>` which defines a collection of functions (principally designed to deal with a range of elements). `upper_bound()` is a method in the STL that returns an iterator pointing to the first element in the range which compares greater than a certain value. The method returns the last iterator if no element compares greater than the value.

Syntax:

`upper_bound( iterator_begin, iterator_end, val );`

Parameters: The `upper_bound() `method accepts 3 parameters

• iterator_begin: Iterator to the initial position
• iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
• val: Value of the upper bound to search for in the range

Return value: An iterator to the upper bound of val in the range. iterator_end if no elements compare more than val

Example of upper_bound() method

```#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(5);
v.push_back(5);
v.push_back(5);
v.push_back(5);
v.push_back(6);

vector<int>::iterator it = upper_bound(v.begin(), v.end(), 5);
cout<<"Upper bound of element 5 is: "<< distance(v.begin(), it) << endl;
}```

Output:

`Upper bound of element 5 is: 6`

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Scroll to Top

Full Stack Integrated Bootcamp Free Trial

• Please enter a number from 7000000000 to 9999999999.