Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-10-26 07:10:03
Original
294 people have browsed it

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

Finding Maximum or Minimum Values in Vectors in C

Getting the maximum or minimum value from a vector in C is a common programming task. Let's explore how to achieve this and address a specific error related to the max_element function.

Using max_element

The max_element function from the library returns an iterator pointing to the maximum value in the given range. To use it with a vector, follow these steps:

  1. Create an iterator: vector::const_iterator it;
  2. Find the maximum value: it = max_element(vector.begin(), vector.end());
  3. Access the value: Use *it or it-> to access the maximum value.

Addressing the Error

The error you encountered is caused by trying to use the begin() method on an array. Arrays do not have a begin() or end() method like vectors. To work with arrays, you must use standard C-style indexing.

Example for Vectors

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

int main() {
    std::vector<int> vector = {1, 2, 3, 4, 5};
    int max_value = *std::max_element(vector.begin(), vector.end());
    std::cout << "Maximum value: " << max_value << std::endl;
    return 0;
}
Copy after login

Example for Arrays

<code class="cpp">#include <array>

int main() {
    std::array<int, 5> array = {1, 2, 3, 4, 5};
    int max_value = 0;  // Initialize to minimum possible value
    for (int i = 0; i < array.size(); i++) {
        if (array[i] > max_value) { max_value = array[i]; }
    }
    std::cout << "Maximum value: " << max_value << std::endl;
    return 0;
}</code>
Copy after login

The above is the detailed content of How to Find the Maximum or Minimum Value in 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
Latest Articles by Author
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!