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

后端 未结 3 1894
臣服心动
臣服心动 2021-01-03 05:51

(This is a related question, but there are difference with my case that makes me doubt my understanding of it).

I have this class:

class MyOwnClass
{         


        
3条回答
  •  一整个雨季
    2021-01-03 06:35

    Try the following

    std::vector MySuperVector(20);
    
    //..filling the vector
    
    auto max = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                                 []( const MyOwnClass &a, const MyOwnClass &b )
                                 {
                                     return a.score < b.score;
                                 } ); 
    

    If you need to find the minimum and maximum element simultaneously then you can use standard algorithm std::minmax_element. It returns a pair of iterators the first of which points to the first minimum element and the second points to the last maximum element. Otherwise you need to call std::max_element and std::min_element separatly. if you need to get the first minimum and the first maximum or the last minimum and the last maximum

    The other approach is to define internal functional objects for each field that can be used for finding maximum or minimum. For example

    class MyOwnClass
    { 
    public:
        int score; Specialcustomtype val1; double index;
    
        struct ByScore
        {
            bool operator ()( const MyOwnClass &a, const MyOwnClass &b ) const
            { 
                return a.score < b.score;
            }
        };
    
        struct ByIndex
        {
            bool operator ()( const MyOwnClass &a, const MyOwnClass &b ) const
            { 
                return a.index < b.index;
            }
        };
    private:
    
    };
    
    //...
    
    auto max_score = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                                       MyOwnClass::ByScore() ); 
    
    auto max_index = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                                       MyOwnClass::ByIndex() ); 
    

提交回复
热议问题