Crosk Cool
Crosk Cool

Reputation: 734

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

This is the code to print the maximum element in the array with its index. I want to the maximum element with the least index (the first max in case of a tie)

How do i modify the above code to get the result.

Upvotes: 0

Views: 398

Answers (2)

KaranKulshrestha
KaranKulshrestha

Reputation: 318

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;

Upvotes: 0

Leon
Leon

Reputation: 32504

If you need only the max element, why don't you use the std::max_element() function? It will do exactly what you want.

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)

Upvotes: 5

Related Questions