Merge vector of vectors into a single vector
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Flattening a std::vector<std::vector<T>> into one std::vector<T> is a common C++ task when nested data needs to be processed linearly. The simplest correct solution is usually to reserve the total size up front and append each inner vector with insert.
Basic Flattening with insert
Suppose you have a vector of integer vectors.
That appends each inner vector in order and preserves element order within each chunk.
Reserve Capacity First
If the nested vectors are large, repeated growth of the result vector can cause extra allocations and copies. Compute the total size first and reserve that amount.
That small optimization is often the difference between a tidy linear pass and unnecessary reallocation churn.
Move Elements When You No Longer Need the Inner Vectors
If the inner vectors will not be used again and T is expensive to copy, move the elements instead of copying them.
After moving, the original inner strings are no longer guaranteed to keep their old values, so use this only when ownership is really being transferred.
Generic Helper Function
A helper function keeps the flattening logic reusable.
That is usually clearer than writing ad hoc loops in multiple places.
Alternatives and Tradeoffs
You could flatten with repeated push_back calls in a nested loop.
That is perfectly valid and sometimes easier to adapt when filtering or transforming values during the flattening step. If you simply want concatenation, insert communicates intent more directly.
Complexity
The total work is proportional to the number of elements copied or moved. Reserving capacity does not change the big-O time complexity, but it reduces allocation overhead and usually improves real performance.
Common Pitfalls
A common mistake is forgetting to reserve space when flattening many large vectors, which can trigger repeated reallocations. Another is using move iterators and then accidentally reading the old inner values as if they were unchanged. Developers also sometimes flatten by copying vectors themselves instead of their contents, which produces the wrong type entirely. Finally, if ordering matters, be careful not to parallelize or sort chunks unless that behavior is intended.
Summary
- Use
insertto append each inner vector into the result. - Reserve the total output size up front when possible.
- Use move iterators only when the source data will not be reused.
- A helper function keeps flattening logic consistent across the codebase.
- The main performance gain usually comes from avoiding unnecessary reallocations.

