# C++ Algorithm upper_bound()

C++ Algorithm upper_bound() function is the version of binary search. This function is used to return an iterator pointing to the first element in the range [first, last) that is greater than to the specified value val.

The first version uses operator < to compare the elements and the second version uses the given comparison function i.e. comp.

## Parameter

first: A forward iterator pointing to the first element in the range to be searched.

last: A forward iterator pointing to the past last element in the range to be searched.

comp: A user defined binary predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise. It follows the strict weak ordering to order the elements.

val: A value of the upper bound to compare the elements in the range.

## Return value

It returns an iterator pointing to the first element of the range that is greater than val or last if no such element is found.

## Complexity

On average, complexity is logarithmic in the distance between first and last: performs up to log2 (N) + 1 element comparisons Where N = last - first.

## Data races

The object in the range [first, last) are accessed.

## Exceptions

This function throws an exception if either an element comparison or an operation on iterator throws an exception.

## Example 1

Let's see the simple example to demonstrate the use of upper_bound():

Output:

```Upper bound of 3 is: 4
```

## Example 2

Let's see another simple example:

Output:

```lower_bound at position 3
upper_bound at position 6
```

## Example 3

Let's see another simple example:

Output:

```Here are the contents of v:
2 3 5 6 7 7 7 8 9 10
Upper bound of 3 in v = 5
Upper bound of 4 in v = 5
Upper bound of 5 in v = 6
Upper bound of 7 in v = 8
Upper bound of 0 in v = 2

Note that the upper bound location of 15 is
the end (one-past-the-last) vector position.
```

## Example 4

Let's see another simple example:

Output:

```Upper bound of 'C' is d
Upper bound of 'C' is C
All elements are less than 'z'.
```

Next TopicC++ Algorithm

### Feedback   