如何在c ++中的结构向量中获取min或max元素,基于结构中的某些字段? [英] How to get min or max element in a vector of structures in c++, based on some field in the structure?

查看:145
本文介绍了如何在c ++中的结构向量中获取min或max元素,基于结构中的某些字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据结构中的某些字段在c ++中的结构向量中获取min或max元素?



例如:

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

现在我想根据宽度解决这个问题,并为此创建一个新的向量,$ b $

解决方案 / div>

 矢量< Size>尺寸; 
...
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;


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;
};
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.

Thanks

解决方案

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;});

这篇关于如何在c ++中的结构向量中获取min或max元素,基于结构中的某些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆