tags:

views:

85

answers:

3

Is there a standard function that returns the position(not value) of the max element of an array of values?

For example:

say 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.

+2  A: 

std::max_element takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.

avakar
+6  A: 

In the STL, max_element provides the iterator (which can be used to get index with 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;
}
Stephen
So this function returns a pointer to the position of the max element? How do i get the position on the array of the max element?
Faken
@Faken: Edited to show.
Stephen
+2  A: 

STL has a max_elements function. Here is an example: http://www.cplusplus.com/reference/algorithm/max_element/

Uri