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?
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
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Or sort the vector and just walk through - better approach if you need the second-smallest etc.
std::sort
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law