How to get min or max element in a vector of structures in c++, based on some field in the structure?

前端 未结 5 1674
一整个雨季
一整个雨季 2021-02-05 08:24

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;
}         


        
5条回答
  •  醉酒成梦
    2021-02-05 09:14

    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;
    }
    

提交回复
热议问题