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

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

    vector sizes;
    ...
    vector sortedByWidths(sizes);
    vector sortedByHeights(sizes);
    sort(sortedByWidths.begin(), sortedByWidths.end(), 
        [](Size s1, Size s2) {return s1.width < s2.width;});
    sort(sortedByHeights.begin(), sortedByHeights.end(), 
        [](Size s1, Size s2) {return s1.height< s2.height;});
    

提交回复
热议问题