×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

How to find the maximum/largest element of a vector in C++ STL?

C++ STL | finding maximum/largest element of a vector: Here, we are going to learn how to find maximum/largest element of a vector?
Submitted by IncludeHelp, on May 18, 2019

Given a vector and we have to maximum/largest element using C++ STL program.

Finding largest element of a vector

To find a largest or maximum element of a vector, we can use *max_element() function which is defined in <algorithm> header. It accepts a range of iterators from which we have to find the maximum / largest element and returns the iterator pointing the maximum element between the given range.

Note: To use vector – include <vector> header, and to use *max_element() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.

Syntax

*max_element(iterator start, iterator end);

Here, iterator start, iterator end are the iterator positions in the vector between them we have to find the maximum value.

Example

Input:
vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };

cout << *max_element(v1.begin(), v1.end()) << endl;

Output:
50

C++ STL program to find maximum or largest element of a vector

//C++ STL program to find maximum or largest 
//element of a vector 
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //vector
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "vector elements..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //finding the maximum element
    int max = *max_element(v1.begin(), v1.end());

    cout << "maximum/largest element is: " << max << endl;

    return 0;
}

Output

vector elements...
10 20 30 40 50
maximum/largest element is: 50

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.