max_element en C++

Tenemos std::max para encontrar un máximo de 2 o más elementos, pero ¿qué pasa si queremos encontrar el elemento más grande en una array, vector, lista o en una subsección? Para cumplir con este propósito, tenemos std::max_element en C++. std::max_element se define dentro del archivo de encabezado y devuelve un iterador que apunta al elemento con el valor más grande en el rango [primero, último]. std::max_element se puede utilizar de dos formas. Las comparaciones se pueden realizar usando el operador < (primera versión), o usando una función predefinida (segunda versión). Si más de un elemento cumple la condición de ser el más grande, el iterador devuelve puntos al primero de dichos elementos. 

Las dos versiones se definen como se indica a continuación:

  1. Para comparar elementos usando “<“: 

            Sintaxis:

    template 
    ForwardIterator max_element (ForwardIterator first, ForwardIterator last);

    first:     Forward iterator pointing to the beginning of the range.
    last:     Forward iterator pointing to the end of the range.

    Return Value:     It returns a pointer to the largest 
    element in the range, and in case if there are more than 
    one such element, then it points to the first one.

    It points to the last in case the range is empty.

CPP

// C++ program to demonstrate the use of std::max_element
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
 int v[] = { 'a', 'c', 'k', 'd', 'e', 'f', 'h' };
 
 // Finding the maximum value between the first and the
 // fourth element
 
 int* i1;
 i1 = std::max_element(v, v + 4);
 
 cout << char(*i1) << "\n";
 return 0;
}
Producción

k

Complejidad de tiempo: O(n)

Espacio Auxiliar: O(1)

          2 . Para la comparación basada en una función predefinida: 

Sintaxis:

template 
ForwardIterator max_element (ForwardIterator first, ForwardIterator last,
                             Compare comp);
Here, first and last are the same as previous case.
comp: Binary function that accepts two elements 
in the range as arguments, and returns a value convertible to bool.

The value returned indicates whether the element passed as first argument 
is considered less than the second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.

Return Value: It returns a pointer to the largest element 
in the range, and in case if there are more than one such element,
then it points to the first one.
It points to the last in case the range is empty.

CPP

// C++ program to demonstrate the use of std::max_element
#include <iostream>
#include <algorithm>
using namespace std;
 
// Defining the BinaryFunction
bool comp(int a, int b)
{
 return (a < b);
}
 
int main()
{
 int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 };
 
 // Finding the maximum value between the third and the
 // ninth element
 
 int* i1;
 i1 = std::max_element(v + 2, v + 9, comp);
 
 cout << *i1 << "\n";
 return 0;
}

Producción:

12

Complejidad temporal: O(n)

Espacio Auxiliar: O(1)

Artículos relacionados:

Este artículo es una contribución de Mrigendra Singh . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *