Martel
Martel

Reputation: 2734

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?

Upvotes: 1

Views: 172

Answers (1)

R Sahu
R Sahu

Reputation: 206717

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>{}};

Upvotes: 5

Related Questions