Home »
C++ STL
Find largest and smallest elements in a vector | C++ STL
In this article, we are going to learn how to find the largest and smallest elements in a vector in C++ Standard Template Library (STL)?
Submitted by Vivek Kothari, on November 08, 2018
A lot of problems in programming challenges require finding a largest and smallest among the given elements. in this article we discuss two methods:
Approach 1: Find Largest and Smallest Vector Elements
First, initialize max as first element, then traverse the vector from index 1 to size-1 and for every traversed element, compare it with max, if it is greater than max, then update max is equal to element. For finding smallest element we do same steps i.e initialize min as first element and for every traversed element, compare it with min, if it is smaller than min, then update min.
Example
#include <bits/stdc++.h>
using namespace std;
// for finding maximum
int Findlarge(vector<int> myVector) {
// Initialize maximum element
int max = myVector[0];
// Traverse vector elements
for (int i = 1; i < myVector.size(); i++)
if (myVector[i] > max) max = myVector[i];
return max;
}
// for finding minimum
int FindMin(vector<int> myVector) {
// Initialize minimum element
int min = myVector[0];
// Traverse vector elements
for (int i = 1; i < myVector.size(); i++)
if (myVector[i] < min) min = myVector[i];
return min;
}
// Main function
int main() {
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(100);
myVector.push_back(76);
myVector.push_back(9);
cout << endl << endl << endl << endl;
cout << "elements in Vector = ";
for (int i = 0; i < myVector.size(); i++) {
cout << myVector[i] << " ";
}
cout << endl;
cout << "Largest element given vector is = " << Findlarge(myVector) << endl;
cout << "smallest element given vector is = " << FindMin(myVector) << endl;
return 0;
}
Output
elements in Vector = 1 100 76 9
Largest element given vector is = 100
smallest element given vector is = 1
Approach 2: Find Largest and Smallest Vector Elements
Another method is finding largest and smallest by using library functions std::max_element and std::min_element, respectively. These methods are defined in <algorithm> header. Time complexity of both the methods is linear i.e the ta(n).
Example
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(100);
myVector.push_back(76);
myVector.push_back(9);
cout << "elements in Vector = ";
for (int i = 0; i < myVector.size(); i++) {
cout << myVector[i] << " ";
}
cout << endl;
cout << "Largest element given vector is = ";
cout << *max_element(myVector.begin(), myVector.end()) << endl;
cout << "smallest element given vector is = ";
cout << *min_element(myVector.begin(), myVector.end());
return 0;
}
Output
elements in Vector = 1 100 76 9
Largest element given vector is = 100
smallest element given vector is = 1