How to find the minimum and maximum element of an Array using STL in C++?
Sometimes we need to find the minimum and maximum element in Array or Vector during solving a question. Well, many people don’t know that there is an inbuilt function in C++ to find the min or the max element and we don’t need to write an extra piece of code for this.
For finding the Minimum element we can use *min_element() function provided in the STL.
For finding the Maximum element we can use *max_element() function provided in the STL.
The syntax is as Follows-
*min_element (first, last);
*max_element (first, last);
In the range, the first element is included but the last element is not. For more clarity [First, last).
Now let us see an Example-
#include <bits/stdc++.h>
using namespace std;
int main()
{
// The array
int arr[] = { 1, 4, 5, 78, 56, 47, 45, 12 };
// Finding the Size of array
int n = sizeof(arr) / sizeof(arr[0]);
// Printing the array
cout << "Our Array is : ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
// Find the minimum element
cout<<endl << "The Min Element = " << *min_element(arr, arr + n);
// Find the maximum element
cout<<endl << "The Max Element = " << *max_element(arr, arr + n);
return 0;
}
OutPut
Array: 1 4 5 78 56 47 45 12
Min Element = 1
Max Element = 78
In the same way we can use it for the Vectors.
In Vectors
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
int k;
for (int i = 0; i < 5; i++)
{
cin >> k;
v.push_back(k);
}
int s = *max_element(v.begin(), v.end());
int t = *min_element(v.begin(), v.end());
cout <<"Max Element is "<<s<<endl;
cout <<"Min Element is "<<t;
return 0;
}
OUTPUT:
12
45
78
23
56
Max Element is 78
Min Element is 12
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.