×

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.

Minimum and maximum elements of a vector in C++ STL

C++ STL | finding minimum and maximum elements of a vector: Here, we are going to learn how we can find the minimum and maximum elements of a given vector?
Submitted by IncludeHelp, on May 17, 2019

Given a vector and we have to find the smallest (minimum) and largest (maximum) elements.

Finding vector's minimum & maximum elements

To find minimum element of a vector, we use *min_element() function and to find the maximum element, we use *max_element() function.

Syntax:

*max_element(iterator start, iterator end);
*min_element(iterator start, iterator end);

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

These functions are defined in <algorithm> header or we can use <bits/stdc++.h> header file.

Example:

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

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

Output:
10
50

C++ STL program to find minimum and maximum elements of a vector

//C++ STL program to append a vector to a vector
#include <bits/stdc++.h>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };
    int min = 0;
    int max = 0;

    //finding minimum  & maximum element
    min = *min_element(v1.begin(), v1.end());
    max = *max_element(v1.begin(), v1.end());

    cout << "minimum element of the vector: " << min << endl;
    cout << "maximum element of the vector: " << max << endl;

    return 0;
}

Output

minimum element of the vector: 10
maximum element of the vector: 50

Related Tutorials

Comments and Discussions!

Load comments ↻





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