Append b to a with a.insert(a.end(), b.begin(), b.end());. It copies every element of b onto the end of a in one call and allocates at most once. For a new vector, reserve(a.size() + b.size()) on an empty one and insert both. To move the elements instead of copying them, wrap b's iterators in std::make_move_iterator.
std::vector has no + and, before C++23, no append, so concatenating comes down to the range form of insert. The questions people ask next are about cost and ownership: whether to reserve, how to move strings or unique_ptrs instead of copying them, how to get a new vector without touching either input, and why appending a vector to itself breaks. The sections below answer each one, then a table helps you choose. Each example runs on this page: hit Run, then edit the code and run it again.
1Append with insert at end()Recommended
a.insert(pos, first, last) copies the range [first, last) into a before pos. With pos = a.end() that is an append. Because a vector's iterators know the distance between them, insert computes the new size up front and reallocates at most once, so a separate reserve call adds nothing when you append to an existing vector. Building a new vector from two others is two inserts into an empty one, with a reserve first so the first insert doesn't allocate a buffer the second one throws away.
#include <iostream> #include <vector> void print(const char* label, const std::vector<int>& v) { std::cout << label << " (" << v.size() << "):"; for (int x : v) { std::cout << ' ' << x; } std::cout << '\n'; } int main() { std::vector<int> a = {1, 2, 3}; std::vector<int> b = {4, 5, 6}; // Append b to the end of a: a grows, b is untouched a.insert(a.end(), b.begin(), b.end()); print("a", a); print("b", b); // A new vector from two others: reserve once, then insert both std::vector<int> x = {10, 20}; std::vector<int> y = {30, 40, 50}; std::vector<int> joined; joined.reserve(x.size() + y.size()); joined.insert(joined.end(), x.begin(), x.end()); joined.insert(joined.end(), y.begin(), y.end()); print("joined", joined); // Prepend instead: insert at begin() (shifts every existing element) std::vector<int> front = {-1, 0}; joined.insert(joined.begin(), front.begin(), front.end()); print("prepended", joined); // insert returns an iterator to the first inserted element std::vector<int> c = {7, 8}; auto it = a.insert(a.end(), c.begin(), c.end()); std::cout << "first inserted: " << *it << " at index " << (it - a.begin()) << '\n'; // The element types only need to convert: ints into a vector of doubles std::vector<double> d = {0.5}; d.insert(d.end(), b.begin(), b.end()); std::cout << "doubles:"; for (double v : d) { std::cout << ' ' << v; } std::cout << '\n'; }
Output
After the append, a (6): 1 2 3 4 5 6 and b (3): 4 5 6: the source keeps its elements. Inserting at begin() prepends, giving prepended (7): -1 0 10 20 30 40 50, but it shifts every existing element back, so it costs time proportional to the whole vector. The returned iterator points at the first new element (first inserted: 7 at index 6), and the element types only have to convert: ints go into a std::vector<double> as doubles: 0.5 4 5 6. If insert reallocates, every iterator, pointer and reference into a taken before the call is invalid afterwards.
2Move the elements instead of copying them
When you don't need b afterwards, copying its strings is wasted work, and for a std::vector<std::unique_ptr<T>> it doesn't compile at all, because a unique_ptr can't be copied. Wrap both iterators in std::make_move_iterator and insert moves each element instead. When the target is still empty, skip the elements entirely: dst = std::move(src) takes over src's buffer.
#include <iostream> #include <iterator> #include <memory> #include <string> #include <utility> #include <vector> int main() { std::vector<std::string> a = {"alpha", "beta"}; std::vector<std::string> b = {"a fairly long string", "another long string"}; // Move the strings out of b instead of copying them a.insert(a.end(), std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())); std::cout << "a: " << a.size() << " strings, last = " << a.back() << '\n'; // b still has 2 elements, but each one is moved-from: valid, contents // unspecified. Clear it so nobody reads them by mistake. std::cout << "b still holds " << b.size() << " elements\n"; b.clear(); // unique_ptr cannot be copied, so plain iterators would not compile here std::vector<std::unique_ptr<int>> owners; owners.push_back(std::make_unique<int>(1)); std::vector<std::unique_ptr<int>> more; more.push_back(std::make_unique<int>(2)); more.push_back(std::make_unique<int>(3)); owners.insert(owners.end(), std::make_move_iterator(more.begin()), std::make_move_iterator(more.end())); std::cout << "owners:"; for (const auto& p : owners) { std::cout << ' ' << *p; } std::cout << '\n'; std::cout << "more[0] is null: " << std::boolalpha << (more[0] == nullptr) << '\n'; // When the target is empty, take the whole buffer: no element is touched std::vector<int> src = {4, 5, 6}; std::vector<int> dst; if (dst.empty()) { dst = std::move(src); } else { dst.insert(dst.end(), src.begin(), src.end()); } std::cout << "dst size " << dst.size() << ", src size " << src.size() << '\n'; }
Output
A move iterator moves the elements, not the vector, so the output says b still holds 2 elements, each one a moved-from string whose value is valid but unspecified. That is why the code clears b. The unique_ptr append prints owners: 1 2 3, and the source pointers are left null: more[0] is null: true. Moving the whole vector prints dst size 3, src size 0. For ints and other cheap types a move is the same as a copy, so plain insert is just as fast. For more on owning pointers in containers, see using smart pointers.
3A new vector: write a concat function
If you concatenate in more than one place, put the reserve-and-insert steps in a function template that takes its inputs by const reference and returns a new vector. Returning by value costs nothing extra: the result is moved or constructed in place. A variadic version with a C++17 fold expression joins any number of vectors with one allocation, which beats chaining two-argument calls that each build a temporary.
#include <iostream> #include <string> #include <vector> // Return a new vector: the inputs are taken by const reference and not changed template <typename T> std::vector<T> concat(const std::vector<T>& a, const std::vector<T>& b) { std::vector<T> out; out.reserve(a.size() + b.size()); out.insert(out.end(), a.begin(), a.end()); out.insert(out.end(), b.begin(), b.end()); return out; } // Any number of vectors: a fold expression runs one insert per argument template <typename T, typename... Rest> std::vector<T> concat_all(const std::vector<T>& first, const Rest&... rest) { std::vector<T> out; out.reserve(first.size() + (rest.size() + ... + 0)); out.insert(out.end(), first.begin(), first.end()); (out.insert(out.end(), rest.begin(), rest.end()), ...); return out; } template <typename T> void print(const std::vector<T>& v) { std::cout << v.size() << ':'; for (const auto& x : v) { std::cout << ' ' << x; } std::cout << '\n'; } int main() { std::vector<int> a = {1, 2}; std::vector<int> b = {3, 4, 5}; print(concat(a, b)); print(a); // unchanged std::vector<std::string> head = {"GET"}; std::vector<std::string> path = {"/api", "/v1"}; std::vector<std::string> tail = {"HTTP/1.1"}; print(concat_all(head, path, tail)); // An empty vector in the list is fine print(concat_all(a, std::vector<int>{}, b, a)); // reserve() made one allocation of exactly the final size auto v = concat_all(a, b, b); std::cout << "size " << v.size() << ", capacity " << v.capacity() << '\n'; }
Output
concat(a, b) prints 5: 1 2 3 4 5 and a is still 2: 1 2. concat_all works for any element type, joining three string vectors into 4: GET /api /v1 HTTP/1.1, and accepts empty vectors and the same vector twice: 7: 1 2 3 4 5 1 2. The last line, size 8, capacity 8, shows the single allocation of the exact size. Some answers define operator+ for vectors instead; it works, but an operator on a standard type you don't own surprises readers (is it concatenation or element-wise addition?), so a named function is clearer.
4std::ranges::copy, back_inserter and views::join
std::ranges::copy(b, std::back_inserter(a)) (or the older std::copy(b.begin(), b.end(), std::back_inserter(a))) also appends, and it is the form to use when the source is not a vector, such as a std::list or a stream. But a back_inserter calls push_back once per element, so the vector grows step by step. If you only need to read both vectors in order, you don't have to build a third one at all: std::views::join over two std::spans walks them as one sequence, and the same view flattens a vector of vectors.
#include <algorithm> #include <array> #include <iostream> #include <iterator> #include <ranges> #include <span> #include <vector> int main() { std::vector<int> a = {1, 2, 3}; std::vector<int> b = {4, 5, 6}; // ranges::copy into a back_inserter: one push_back per element of b std::ranges::copy(b, std::back_inserter(a)); std::cout << "a:"; for (int x : a) { std::cout << ' ' << x; } std::cout << '\n'; // Why insert is the better default: count how often the buffer moves std::vector<int> big(1000, 7); std::vector<int> v1 = {1, 2, 3}; const int* old = v1.data(); v1.insert(v1.end(), big.begin(), big.end()); std::cout << "insert: " << (v1.data() != old ? 1 : 0) << " reallocation\n"; std::vector<int> v2 = {1, 2, 3}; int moves = 0; for (int x : big) { old = v2.data(); v2.push_back(x); if (v2.data() != old) { ++moves; } } std::cout << "push_back loop: " << moves << " reallocations\n"; // No copy at all: views::join walks x, then y, through two spans std::vector<int> x = {10, 20}; std::vector<int> y = {30, 40}; std::array<std::span<const int>, 2> parts = {x, y}; std::cout << "joined view:"; for (int n : parts | std::views::join) { std::cout << ' ' << n; } std::cout << '\n'; // The same join flattens a vector of vectors into one vector std::vector<std::vector<int>> rows = {{1, 2}, {}, {3}, {4, 5, 6}}; auto flat_view = rows | std::views::join; std::vector<int> flat(flat_view.begin(), flat_view.end()); std::cout << "flat: " << flat.size() << " elements, last " << flat.back() << '\n'; }
Output
The copy gives the same a: 1 2 3 4 5 6. The counts show the difference: appending 1000 elements takes insert: 1 reallocation but push_back loop: 9 reallocations, each one copying everything so far (the exact count depends on the library's growth factor; this is GCC's libstdc++). Call reserve first when you append with back_inserter. The view prints joined view: 10 20 30 40 without copying, and is valid only while x and y are alive and unchanged. Flattening rows gives flat: 6 elements, last 6. C++23 adds a.append_range(b) and C++26 adds std::views::concat(x, y); this page compiles as C++20, so neither appears in the code.
5Appending a vector to itself
v.insert(v.end(), v.begin(), v.end()) looks like the obvious way to double a vector, but it is undefined behaviour: the standard requires that the range passed to insert does not point into the vector itself, and if insert reallocates, it reads from a buffer it has already freed. It may even appear to work in a quick test, which is why the example does not run it. Any of three fixes is safe.
#include <algorithm> #include <cstddef> #include <iostream> #include <iterator> #include <vector> void print(const char* label, const std::vector<int>& v) { std::cout << label << ':'; for (int x : v) { std::cout << ' ' << x; } std::cout << '\n'; } int main() { // Wrong: v.insert(v.end(), v.begin(), v.end()) is undefined behaviour. // The range must not point into v itself, and insert may reallocate // while it is still reading from that range. // Fix 1: append a copy (the copy is a separate vector) std::vector<int> v = {1, 2, 3}; const std::vector<int> copy = v; v.insert(v.end(), copy.begin(), copy.end()); print("copy first", v); // Fix 2: reserve first, so nothing reallocates, then copy the old part std::vector<int> w = {1, 2, 3}; const std::size_t n = w.size(); w.reserve(2 * n); std::copy_n(w.begin(), n, std::back_inserter(w)); print("reserve + copy_n", w); // Fix 3: by index; push_back of one of its own elements is allowed std::vector<int> u = {1, 2, 3}; const std::size_t m = u.size(); for (std::size_t i = 0; i < m; ++i) { u.push_back(u[i]); } print("index loop", u); // Repeat the whole vector k times (like Python's list * 3) std::vector<int> base = {7, 8}; std::vector<int> rep; rep.reserve(base.size() * 3); for (int k = 0; k < 3; ++k) { rep.insert(rep.end(), base.begin(), base.end()); } print("three times", rep); }
Output
All three print 1 2 3 1 2 3. Copying first is the simplest and costs one extra vector. reserve then std::copy_n is safe because, with enough capacity, push_back never reallocates and the iterators to the old elements stay valid; copying exactly n elements also keeps the loop from chasing its own new elements. The index loop relies on a guarantee: push_back(u[i]) works even when the push reallocates. The last block repeats a vector three times (three times: 7 8 7 8 7 8), since C++ has no v * 3.
6Which should you use?
| Method | Allocations | Changes | Best for |
|---|---|---|---|
| a.insert(a.end(), b.begin(), b.end()) | At most one | a | Appending: the default |
| insert with make_move_iterator | At most one | a, moves out of b | Strings, unique_ptr, when b is done |
| reserve + two inserts (concat) | Exactly one | Nothing | A new vector, inputs untouched |
| ranges::copy + back_inserter | Many, unless reserved | a | Sources that are not vectors |
| views::join over spans | None | Nothing | Reading both in order, flattening |
| v.insert(v.end(), v.begin(), v.end()) | Undefined | v | Never: copy first or reserve |
Frequently asked questions
Is there a + operator to concatenate vectors in C++?
No. std::vector has no + or +=, and no append before C++23 (which adds a.append_range(b)). Use a.insert(a.end(), b.begin(), b.end()) to append, or a small concat(a, b) function that reserves and inserts both into a new vector. You can define operator+ yourself, but a named function is clearer, because readers may expect + on vectors to add elements pairwise.
What is the fastest way to concatenate two vectors?
The range insert: it knows the number of new elements and reallocates at most once, so a.insert(a.end(), b.begin(), b.end()) is as fast as appending gets. For a new vector, call reserve(a.size() + b.size()) first so you get exactly one allocation. A push_back or back_inserter loop without reserve reallocates many times (9 times for 1000 ints on this compiler). If b holds strings or other heavy objects you no longer need, move them with std::make_move_iterator.
How do I merge two sorted vectors into one sorted vector?
That is std::merge, not concatenation: std::vector<int> out; out.reserve(a.size() + b.size()); std::merge(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(out)); interleaves two sorted inputs into one sorted output in linear time. Concatenating and then calling std::sort gives the same result but costs a full sort.
How do I flatten a vector of vectors in C++?
In C++20, auto flat_view = rows | std::views::join; gives a view over every element in order, and std::vector<int> flat(flat_view.begin(), flat_view.end()); copies it into one vector. Before C++20, loop over the rows and insert each one at flat.end(), after reserving the total size.
Does insert invalidate iterators when I append to a vector?
If the vector has to grow its buffer, yes: every iterator, pointer and reference into it becomes invalid. If the new size fits in the current capacity(), the existing elements stay where they are and only end() changes. Call reserve first if you need to keep pointers to elements valid across an append.
Can I append a vector to itself with insert?
Not with v.insert(v.end(), v.begin(), v.end()): the standard forbids passing iterators into the same vector, and a reallocation in the middle of the copy reads freed memory. Copy it first (auto copy = v;), or reserve(2 * n) and then std::copy_n(v.begin(), n, std::back_inserter(v)), or push back v[i] for each old index.