Find the maximum element of a Vector using STL in C++

In this tutorial, we will be learning about how to find the maximum element of a vector using STL (Standard Template Library) in C++.

Basically, we just traverse the whole vector and check the greater element among them. But, traversing the whole vector takes a high amount of time. So, here we are reducing that by using an STL function.

Before moving into finding the maximum element of a vector. If you are a beginner, please go through the sample vector program of STL. So, that you will be comfortable with STL.

Take user input into vector in C++

Description

By using the *max_element() method from STL(Standard template library), we will be getting the maximum element of the vector.

Header Files

We, generally require 3 Header files over here which are…

<iostream>(Standard input output stream)

<vector>(for declaring vector)

<algorithm>(in order to use *max_element() function)

Syntax

*max_element(start_index,end_index)

Here…

  • *max_element represents the name of a function.
  • start_index represents the starting index of the vector.
  • end_index represents the ending index of the vector.

Time Complexity

O(n)

Space Complexity

O(1)

The Auxiliary space is being considered.

Code

The Sample code is as follows…

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cout<<"Enter the size of a vector\n";
    cin>>n;
    vector<int>v;
    cout<<"Enter the elements of the vector\n";
    for(int i=0;i<n;i++)
    {
        int a;
        cin>>a;
        v.push_back(a);
    }
    cout<<"Maximum element is : "<<*max_element(v.begin(),v.end());
    return 0;
}

Output :

Enter the size of a vector
5
Enter the elements of the vector
1 3 6 8 3
Maximum element of the vector is : 8

Explanation

Here, firstly user enters the size of a vector. then the user enters the elements of the vector. then, by using the *max_element() function it finds out the maximum element of the vector.

*max_element(v.begin(),v.end())

  • v.begin() represents the starting index of the vector v.
  • v.end() represents the ending index of the vector v.

 

Leave a Reply

Your email address will not be published.