std::istreambuf_iterator initializes with no

2019-09-17 18:29发布

问题:

Here is the code:

#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>

std::vector<unsigned char> bytes;
{
    std::ifstream in(name, std::ios_base::binary);
    bytes.assign(std::istreambuf_iterator<char>(in >> std::noskipws),
                 std::istreambuf_iterator<char>());
}

According to the reference, the vector.assign function takes two arguments, first and last, and takes anything in between into the vector. And the istreambuf_iterator function takes this form:

istreambuf_iterator( std::basic_istream<CharT,Traits>& is );    
istreambuf_iterator( std::basic_streambuf<CharT,Traits>* s );

These are all easy to understand, but in the snippet above, the second iterator initializer takes no arguments, what does it mean?

Also notice that the type of bytes is unsigned char, while the type of the iterator is char, isn't this a mismatch?

回答1:

the second iterator initializer takes no arguments, what does it mean?

It means it's initialized to be the end-of-stream iterator.

Also notice that the type of bytes is unsigned int, while the type of the iterator is char, isn't this a mismatch?

You mean unsigned char right? (That's what it says in your code.)

It's fine because unsigned char can be constructed from and assigned from char. Templated functions taking iterator ranges generally do not require that the types match exactly. (For the precise requirements, see Table 100 in §23.2.3 of the standard.)