如何根据属性从向量中提取最大的对象?
假设我有一堆 Donut
对象,每个甜甜圈都有一个公共整数属性 diameter
。如果我有一个甜甜圈向量,如何提取直径最小或最大的甜甜圈?
Let's say I have a bunch of Donut
objects, and each of these donuts has a public integer attribute diameter
. If I have a vector of donuts, how can I extract the donut with the smallest or largest diameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用
std::min_element
和std::max_element
。例如,给定一个std::vector
:如果您想使用
operator<
(默认使用)以外的其他内容来比较元素,则需要编写自定义比较器:用作:
您还可以使用函数对象(也称为函子)实现比较器,或者如果您的编译器支持 lambda 表达式,则可以使用 lambda:
You use
std::min_element
andstd::max_element
. For example, given astd::vector<int>
:If you want to compare elements using something other than
operator<
(which is used by default), you need to write a custom comparator:Used as:
You can also implement the comparator using a function object (also called a functor) or if your compiler supports lambda expressions you can use a lambda:
您可以使用
std::min_element
:如果您想获得最大的,您可以使用
std::max_element
与相同的比较器。You can use
std::min_element
:If you want to get the largest, you can use
std::max_element
with the same comparator.您可以将 std::max_element/std::min_element 算法与运算符<结合使用使用直径属性或用户提供的比较函数进行比较。
http://www.cplusplus.com/reference/algorithm/max_element/
http://www.cplusplus.com/reference/algorithm/min_element/
You could use the std::max_element/std::min_element algorithm in combination with an operator< that compares using the diameter attribute or an user provided compare function.
http://www.cplusplus.com/reference/algorithm/max_element/
http://www.cplusplus.com/reference/algorithm/min_element/