Home > Backend Development > C++ > body text

How to Find the Maximum or Minimum Value in a C Vector or Array?

DDD
Release: 2024-10-24 19:05:29
Original
953 people have browsed it

How to Find the Maximum or Minimum Value in a C   Vector or Array?

Finding Maximum or Minimum Values in a Vector or Array

Question:

How can the maximum or minimum value be obtained from a vector in C ? Would the same approach work for an array?

Solution:

In C , several methods are available for finding the maximum or minimum value in a vector or array.

Vectors:

To determine the maximum or minimum value within a vector, utilize the max_element() or min_element() functions from the library. These functions accept two iterators representing the beginning and end of the container. They return an iterator pointing to the element with the maximum or minimum value, respectively.

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

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

  // Find the maximum value
  std::vector<int>::iterator max_it = std::max_element(vector.begin(), vector.end());

  // Print the maximum value
  std::cout << "Maximum value: " << *max_it << std::endl;

  return 0;
}
Copy after login

Arrays:

For arrays, you can directly use the loop approach:

<code class="cpp">int array[] = {1, 3, 5, 2, 4};
int max_value = array[0];
for (int i = 1; i < sizeof(array) / sizeof(array[0]); i++) {
  if (array[i] > max_value) {
    max_value = array[i];
  }
}</code>
Copy after login

The above is the detailed content of How to Find the Maximum or Minimum Value in a C Vector or Array?. 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!