Home > Software design >  Finding the maximum index of the biggest element of an array/vector
Finding the maximum index of the biggest element of an array/vector

Time:08-24

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?

CodePudding user response:

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.

CodePudding user response:

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);
  • Related