[c++] Finding the position of the max element

Is there a standard function that returns the position(not value) of the max 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.

This question is related to c++ algorithm

The answer is


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


Or, written in one line:

std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));

You can use max_element() function to find the position of the max element.

int main()
{
    int num, arr[10];
    int x, y, a, b;

    cin >> num;

    for (int i = 0; i < num; i++)
    {
        cin >> arr[i];
    }

    cout << "Max element Index: " << max_element(arr, arr + num) - arr;

    return 0;
}

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.