Encontre o valor máximo em array em C++
- Use o método iterativo para encontrar o valor máximo em um array C++
- 
          
            Use o algoritmo std::max_elementpara encontrar o valor máximo em um array C++
- 
          
            Use o algoritmo std::minmax_elementpara encontrar o valor máximo em um array C++
 
Este artigo apresentará como encontrar o valor máximo em um array em C++.
Use o método iterativo para encontrar o valor máximo em um array C++
A maneira direta de implementar uma função customizada para pesquisa de valor máximo é usando o método iterativo. O código de exemplo a seguir tem a estrutura de loop for que percorre cada elemento do array e verifica se o valor atual é maior que o valor máximo atual. Observe que o valor máximo atual é inicializado com o valor do primeiro elemento na matriz e modificado quando a condição if é avaliada como verdadeira.
#include <sys/time.h>
#include <ctime>
#include <iostream>
using std::cout;
using std::endl;
void generateNumbers(int arr[], size_t &width) {
  std::srand(std::time(nullptr));
  for (size_t i = 0; i < width; i++) {
    arr[i] = std::rand();
  }
}
template <typename T>
T FindMax(T *arr, size_t n) {
  int max = arr[0];
  for (size_t j = 0; j < n; ++j) {
    if (arr[j] > max) {
      max = arr[j];
    }
  }
  return max;
}
float time_diff(struct timeval *start, struct timeval *end) {
  return (end->tv_sec - start->tv_sec) + 1e-6 * (end->tv_usec - start->tv_usec);
}
int main() {
  struct timeval start {};
  struct timeval end {};
  size_t width = 100000;
  int *arr = new int[width];
  generateNumbers(arr, width);
  gettimeofday(&start, nullptr);
  cout << "Maximum element is: " << FindMax(arr, width) << endl;
  gettimeofday(&end, nullptr);
  printf("FindMax: %0.8f sec\n", time_diff(&start, &end));
  delete[] arr;
  return EXIT_SUCCESS;
}
Resultado:
Maximum element is: 2147460568
FindMax: 0.00017500 sec
Use o algoritmo std::max_element para encontrar o valor máximo em um array C++
std::max_element é outro método para encontrar o valor máximo em um determinado intervalo. Faz parte dos algoritmos STL e a sobrecarga mais simples leva apenas dois iteradores para denotar as bordas de intervalo a serem pesquisadas. std::max_element retorna um iterador para o elemento de valor máximo. Se vários elementos tiverem o mesmo valor e simultaneamente forem máximos, a função retornará o iterador que aponta para o primeiro.
#include <sys/time.h>
#include <ctime>
#include <iostream>
using std::cout;
using std::endl;
void generateNumbers(int arr[], size_t &width) {
  std::srand(std::time(nullptr));
  for (size_t i = 0; i < width; i++) {
    arr[i] = std::rand();
  }
}
template <typename T>
T FindMax2(T *arr, size_t n) {
  return *std::max_element(arr, arr + n);
}
float time_diff(struct timeval *start, struct timeval *end) {
  return (end->tv_sec - start->tv_sec) + 1e-6 * (end->tv_usec - start->tv_usec);
}
int main() {
  struct timeval start {};
  struct timeval end {};
  size_t width = 100000;
  int *arr = new int[width];
  generateNumbers(arr, width);
  gettimeofday(&start, nullptr);
  cout << "Maximum element is: " << FindMax2(arr, width) << endl;
  gettimeofday(&end, nullptr);
  printf("FindMax2: %0.8f sec\n", time_diff(&start, &end));
  delete[] arr;
  return EXIT_SUCCESS;
}
Resultado:
Maximum element is: 2147413532
FindMax2: 0.00023700 sec
Use o algoritmo std::minmax_element para encontrar o valor máximo em um array C++
Alternativamente, podemos usar o algoritmo std::minmax_element de STL para encontrar os elementos mínimo e máximo em um determinado intervalo e retorná-los como std::pair. A função minmax_element pode opcionalmente assumir a função de comparação binária customizada como o terceiro argumento. Caso contrário, ele tem os mesmos parâmetros que o max_element e se comporta de forma semelhante quando vários elementos mín / máx são encontrados no intervalo.
#include <sys/time.h>
#include <ctime>
#include <iostream>
using std::cout;
using std::endl;
void generateNumbers(int arr[], size_t &width) {
  std::srand(std::time(nullptr));
  for (size_t i = 0; i < width; i++) {
    arr[i] = std::rand();
  }
}
template <typename T>
auto FindMinMax(T *arr, size_t n) {
  return std::minmax_element(arr, arr + n);
}
float time_diff(struct timeval *start, struct timeval *end) {
  return (end->tv_sec - start->tv_sec) + 1e-6 * (end->tv_usec - start->tv_usec);
}
int main() {
  struct timeval start {};
  struct timeval end {};
  size_t width = 100000;
  int *arr = new int[width];
  generateNumbers(arr, width);
  gettimeofday(&start, nullptr);
  auto ret = FindMinMax(arr, width);
  gettimeofday(&end, nullptr);
  cout << "MIN element is: " << *ret.first << " MAX element is: " << *ret.second
       << endl;
  printf("FindMinMax: %0.8f sec\n", time_diff(&start, &end));
  delete[] arr;
  return EXIT_SUCCESS;
}
Resultado:
MIN element is: 3843393 MAX element is: 2147251693
FindMinMax: 0.00000400 sec
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook