Programming Tips - STL: How to efficiently append a byte vector to another

Date: 2009aug26 Update: 2026aug21 Language: C++ Q. STL: How to efficiently append a byte vector to another A.
#include <vector> typedef std::vector<BYTE> BYTE_ARRAY; // I use "Ba" as a short form of "BYTE_ARRAY" on this page // Here's a fast way to do it: void AppendMemoryToBa(BYTE_ARRAY &ba, const LPVOID in, const size_t size) { size_t before_size = ba.size(); ba.resize(before_size + size); memcpy(ba.begin() + before_size, in, size); } // Append b to a inline void AppendBaToBa(BYTE_ARRAY &a, const BYTE_ARRAY &b) { AppendMemoryToBa(a, (LPVOID)b.begin(), b.size()); }
// Another way inline void AppendBaToBa(BYTE_ARRAY &a, const BYTE_ARRAY &b) { a.insert(a.end(), b.begin(), b.end()); }
// Here's the slow way: void SLOW_AppendBaToBa(BYTE_ARRAY &a, const BYTE_ARRAY &b) { for (BYTE_ARRAY::const_iterator it = b.begin(); it != b.end(); it++) { a.push_back(*it); } }