Javatpoint Logo
Javatpoint Logo

C++ Algorithm max_element()

C++ Algorithm max_element() returns an iterator pointing to the element with the largest value in the range [first, last). If several elements fulfill this condition, the returned iterator points to the first of such elements.

Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version.

Syntax

Parameter

first: An input iterator pointing the position to the first element in the range to be searched for the largest element.

last: An input iterator pointing the position to the past last element in the range to be searched for the largest element.

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

Return value

It returns the larger value in the range [first, last) or last if the range is empty.

Complexity

Complexity is linear in one less than the number of elements compared.

Data Races

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

Exceptions

This function throws an exception if any comparison throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to find the position of maximum element in the range:

Output:

max element at position: 5

Example 2

Let's see another simple example to find the largest element in the range using default version:

Output:

Maximum value is: k

Example 3

Let's see another simple example to find the largest element in the range using comparison function:

Output:

Maximum element is: 12

Example 4

Let's see another simple example:

Output:

max_element() without predicate 
Vector : 10 20 30 50 40 100 70 60 80 90 
Maximum element = 100

max_element() with predicate
Name	Marks
Amita	99
Divya	80
Kashish 90
Nikita	60
Person with maximum marks = Amita, Marks = 99

Next TopicC++ Algorithm





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA