Is there any function that selects directly the smallest and the greatest number in a vector or do I have to write an algorithm for that?
Printable View
Is there any function that selects directly the smallest and the greatest number in a vector or do I have to write an algorithm for that?
Use the min_element and max_element functions.
Output:Code:#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> intVect;
intVect.push_back(18);
intVect.push_back(21);
intVect.push_back(36);
intVect.push_back(14);
intVect.push_back(9);
std::cout << "Min value is: " << *std::min_element(intVect.begin(),intVect.end()) << std::endl;
std::cout << "Max value is: " << *std::max_element(intVect.begin(),intVect.end()) << std::endl;
}
Code:Min value is: 9
Max value is: 36
Or sort the vector and just walk through - better approach if you need the second-smallest etc.
std::sort