With vectors, one can assume that elements are stored contiguously in memory, allowing the range [&vec[0], &vec[vec.capacity()) to be used as a normal array. E.g.,
vector<char> buf;
buf.reserve(N);
int M = read(fd, &buf[0], N);
But now the vector doesn't know that it contains M bytes of data, added externally by read(). I know that vector::resize() sets the size, but it also clears the data, so it can't be used to update the size after the read() call.
Is there a trivial way to read data directly into vectors and update the size after? Yes, I know of the obvious workarounds like using a small array as a temporary read buffer, and using vector::insert() to append that to the end of the vector:
char tmp[N];
int M = read(fd, tmp, N);
buf.insert(buf.end(), tmp, tmp + M)
This works (and it's what I'm doing today), but it just bothers me that there is an extra copy operation there that would not be required if I could put the data directly into the vector.
So, is there a simple way to modify the vector size when data has been added externally?
&buf[0]works in debug mode? For instance, on Visual Studio, in debug modestd::vector::operator[]performs a range check. So that expression will throw ifbufis empty.vector. You can see where it stores thebeginandendpointers and capacity, and if you just overwrite theendpointer, I'm pretty sure that will change the size as you want. Just copy whatever the implementation ofresize()does in the case where the capacity is big enough to start with, leaving out the memset/fill/whatever. You'll have to work around someprivatemodifiers, of course, perhaps by hard-coding in the offsets.