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

后端 未结 3 1899
臣服心动
臣服心动 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:50

    That your elements are of different types it doesn't matter, you can always compare the field you're interested in:

    std::vector MySuperVector(20);
    
    // A pred function to adjust according to your score
    bool comparator(const MyOwnClass& s1, const MyOwnClass& s2) {
        return s1.score < s2.score;
    }
    
    int main() {
        MySuperVector[0].score = 23; // This will be returned
        MySuperVector[1].score = 2;
        MySuperVector[5].score = -22;
    
        auto element = std::max_element(MySuperVector.begin(), 
                                        MySuperVector.end(), comparator);
    
        std::cout << element->score; // 23
    }
    

    Example

    Notice that you don't even need the minmax_element function since you're just asking for the greatest element (max_element is a better fit).

    If the runtime efficiency to find your greatest value matters, you might want to take a look at priority_queues (heap adaptors).

提交回复
热议问题