Home > Backend Development > C++ > body text

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

DDD
Release: 2024-10-24 18:58:02
Original
989 people have browsed it

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.

<code class="cpp">#include <vector>
#include <algorithm>

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

  // Getting the maximum value
  int max = *std::max_element(vector.begin(), vector.end());
  std::cout << "Maximum: " << max << std::endl;

  // Getting the minimum value
  int min = *std::min_element(vector.begin(), vector.end());
  std::cout << "Minimum: " << min << std::endl;

  // Using iterators
  std::vector<int>::iterator it_max = std::max_element(vector.begin(), vector.end());
  std::cout << "Element with maximum value: " << *it_max << std::endl;
}
Copy after login

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.

<code class="cpp">int main() {
  int array[5] = {1, 2, 3, 4, 5};

  // Getting the maximum value
  int max = array[0];
  for (int i = 1; i < 5; i++) {
    if (array[i] > max) {
      max = array[i];
    }
  }
  std::cout << "Maximum: " << max << std::endl;
}</code>
Copy after login

The above is the detailed content of How to efficiently find the maximum or minimum value within a C vector?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!