Finding the position of the maximum element

C++Algorithm

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

Or, written in one line:

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

Solution 3 - C++

You can use the max_element() function to find the position of the maximum 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;
}

Solution 4 - C++

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.

Solution 5 - C++

cout<<max_element(arr.begin(), arr.end()) - arr.begin();

Solution 6 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFakenView Question on Stackoverflow
Solution 1 - C++StephenView Answer on Stackoverflow
Solution 2 - C++AlexView Answer on Stackoverflow
Solution 3 - C++rashedcsView Answer on Stackoverflow
Solution 4 - C++avakarView Answer on Stackoverflow
Solution 5 - C++GauravView Answer on Stackoverflow
Solution 6 - C++UriView Answer on Stackoverflow