Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the difference betwen `istreambuf_iterator` and `istream_iterator`

Tags:

c++

  1. What is the difference betwen istreambuf_iterator and istream_iterator.

  2. 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?

  3. And where is that all documented?

like image 933
Jessica Jin Avatar asked Nov 09 '14 02:11

Jessica Jin


1 Answers

What is the difference betwen istreambuf_iterator and istream_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.

like image 196
David G Avatar answered Oct 20 '22 17:10

David G