c++iteratoristream-iterator

Use of '{}' as end iterator in std::vector constructor


A way for reading a file and put it as a byte array into a vector would be:

std::ifstream input(filePath, std::ios::binary);
std::vector<unsigned char> barray(std::istreambuf_iterator<char>(input), {});

As far as I understand, the constructor used for std::vector in the above code snippet is

template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );

Thus, the {} corresponds to last.

What is exactly {}? Is it acting like a null/empty iterator?


Solution

  • Thus, the {} corresponds to last.
    What is exactly {}? Is it acting like a null/empty iterator?

    It's a default constructed object of type std::istreambuf_iterator<char>.

    std::vector<unsigned char> barray(std::istreambuf_iterator<char>(input), {});
    

    is the same as

    std::vector<unsigned char> barray{std::istreambuf_iterator<char>{input},
                                      std::istreambuf_iterator<char>{}};