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
#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
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