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;
}
You can use std::min_element and std::max_element with a suitable functor:
bool cmp(const Size& lhs, const Size& rhs)
{
return lhs.width < rhs.width;
}
then
auto min_it = std::min_element(sizes.begin(), sizes.end(), cmp);
auto max_it = std::max_element(sizes.begin(), sizes.end(), cmp);
In C++11 you can replace cmp
with a lambda expression.
See also: std::minmax_element