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;
}
Solution using std::minmax_element with lambda expression:
#include
#include
struct Size {
int width, height;
};
int main()
{
std::vector sizes;
sizes.push_back({4,1});
sizes.push_back({2,3});
sizes.push_back({1,2});
auto minmax_widths = std::minmax_element(sizes.begin(), sizes.end(),
[] (Size const& lhs, Size const& rhs) {return lhs.width < rhs.width;});
auto minmax_heights = std::minmax_element(sizes.begin(), sizes.end(),
[] (Size const& lhs, Size const& rhs) {return lhs.height < rhs.height;});
std::cout << "Minimum (based on width): " << minmax_widths.first->width << std::endl;
std::cout << "Maximum (based on width): " << minmax_widths.second->width << std::endl;
std::cout << "Minimum (based on height): " << minmax_heights.first->height << std::endl;
std::cout << "Maximum (based on height): " << minmax_heights.second->height << std::endl;
}