简体   繁体   中英

How to append raw bytes to std::vector?

I want to append the raw bytes into vector like this.

vector.reserve(current_size + append_data_size);
memcpy(append_data, vector.data() + current_size, append_data_size);
vector.resize(current_size  + append_data_size) // Expect only set size to current_size + append_data_size.

does below is slower? because I think vector is initialised to default first then set the data which is waste.

vector.resize(current_size  + append_data_size);
memcpy(append_data, vector.data() + current_size, append_data_size);

Modifying vector storage beyond its size is undefined behavior, and a subsequent resize will initialize the new elements at the end of the storage.

However, you could use insert instead:

vector.insert(vector.end(), bytes, bytes + size);

Even if you call reserve , you still must call resize on the vector if you want to access the new elements, otherwise the behaviour of your code is undefined . What reserve can do is make push_back and other such operations more efficient.

Personally I wouldn't concern yourself with any such optimisations unless you can prove they have an effect with an appropriate profiling tool. More often than not, fiddling with the capacity of a std::vector is pointless.

Also using memcpy is hazardous. (Copy constructors will not be called for example, knowledge of the exact behaviour of copying padding in structures with memcpy for example is a sure way of increasing your reputation on this site!) Use insert instead and trust the compiler to optimise as appropriate.

Without an explicit additional parameter, std::vector::resize value-initialises any additional members. Informally that means the elements of a std::vector of T say are set to values in the same way as the t in static T t; would be.

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