1

Currently I'm only aware of the following:

vector<int> nums= {3,2,1,0,2,3,3,1,0,0}; 
return max_element(nums.begin(), nums.end())-nums.begin(); 

But in that case it would return the lowest index of the maximum element.

A way around it would be:

vector<int> nums= {3,2,1,0,2,3,3,1,0,0}; 
int n = *max_element(nums.begin(), nums.end());
for(int i=nums.size()-1; i>-1; i--){
    if(nums[i]==n) {
       return i; 
       break; 
    }
}

But is there any simpler way that I can achieve the same result without bruteforcing it?

yokgn
  • 13
  • 3
  • Pull up the documentation on std::vector and review the iterators it provides. The index from iterator calculation (which I overlooked you making at first) will also need to be adjusted when you change the iterators you use. – Avi Berger Aug 22 '22 at 16:23
  • FYI, your `break` statement has no effect. Once the `return` is executed, no other statements in the function are executed (because it returned). – Thomas Matthews Aug 22 '22 at 16:53
  • Sort the array by ascending order. Largest elements will be at the end. The index of the largest element will be the index of the last element. – Thomas Matthews Aug 22 '22 at 16:55

2 Answers2

2

You could iterate backwards by using reverse iterators, and get the distance:

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<int> nums= {3,2,1,0,2,3,3,1,0,0}; 
    auto iter = std::max_element(nums.rbegin(), nums.rend()).base();
    std::cout << std::distance(nums.begin(), std::prev(iter));
}

Output:

6

See what base() does when it comes to reverse iterators.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
1

Whereas std::max_element returns the first largest element, std::minmax_element returns the last one (for the largest).

So you might do:

std::vector<int> nums = {3,2,1,0,2,3,3,1,0,0}; 
return std::distance(nums.begin(),
                     std::minmax_element(nums.begin(), nums.end()).second);
Jarod42
  • 203,559
  • 14
  • 181
  • 302