Find max and min Element and Respective Index in a Vector
suggest changeTo find the largest or smallest element stored in a vector, you can use std::max_element and std::min_element, respectively. These functions are defined in the <algorithm> header. If several elements are equivalent to the greatest (smallest) element, they return the iterator to the first such element. They return v.end() for an empty vector, and dereferencing that iterator is undefined behavior.
std::vector<int> v = {5, 2, 8, 10, 9};
int maxElementIndex = std::max_element(v.begin(),v.end()) - v.begin();
int maxElement = *std::max_element(v.begin(), v.end());
int minElementIndex = std::min_element(v.begin(),v.end()) - v.begin();
int minElement = *std::min_element(v.begin(), v.end());
std::cout << "maxElementIndex:" << maxElementIndex << ", maxElement:" << maxElement << '\n';
std::cout << "minElementIndex:" << minElementIndex << ", minElement:" << minElement << '\n';
Output:
maxElementIndex:3, maxElement:10
minElementIndex:1, minElement:2
The minimum and maximum element in a vector can be retrieved at the same time by using std::minmax_element, which is also defined in the <algorithm> header. If several elements are equivalent, the iterator for the maximum is the last maximum, not the first:
std::vector<int> v = {5, 2, 8, 10, 9};
auto minmax = std::minmax_element(v.begin(), v.end());
std::cout << "minimum element: " << *minmax.first << '\n';
std::cout << "maximum element: " << *minmax.second << '\n';
Output:
minimum element: 2
maximum element: 10