What is the difference betwen istreambuf_iterator
and istream_iterator
.
For the following code:
istream_iterator<int> cin_in(cin);
istream_iterator<int> end;
where does the iterator end
point to?
Will the iterator bind with the stream?
If I write the code
istream_iterator<int>()
is it the same as end
?
And where is that all documented?
What is the difference betwen
istreambuf_iterator
andistream_iterator
.
std::istream_iterator
is an iterator for formatted extraction. For instance, if you have a line of integers from a file and wish to copy them to some container, you would use std::istream_iterator<int>
which internally will copy the value extracted from an int
(using operator>>()
) to the container:
std::copy(std::istream_iterator<int>(file),
std::istream_iterator<int>(), std::back_inserter(some_container));
std::istreambuf_iterator
is an iterator for unformatted extraction. It works directly on the std::streambuf
object provided through its constructor. As such, if you need simply the contents of the file without worrying about their format, use this iterator. For example, sometimes you want to read an entire file into a string or some container. A regular formatted extractor will discard leading whitespace and convert extracted tokens; the buffer iterator will not:
std::string str(std::istreambuf_iterator<char>{file}, {});
Where does the iterator end point to?
A default-constructed stream iterator is simply a special sentinel object that represents the end of the stream. Since IOStreams are one-pass, there's no way for it to actually point to the end until we have read up to that point. Internally, when an extraction has failed or the read hit the end-of-file, the iterator that was constructed with a stream (or stream buffer) will change into an end stream iterator. This is what helps standard algorithms work with stream iterators, since they act like regular iterators on the outside.
And where is that all documented?
Many places. Formally in the Standard. You can also find documentation on cppreference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With