Question
I have two standard C++ vectors:
std::vector<int> a;
std::vector<int> b;
Assume both vectors contain around 30 elements.
How can I append all elements of b to the end of a?
One possible approach is to loop through b and call push_back() for each element, but I would prefer a cleaner standard-library solution.
Short Answer
By the end of this page, you will understand how to append one std::vector to another in C++, why insert() is the usual solution, how it works internally, when push_back() loops are still acceptable, and what mistakes to avoid when combining vectors.
Concept
In C++, a std::vector stores elements in a contiguous dynamic array. When you want to append one vector to another, you usually want to copy a whole range of elements from the second vector into the first.
The standard way to do this is with vector::insert().
a.insert(a.end(), b.begin(), b.end());
This means:
- insert into
a - at position
a.end()(the end ofa) - all elements from the range
[b.begin(), b.end())
This is important because:
- it is concise
- it uses the standard library idiomatically
- it expresses your intent clearly: append a range
- it can be more efficient and readable than manually looping
When appending vectors, C++ may need to grow the destination vector's storage. If a does not have enough capacity, it allocates more memory and copies or moves elements into the new storage.
For beginner-friendly code, insert() is the most common and direct solution for concatenating vectors.
Mental Model
Think of a std::vector as a row of boxes on a shelf.
ais one row of boxes already holding values.bis another row of boxes.- Appending
btoameans taking all boxes fromband placing copies of them at the end ofa's row.
insert() is like saying:
Starting at the end of shelf
a, place every item from shelfbin order.
You do not need to move one item at a time manually in your own loop unless you want special behavior.
Syntax and Examples
The usual syntax is:
a.insert(a.end(), b.begin(), b.end());
Example 1: Append one vector to another
#include <iostream>
#include <vector>
int main() {
std::vector<int> a{1, 2, 3};
std::vector<int> b{4, 5, 6};
a.insert(a.end(), b.begin(), b.end());
for (int value : a) {
std::cout << value << ' ';
}
}
Output:
1 2 3 4 5 6
Explanation
a.end()says to insert at the end of
Step by Step Execution
Consider this example:
std::vector<int> a{10, 20};
std::vector<int> b{30, 40, 50};
a.insert(a.end(), b.begin(), b.end());
Step by step:
astarts as:
[10, 20]
bstarts as:
[30, 40, 50]
-
a.end()points just past the last element ofa -
b.begin()points to30 -
b.end()points just past50
Real World Use Cases
Appending vectors appears often in real programs.
1. Merging batches of data
A program may read records from multiple files and store them in one vector:
allRecords.insert(allRecords.end(), batch.begin(), batch.end());
2. Combining API or database results
If data is loaded page by page, each new page can be appended to the existing result set.
3. Building token lists or parsed output
A parser may collect tokens from multiple stages and append them into one final sequence.
4. Game development
A game might combine lists of visible objects, events, or commands into one processing queue.
5. Logging and telemetry
Applications sometimes collect event chunks in separate vectors and then merge them for processing or writing to disk.
Real Codebase Usage
In real codebases, developers often combine insert() with a few common patterns.
Reserve before append
When size is predictable, this is a common optimization:
items.reserve(items.size() + newItems.size());
items.insert(items.end(), newItems.begin(), newItems.end());
Guard clause for empty input
if (b.empty()) {
return;
}
a.insert(a.end(), b.begin(), b.end());
This can make intent clearer, especially in functions.
Appending results from helper functions
std::vector<int> loadPart1();
std::vector<int> loadPart2();
std::vector<int> result = loadPart1();
std::vector<int> extra = loadPart2();
result.insert(result.(), extra.(), extra.());
Common Mistakes
1. Using push_back() with the whole vector
This does not work because push_back() adds one element, not a whole range.
Broken code:
std::vector<int> a{1, 2};
std::vector<int> b{3, 4};
a.push_back(b); // error
Why it fails:
astoresintbis astd::vector<int>- an
intvector cannot push a whole vector as oneint
2. Forgetting the insert position
Broken code:
a.insert(b.begin(), b.end());
Why it fails:
insert()needs a position inafirst
Comparisons
| Approach | Best for | Pros | Cons |
|---|---|---|---|
a.insert(a.end(), b.begin(), b.end()) | Appending all elements from another vector | Clear, standard, concise | Copies elements unless move iterators are used |
Loop with push_back() | Custom logic while appending | Flexible, easy to filter/transform | More verbose |
Assignment a = b | Replacing contents of a | Simple | Does not append |
std::copy with std::back_inserter(a) | Generic algorithms style | Works well with algorithm pipelines | Slightly less direct for beginners |
Cheat Sheet
// Append vector b to vector a
std::vector<int> a;
std::vector<int> b;
a.insert(a.end(), b.begin(), b.end());
Quick rules
insert(pos, first, last)inserts a range at positionpos- to append, use
a.end()as the position - source vector
bis unchanged when using normal iterators - reserve capacity first if performance matters
Useful pattern
a.reserve(a.size() + b.size());
a.insert(a.end(), b.begin(), b.end());
Alternative
for (int x : b) {
a.push_back(x);
}
If you need transformation or filtering
Use a loop instead of insert().
Common error
FAQ
How do I append one std::vector to another in C++?
Use:
a.insert(a.end(), b.begin(), b.end());
Does insert() modify the second vector?
No. In the normal form, it copies elements from b into a. b remains unchanged.
Is looping with push_back() wrong?
No. It is completely valid. insert() is just shorter and clearer when appending a whole range.
Should I call reserve() before appending?
If performance matters and you know the final size, yes. It can reduce reallocations.
Can I append vectors of custom objects?
Yes, as long as the element types are compatible and copyable or movable as needed.
What if I want to move elements instead of copy them?
You can use move iterators:
a.insert(a.end(), std::make_move_iterator(b.()), std::(b.()));
Mini Project
Description
Build a small C++ program that combines multiple groups of numbers into a single list. This demonstrates how appending vectors works in a realistic situation, such as merging batches of data loaded from different sources.
Goal
Create a program that appends one vector to another and prints the combined result.
Requirements
- Create two
std::vector<int>variables with sample values. - Append the second vector to the first using a standard-library approach.
- Print the final combined vector.
- Reserve capacity before appending.
- Keep the second vector unchanged.
Keep learning
Related questions
Advantages of Brace Initialization in C++
Learn why C++ brace initialization is often clearer and safer than other object initialization styles, with examples and common pitfalls.
Basic Rules and Idioms for Operator Overloading in C++
Learn the core rules, syntax, and common idioms for operator overloading in C++, including member vs non-member operators.
C++ Aggregates, Trivial Types, Trivially Copyable Types, and PODs Explained
Learn what aggregates, trivial types, trivially copyable types, and PODs mean in C++, how they differ, and why they matter.