有没有任何效率优势使用minmax_element超过min_element和max_element在一起? [英] Is there any efficiency advantage in using minmax_element over min_element and max_element together?

查看:1177
本文介绍了有没有任何效率优势使用minmax_element超过min_element和max_element在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: minmax_element :返回一个由迭代器组成的对,作为第一个元素的最小元素和作为第二个元素的迭代器。

std::minmax_element : returns a pair consisting of an iterator to the smallest element as the first element and an iterator to the greatest element as the second.

std :: min_element :将迭代器返回范围[first,last]中的最小元素。

std::min_element : returns an iterator to the smallest element in the range [first, last).

std :: max_element :将迭代器返回范围[first,last]中的最大元素。

std::max_element : returns an iterator to the largest element in the range [first, last).

std :: minmax_element / strong>的完整列表来实现呢?

Does std::minmax_element uses sorting of complete list to achieve this?

std :: minmax_element 中处理返回的对的开销是否足够?

Is the overhead of processing returned pair from std::minmax_element worthy enough?

推荐答案

您不必担心 std :: minmax_element 任何排序。它以完全穿过的方式离开范围。更有效率的原因是它可以在单次通过中找到最大值和最小值,其中在分别查找最大值和最小值时,必须执行两次完全遍历。

You do not have to worry about std::minmax_element doing any sorting. It leaves the range in the exact way it was traversed. The reason it is more efficient is it can find both the max and min in a single pass where when looking for max and min separately you have to do two full traversals.

std :: minmax_element 的复杂度为 max(floor(3/2(N-1)),0)其中 std :: max_element std :: min_element 每个都是 max ,0),因此使用 std :: minmax_element

std::minmax_element has the complexity of max(floor(3/2(N−1)), 0) where as std::max_element and std::min_element each are max(N-1,0) so it is about 25% less operations using std::minmax_element

std :: minmax_element 找到最后一个最大的元素,而 std :: max_element 最大。

There is also a difference where std::minmax_element finds the last largest element while std::max_element finds the first largest.

所以如果你需要找到一个范围的最小值和最大值,那么你应该使用 std :: minmax_element 。如果你只需要min或max,那么你应该使用专门的版本。处理从 std :: minmax_element 的返回将更容易与即将到来的C ++ 17标准和结构化绑定。您将能够写

So if you need to find the min and max of a range then you should use std::minmax_element. If you only need the min or max then you should use the specialized version. Dealing with the return from std::minmax_element will get even easier with the upcoming C++17 standard and structured bindings. You will be able to write

auto [min, max] = std::minmax_element(...);

,现在该对的第一个元素存储在 min ,第二个存储在 max

and now the first element of the pair is stored in min and the second is stored in max.

这篇关于有没有任何效率优势使用minmax_element超过min_element和max_element在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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