简体   繁体   中英

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 :

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

Another option is to use vector::assign .

Since a pointer and an iterator are basically the same thing you can use std::vector::assign or std::vector::insert . assign will set the vector to the range while insert will add it to any existing elements in the vector

vec.assign(buffer, buffer + size_of_buffer)
//or
vec.insert(vec.end(), buffer, buffer + size_of_buffer)
           ^^^^^^^^^ position to insert the elements before

Also note that

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

Is not a valid constructor call for a std::vector If you are trying to construct the vector directly from the buffer you need

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM