为什么std :: max_element需要ForwardIterator? [英] Why does std::max_element require a ForwardIterator?

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

问题描述

C ++标准库的 max_element 算法要求将迭代器作为输入传递给模型 ForwardIterator

The C++ standard library's max_element algorithm requires the iterators passed as inputs to model ForwardIterator.

我的理解是 ForwardIterator 通过指定你可以使用一个来优化 InputIterator ForwardIterator 多次迭代相同的范围。因此,多遍算法需要 ForwardIterator s。

My understanding is that ForwardIterator refines InputIterator by specifying that you can use a ForwardIterator to iterate over the same range multiple times. Therefore, multi-pass algorithms require ForwardIterators.

然而, max_element 不是多遍算法 - 只需迭代一次范围就可以确定其最大元素。那么为什么 max_element 需要额外的功能 ForwardIterator

However, max_element is not a multi-pass algorithm - it is sufficient to iterate over a range once to determine its maximum element. So why does max_element need the additional capabilities of ForwardIterator?

推荐答案

std :: max_element 返回最大元素的迭代器。如果你提供单个通过范围,那么迭代器将不再有效,因为算法必须对范围执行完整传递。

std::max_element returns an iterator to the maximum element. If you provide a single pass range, that iterator will not be valid any more, since the algorithm has to perform a full pass on the range.

在单程范围内,您无法将可用的迭代器保留为先前的值。这是由于标准中表107中给出的 ++ r 的后置条件:

On a single pass range, you cannot keep an usable iterator to a previous value. This is due to a post-condition on ++r given in Table 107 in the standard:


发布: r 的前一个值的任何副本不再需要可解除引用或位于 =的域中=

post: any copies of the previous value of r are no longer required either to be dereferenceable or to be in the domain of ==.

基本上,单次通过范围是在您通过它时消失的范围,和 std :: max_element 需要一个范围,以便将迭代器返回到(可能)中间。

Basically, a single pass range is a range that "disappears" as you pass through it, and std::max_element needs a range that sticks around in order to return an iterator to (possibly) the middle of it.

可以编写一个算法来计算返回实际最大值而不是迭代器的最大值,但这需要值可以复制以便按值返回。 Movable是不够的,因为移动会阻止使用const迭代器。并且通过引用返回也不是一个选项,因为这意味着范围实际上停留在。

One could write an algorithm to compute the maximum that returned the actual maximum value instead of an iterator, but that would require the values to be copyable in order to return it by value. Movable would not be enough as moving would prevent the use of const iterators. And returning by reference would not be an option either, as that would mean the range actually stuck around.

这篇关于为什么std :: max_element需要ForwardIterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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