c – 对InputIterator语义/概念要求的困惑

C InputIterator是Iterator概念中最受限制的类型之一.它只能保证支持解除引用,相等比较,预增量和后增量(以及后增量和取消引用)

由于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的值相同? (当然,提供它产生的任何类型*实现理智的相等比较语义)

解决方法

Is value1 guaranteed to be the same value as value2?

是.实际上,您也可以复制迭代器,并且保证在复制其中一个迭代器之前,该副本会提供相同的结果:

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语言中的static关键字 在C语言中,static可以用来修饰局...
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针...
浅谈C/C++中的指针和数组(一)指针是C/C++...
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时...
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下...
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面...