Search code examples
c++algorithmc++11maxstdvector

How to get the minimum or maximum element in a vector of structures in C++, based on some field in the structure


How can I get the minimum or maximum element in a vector of structures in C++, based on some field in the structure?

For example:

struct Size {
    int width, height;
};
vector<Size> sizes;

And now I want to solve that based on width and create a new vector for that. And then sort based on height and create a new vector for that.


Solution

  • vector<Size> sizes;
    ...
    vector<Size> sortedByWidths(sizes);
    vector<Size> 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;});