如果出现平局,如何使minmax_element返回索引最少的元素

Cro*_*ool 0 c++ std stl-algorithm c++14

#include<utility>
#include<alogrithm>
#include<iostream>
using namespace std;
int main(void)
{
  int n=5;
  int s[]={3,5,1,5,5};
  auto r=minmax_element(s,s+n);
  cout<<r.second-s<<endl;
  cout<<*r.second;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是使用索引打印数组中最大元素的代码.我想要索引最小的最大元素(如果是平局,则为第一个最大值)

如何修改上面的代码以获得结果.

Leo*_*eon 5

如果只需要max元素,为什么不使用该std::max_element()函数?它会完全按照你的意愿行事.

auto r = std::max_element(s, s+n);
cout << r-s << endl; // index of the maximum element in [s, s+n)
cout << *r  << endl; // value of the maximum element in [s, s+n)
Run Code Online (Sandbox Code Playgroud)