JustWe
JustWe

Reputation: 4484

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);

Upvotes: 2

Views: 5458

Answers (2)

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 5

Andrey Semashev
Andrey Semashev

Reputation: 10614

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);

Upvotes: 10

Related Questions