Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion over InputIterator semantics/concept requirements

The C++ InputIterator is one of the most limited type of Iterator Concept. It is only guaranteed to support dereference, equality comparison, pre-increment and post-increment (and post-increment and dereference)

Because InputIterator objects often iterate over an arbitrary stream, you can't even be sure that iterating twice over the same input will yield the same values.

I'm confused, though, if the dereference operator, operator *, is guaranteed to return the same value every time you dereference it, provided that you never increment the iterator.

For example, assuming std::begin(some_input_stream) returns an object that meets the InputIterator concept requirements, and it is not equal to or past the end position:

auto it = std::begin(some_input_stream);
auto value1 = *it;
auto value2 = *it;
assert(value1 == value2);

Is value1 guaranteed to be the same value as value2? (Providing, of course, that whatever type *it yields implements sane equality comparison semantics)

like image 978
Channel72 Avatar asked Sep 09 '13 12:09

Channel72


1 Answers

Is value1 guaranteed to be the same value as value2?

Yes. In fact, you could also copy the iterator, and that copy is guaranteed to give the same result until you increment one of the iterators:

auto it2 = it;
auto value3 = *it2;
assert(value3 == value1);

++it2;
auto value4 = *it; // ERROR: might not be dereferencable any more

This is specified by the requirements for *a in C++11 Table 107 (Input Iterator requirements):

If a == b and (a,b) is in the domain of == then *a is equivalent to *b.

and, after ++r:

Any copies of the previous value of r are no longer required either to be dereferenceable or to be in the domain of ==.

like image 56
Mike Seymour Avatar answered Nov 04 '22 20:11

Mike Seymour