在平局的情况下如何使 minmax_element 到 return 具有最小索引的元素

How to make minmax_element to return the element with least index in case of a tie

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

这是打印数组中最大元素及其索引的代码。 我想要索引最少的最大元素(在平局的情况下是第一个最大值)

如何修改上面的代码得到结果。

如果只需要最大元素,为什么不使用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)
vector<int> v = {1, 4, 2, 2, 3};
auto r = minmax_element(v.begin(), v.end());
cout << r.first - v.begin() << " " << r.second - v.begin() << endl;