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?
This is a discussion on Sorting out vector elements within the C++ Programming forums, part of the General Programming Boards category; Is there any function that selects directly the smallest and the greatest number in a vector or do I have ...
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
I used to be an adventurer like you... then I took an arrow to the knee.
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