第二大元素的 std::max_element ? [英] std::max_element for second largest element?

查看:33
本文介绍了第二大元素的 std::max_element ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

STL 提供了 std::max_element 来查找可迭代对象中的最大元素,例如像这样:

The STL provides std::max_element to find the largest element in an iterable, e.g. like this:

std::vector<float>::const_iterator max = 
  std::max_element(obj.pt()->begin(), obj.pt()->end());
return std::distance(obj.pt()->begin(), max);

还有什么东西可以获得第 n 个最大元素的迭代器吗?

Is there also something to get an iterator for the n-th largest element?

(请注意,max_element 返回一个迭代器,这实际上很重要:我正在寻找可迭代对象中第 n 个最大元素的位置,而不是值本身.)

(Note that max_element returns an iterator and this is actually important: Rather than for the value itself, I am looking for the position of the n-th largest element within the iterable.)

推荐答案

max_element() 方法可用于通过传递 lambda 函数来获取第二大元素,该函数将元素与先前找到的最大元素进行比较,如果它等于最大的元素,然后它会简单地跳过该元素.

max_element() method can be used to get second largest element by passing lambda function which compares the element with the previously found largest element and if it is equal to the largest element then it'll simply skip that element.

auto largest = max_element(vec.begin(), vec.end());
auto secondLargest = max_element(vec.begin(), vec.end(),
                                 [&largest](unsigned long &a, unsigned long &b) {
                                     return ((b != (*largest)) && (a < b));
                                 });

这篇关于第二大元素的 std::max_element ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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