How to get min or max element in a vector of structures in c++, based on some field in the structure?
For example:
struct Size {
int width, height;
}
In C++11, you can use the std::minmax_element() standard function, which (given a pair of iterators) and possibly a custom comparator (that would allow you to define the field on which the ordering is based), will return you an iterator to the minimum and an iterator to the maximum element, packed in an std::pair
.
So for instance:
#include // For std::minmax_element
#include // For std::tie
#include // For std::vector
#include // For global begin() and end()
std::vector sizes = { {4, 1}, {2, 3}, {1, 2} };
decltype(sizes)::iterator minEl, maxEl;
std::tie(minEl, maxEl) = std::minmax_element(begin(sizes), end(sizes),
[] (Size const& s1, Size const& s2)
{
return s1.width < s2.width;
});
Here is a live example.