How to find index of maximum and minimum element in vector in C++

In this tutorial, we are going to find the index of maximum and minimum elements in vector in C++.

In vectors, the size grows dynamically. Thus one can change the size dynamically as per requirement.  They are part of the STL library of C++.  For using vectors we need to use vector header file.

C++ Code: Index of maximum and minimum element in vector

Read the comments in the code for better understanding.

#include <iostream>
#include <vector>
#include <algorithm>
 
int main()
{
    std::vector<int> v = {2, 1, 3, 6, 7, 9, 8};
 
    auto it = std::minmax_element(v.begin(), v.end());
    int min_idx = std::distance(v.begin(), it.first);
    int max_idx = std::distance(v.begin(), it.second);
 
    std::cout << min_idx << ", " << max_idx << std::endl; // 1, 5
 
    return 0;
}

Output:

1, 5

Working algorithm:

First we will put header file <vector> in the code. Then we will insert a vector of considerable length. Then we will use auto iterator for minimum and maximum element identification with v begin and v end function.

For min index we will use std distance with v begin function and the iterator will start checking the first value. and for max index we will start checking with the second element. So the iterators will check the whole vector for max and min element and their return its index.

Output will be in (min_idex, max_index). So here 1 represents the minimum element index and 5 represents the maximum element index .

Leave a Reply

Your email address will not be published.