Bob5421 Bob5421 - 7 months ago 52
C++ Question

Feed std::vector<unsigned char> from unsigned char *

i have write this piece of code:

unsigned char *buffer = ...
std::vector<unsigned char> vec(buffer,128);

This works but i would like to feed the vector after its declaration (suppose the vector is a field of a class)

unsigned char *buffer = ...
std::vector<unsigned char> vec;
vec = vec(buffer,128) ???

I do not know what to do on the last line.
The only thing that actually works is to resize the vector then do a memcpy. Is there a better way?


Well, with move semantics, you can simply do

vec = std::vector<unsigned char>(buffer, buffer + 128);

If that ruffles your feathers, you can use std::copy together with std::back_inserter:

std::copy(buffer, buffer+128, std::back_inserter(vec));

Another option is to use vector::assign.