# c++ insert of - Appending a vector to a vector

2
Answers

vectors at push

This question already has an answer here:

- Concatenating two std::vectors 17 answers

Assuming I have 2 standard vectors:

```
vector<int> a;
vector<int> b;
```

Let's also say the both have around 30 elements.

- How do I add the vector b to the end of vector a?

The dirty way would be iterating through b and adding each element via `vector<int>::push_back()`

, though I wouldn't like to do that!

527 votes

c++

If you would like to add vector to itself both popular solutions will fail:

```
std::vector<std::string> v, orig;
orig.push_back("first");
orig.push_back("second");
// BAD:
v = orig;
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "", "" }
// BAD:
v = orig;
std::copy(v.begin(), v.end(), std::back_inserter(v));
// std::bad_alloc exception is generated
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "first", "second" }
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
std::copy(v.begin(), v.end(), std::back_inserter(v));
// Now v contains: { "first", "second", "first", "second" }
// GOOD (best):
v = orig;
v.insert(v.end(), orig.begin(), orig.end()); // note: we use different vectors here
// Now v contains: { "first", "second", "first", "second" }
```

c++1

525