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

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

    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.

提交回复
热议问题