简体   繁体   English

为什么双向迭代器没有运算符+/-?

[英]Why is there no operator +/- for a bidirectional iterator?

My own reasoning for it is that there is no random access and there is no way to know the bounds. 我自己的理由是,没有随机访问,也没有办法知道界限。 But then why do we have std::advance ? 但是,为什么我们要使用std::advance呢? [EDIT] And come to think of it, why is there no std::deadvance (for lack of a better word)? [编辑]考虑一下,为什么没有std::deadvance (因为缺少更好的词)?

You are right; 你是对的; the requirements for operator+/- is that it be an O(1) operation, which cannot be met by bidirectional iterators. operator+/-的要求是它是O(1)操作,双向迭代器无法满足。 std::advance has no such speed requirement (but will use it when available, eg, for random access iterators). std::advance没有这样的速度要求(但是会在可用时使用它,例如,用于随机访问迭代器)。

Note that boost has boost::next and boost::prior implementations for iterators; 注意,boost为迭代器提供了boost::nextboost::prior实现; I'm not sure what their status is on standardization but if it's in boost it's solid. 我不确定他们在标准化方面的地位如何,但是如果它在推动中的确是牢固的。

The rational for std::advance is that it should be obvious that you really intended to use it, even if it is not O(1). std::advance的合理性在于,即使它不是O(1),也应该明确地表明您确实打算使用它。

You don't need a std::deadvance as you can use std::advance with a negative distance (for bidirectional iterators). 您不需要std::deadvance因为您可以使用负距离的std::advance (对于双向迭代器)。

我们之所以拥有std::advance是因为它提供了一种使用迭代器支持的最有效方式来推进迭代器的方法

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

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