Reputation: 289
I've read that input iterators are used to read in input streams like cin
, which can contain something like "abc"
. If we have two iterators, let's say of typestd::istream_iterator
that both point to 'a'
, and we increment one of them, the other one will become invalidated.
I'm wondering why that's the case. It seems like incrementing one iterator would cause it to read in 'b'
, but I'm not sure why incrementing the other one wouldn't allow that to work either. I've read that this does happen, but I'm a little confused as to why it's the case. Is it how the input streams are structured, or something else?
Upvotes: 0
Views: 197
Reputation: 19128
InputIterator
is not a specific class, it is a concept, which allows efficient implementation of certain constructs. For example, suppose you have a file with lines, max line length is 128 bytes, and you have to provide an iterable interface: with the input iterator concept, you can simply allocate a buffer for a single line, and simply read the next line into this buffer, whenever an input iterator is incremented.
An other example: suppose you have a generator function, which produces the fibonacchi sequence. A BidirectionalIterator
based implementation would need to store the generated number somewhere, while an InputIterator
based solution can simply ask the generator for the next number, and drop the current one - no additional storage is needed.
Upvotes: 1