1

I have what I believe is a simple question about the std::vector type. The underlying problem is straightforward: I have a function that reads a stream of data into a buffer (as well as getting the buffer's size), then returns a that data as a vector. The type for the collection elements is fixed, uint8_t. My question is, is there a better way for me to populate the vector than walking the buffer?

Here is my naive, harebrained code:

uint8_t* buffer;
size_t size;
stream->readBuffer(buffer, size); // I don't own the stream class
std::vector<uint8_t> output(size);
for (size_t i = 0; i < currentChunkLength; i++)
{
    output.push_back(buffer[i]);
}
return output;
Justin R.
  • 23,435
  • 23
  • 108
  • 157
  • 3
    `std::vector(buffer, buffer+size);` PS: if you initialize a vector with a size, don't use push back you'll end up with twice the elements, of which the first half have default values. – Borgleader Aug 29 '13 at 20:00
  • Ah, I didn't see that similar question (I didn't consider my pointer and length to be a c-style array). Surprisingly the answers are all different! Regardless it looks like I should close this as a dupe. – Justin R. Aug 29 '13 at 20:10

2 Answers2

17

Use the constructor taking iterators:

std::vector<unit8_t> output(buffer, buffer + size);
David Brown
  • 13,336
  • 4
  • 38
  • 55
6

You could read in one step (you own the vector):

std::vector<uint8_t> output(size);
stream->readBuffer(output.data(), output.size());
Naszta
  • 7,560
  • 2
  • 33
  • 49
  • Interesting. I hadn't considered this. Just because I'm curious, what are the pros and cons reading directly into the vector? I'm assuming that at a minimum I'm saving one memory allocation? – Justin R. Aug 29 '13 at 20:08
  • If the readBuffer method allocates the memory itself I don't think you can do this. – Borgleader Aug 29 '13 at 20:09
  • 1
    @fatcat1111 a memcpy in to what? in your example the buffer ptr is unitialized – Borgleader Aug 29 '13 at 20:12
  • `std::vector` is continuous and memory leak free. This is the C++ way of heap memory use of simple types. (I haven't called `delete` or `delete []` directly for years.) – Naszta Aug 29 '13 at 20:23
  • @fatcat1111 my point exactly, in your example not pointing to anything so memcopying into it is bad. – Borgleader Aug 29 '13 at 22:40