Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the position of the maximum element

Tags:

c++

algorithm

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.

like image 367
Faken Avatar asked Jun 01 '10 21:06

Faken


People also ask

How do you find the position of the maximum element in a vector?

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.

How do you find the maximum element on a map?

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.

How do you find the maximum element of a matrix?

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.


2 Answers

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; } 
like image 125
Stephen Avatar answered Oct 12 '22 00:10

Stephen


Or, written in one line:

std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end())); 
like image 40
Alex Avatar answered Oct 11 '22 22:10

Alex