Copy the contents of std::vector<char> into a char* buffer?

std::copy(_v.begin(), _v.end(), buffer);

This is preferred way to do this in C++. It is safe to copy this way if buffer is large enough.


If you just need char*, then you can do this:

char *buffer=&v[0];//v is guaranteed to be a contiguous block of memory.
//use buffer

Note changing data pointed to by buffer changes the vector's content also!

Or if you need a copy, then allocate a memory of size equal to v.size() bytes, and use std::copy:

 char *buffer = new char[v.size()];
 std::copy(v.begin(), v.end(), buffer);

Dont forget to delete []buffer; after you're done, else you'll leak memory.

But then why would you invite such a problem which requires you to manage the memory yourself.. especially when you can do better, such as:

auto copy = v; // that's simpler way to make copies!!
// and then use copy as new buffer.
// no need to manually delete anything. :-)

Hope that helps.


The safest way to copy a vector<char> into a char * buffer is to copy it to another vector, and then use that vector's internal buffer:

std::vector<char> copy = _v;
char * buffer = &copy[0];

Of course, you can also access _vs buffer if you don't actually need to copy the data. Also, beware that the pointer will be invalidated if the vector is resized.

If you need to copy it into a particular buffer, then you'll need to know that the buffer is large enough before copying; there are no bounds checks on arrays. Once you've checked the size, your second method is best. (The first only works if vector::iterator is a pointer, which isn't guaranteed; although you could change the second argument to &_v[0] to make it work. The third does the same thing, but is more complicated, and probably should be fixed so it doesn't modify buffer).

Tags:

C++

Stl

Stdvector