C++ – Finding the position of the maximum element

algorithmc

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.

Best Answer

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;
}