简体   繁体   English

为什么std :: max_element需要ForwardIterator?

[英]Why does std::max_element require a ForwardIterator?

The C++ standard library's max_element algorithm requires the iterators passed as inputs to model ForwardIterator . C ++标准库的max_element算法要求将迭代器作为输入传递给模型ForwardIterator

My understanding is that ForwardIterator refines InputIterator by specifying that you can use a ForwardIterator to iterate over the same range multiple times. 我的理解是, ForwardIterator通过指定您可以使用ForwardIterator迭代相同的范围来优化InputIterator Therefore, multi-pass algorithms require ForwardIterator s. 因此,多遍算法需要ForwardIterator

However, max_element is not a multi-pass algorithm - it is sufficient to iterate over a range once to determine its maximum element. 但是, max_element不是多遍算法 - 只需迭代一次范围就足以确定其最大元素。 So why does max_element need the additional capabilities of ForwardIterator ? 那么,为什么max_element需要的额外功能ForwardIterator

std::max_element returns an iterator to the maximum element. std::max_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. 如果提供单个传递范围,则该迭代器将不再有效,因为算法必须对该范围执行完整传递。

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: 这是由于标准表107中给出的++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 == . post: r的先前值的任何副本不再需要可解除引用或在==的域中。

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. 基本上,单个通过范围是一个“消失”的范围,当你通过它时, std::max_element需要一个固定的范围,以便将迭代器返回到(可能)它的中间。

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. Movable是不够的,因为移动会阻止使用const迭代器。 And returning by reference would not be an option either, as that would mean the range actually stuck around. 并且通过引用返回也不是一种选择,因为这意味着范围实际上被困住了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM