"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to efficiently find the maximum or minimum value within a C++ vector?

How to efficiently find the maximum or minimum value within a C++ vector?

Published on 2024-11-08
Browse:111

How to efficiently find the maximum or minimum value within a C   vector?

How to Retrieve Maximum or Minimum Values in a Vector in C

In C , finding the maximum or minimum value within a vector is a common task. While arrays and vectors share similarities, obtaining these values differs slightly between the two data structures.

Vectors

To retrieve the maximum or minimum value in a vector, you can use the std::max_element() or std::min_element() functions from the header. These functions take iterators to the beginning and end of the vector as arguments and return an iterator pointing to the element with the maximum or minimum value.

#include 
#include 

int main() {
  std::vector vector = {1, 2, 3, 4, 5};

  // Getting the maximum value
  int max = *std::max_element(vector.begin(), vector.end());
  std::cout ::iterator it_max = std::max_element(vector.begin(), vector.end());
  std::cout 

Arrays

In the case of arrays, you cannot directly use std::max_element() or std::min_element() since they require iterators. Instead, you can use a loop to iterate through the array and find the maximum or minimum value manually.

int main() {
  int array[5] = {1, 2, 3, 4, 5};

  // Getting the maximum value
  int max = array[0];
  for (int i = 1; i  max) {
      max = array[i];
    }
  }
  std::cout 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3