我可以使用反向迭代器作为 ForwardIt 吗?

Can I use reverse iterator as ForwardIt?

基于this questionstd::rotate 定义如下:

template< class ForwardIt >
constexpr ForwardIt rotate( ForwardIt first, ForwardIt n_first, ForwardIt last );

查看名称 ForwardIt,它需要前向迭代器。

问题:假设我的初始集合支持正向迭代器(例如vector),我可以在这里使用反向迭代器 ? Why/why 不是吗?

查看,例如,http://www.cplusplus.com/reference/iterator/reverse_iterator/, I don't understand if what is returned be considered a forward iterator. Do I have to guarantee that reverse iterator satisfies forward iterator's properties? In this case, how can I check that it's true? vector::rbegin() 文档没有提及是否是这种情况。

查看 iterator_category 成员 typedef。迭代器通过将其设置为适当的标记来报告它们的类别。

[ https://en.cppreference.com/w/cpp/iterator/reverse_iterator ]

iterator_category — If std::iterator_traits<Iter>::iterator_category models std::derived_from<std::random_access_iterator_tag>, this is std::random_access_iterator_tag. Otherwise, this is std::iterator_traits<Iter>::iterator_category unchanged.

鉴于原始迭代器必须至少是双向的(参见 link),这意味着生成的迭代器要么是随机访问的(如果原始迭代器至少是随机访问的),要么是双向的(否则)。

(这里使用std::derived_from是因为当A是B的子集时类别A继承自类别B,这意味着A的要求是B的要求的超集。唯一继承自random_access_iterator_tagcontiguous_iterator_tag.)

reverse_iterator 的要求在 reverse.iter.requirements 中给出:

The template parameter Iterator shall either meet the requirements of a Cpp17BidirectionalIterator ([bidirectional.iterators]) or model bidirectional_­iterator ([iterator.concept.bidir]).

以及iterator.concept.bidir的要求:

The bidirectional_­iterator concept adds the ability to move an iterator backward as well as forward.

所以是的,reverse_iterator 可以用作 forward_iterator