Is there a standard function that returns the position (not value) of the maximum element of an array of values?
For example:
Suppose I have an array like this:
sampleArray = [1, 5, 2, 9, 4, 6, 3]
I want a function that returns the integer of 3 that tells me that sampleArray[3]
is the largest value in the array.
To find the largest or smallest element stored in a vector, you can use the methods std::max_element and std::min_element , respectively. These methods are defined in <algorithm> header. If several elements are equivalent to the greatest (smallest) element, the methods return the iterator to the first such element.
The recommended solution is to use the std::max_element to find an element having the maximum value in a map. It returns an iterator pointing to an element with the maximum value in the specified range. It is defined in the <algorithm> header.
Approach: The idea is to traverse the matrix using two nested loops, one for rows and one for columns and find the maximum element. Initialize a variable maxElement with a minimum value and traverse the matrix and compare every time if the current element is greater than a maxElement.
In the STL, std::max_element
provides the iterator (which can be used to get index with std::distance
, if you really want it).
int main(int argc, char** argv) { int A[4] = {0, 2, 3, 1}; const int N = sizeof(A) / sizeof(int); cout << "Index of max element: " << distance(A, max_element(A, A + N)) << endl; return 0; }
Or, written in one line:
std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With