0

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?

  • 1
    Use [resize()](http://en.cppreference.com/w/cpp/container/vector/resize) not [reserve()](http://en.cppreference.com/w/cpp/container/vector/reserve). – Galik Nov 25 '17 at 02:23
  • Well, if you know that you are reading in chars, couldn't you just read in a certain number of characters? – NL628 Nov 25 '17 at 02:25
  • Possible duplicate of https://stackoverflow.com/questions/43681922/vectorreserve-cause-vector-iterator-offset-out-of-range – Galik Nov 25 '17 at 02:29
  • reserve is just allocating memory: it does not set the size. – zdf Nov 25 '17 at 02:38

1 Answers1

0

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.

Yashas
  • 1,154
  • 1
  • 12
  • 34