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

前端 未结 5 1669
一整个雨季
一整个雨季 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:18

    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

提交回复
热议问题