What is the best way to concatenate two vectors?

jmasterx picture jmasterx · Jul 5, 2010 · Viewed 223.3k times · Source

I'm using multitreading and want to merge the results. For example:

std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;

I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?

Answer

Kirill V. Lyadvinsky picture Kirill V. Lyadvinsky · Jul 5, 2010
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );