C++ InputIterator
是迭代器概念中最有限的类型之一。它只保证支持解引用、相等比较、前自增和后自增(以及后自增和解引用)
因为 InputIterator
对象经常迭代任意流,您甚至不能确定对同一输入迭代两次会产生相同的值。
不过,我很困惑,如果取消引用运算符 operator *
每次取消引用时都能保证返回相同的值,前提是您从不递增迭代器。
例如,假设std::begin(some_input_stream)
返回一个满足InputIterator
概念要求的对象,而它
不等于到或超过结束位置:
auto it = std::begin(some_input_stream);
auto value1 = *it;
auto value2 = *it;
assert(value1 == value2);
是否保证 value1
与 value2
的值相同? (当然,前提是 *it
产生的任何类型都实现了合理的相等比较语义)
最佳答案
Is
value1
guaranteed to be the same value asvalue2
?
是的。事实上,您还可以复制迭代器,并且该拷贝保证提供相同的结果直到您递增其中一个迭代器:
auto it2 = it;
auto value3 = *it2;
assert(value3 == value1);
++it2;
auto value4 = *it; // ERROR: might not be dereferencable any more
这由 C++11 表 107(输入迭代器要求)中的 *a
要求指定:
If
a == b
and(a,b)
is in the domain of==
then*a
is equivalent to*b
.
并且,在 ++r
之后:
Any copies of the previous value of
r
are no longer required either to be dereferenceable or to be in the domain of==
.
关于c++ - 对 InputIterator 语义/概念要求的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18698140/