Search code examples
c++vectoristream

How to read specific number of bytes from istream into a vector?


I'd like to read a number of bytes from an istream into a vector. I thought this would have the answer but it's actually asking an entirely different thing.

My code so far:

std::vector<char> read_buffer(std::istream& is, const std::size_t size) {
    std::vector<char> buf;
    buf.reserve(size);
    is.read(buf.data(), size);
    return buf;
}

This doesn't work because vector was written into without it knowing, so after the is.read, its size is still 0, not size. What's the proper way to implement this function?


Solution

  • The vector container wraps a dynamic array. It is important to understand the difference between capacity and size of a vector.

    Size: The size of a vector is the number of items it is currently holding.

    Capacity: Capacity is the number of items the vector can hold without requiring a memory reallocation.

    The array which the container wraps can be larger than the number of elements it contains. When you push back a new element, the vector will add it to the end of the array. If there is no room left, i.e: capacity was already equal to the size before before pushing, the vector requests for a larger array.

    In your code, you have used reserve which is used to increase the capacity of the vector. The size of the vector remains zero.

    To increase the size of the vector, you should use resize.