"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 Find the Maximum or Minimum Value in a C++ Vector?

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

Published on 2024-12-21
Browse:909

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

#include 
#include 

int main() {
    std::vector vector = {1, 2, 3, 4, 5};
    int max_value = *std::max_element(vector.begin(), vector.end());
    std::cout 

Example for Arrays

#include 

int main() {
    std::array array = {1, 2, 3, 4, 5};
    int max_value = 0;  // Initialize to minimum possible value
    for (int i = 0; i  max_value) { max_value = 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