std::vector<int> a; std::vector<int> b; std::vector<int> c;
I would like to concatenate these three vectors by appending b
's and c
's elements to a
. Which is the best way to do this, and why?
1) By using vector::insert
:
a.reserve(a.size() + b.size() + c.size()); a.insert(a.end(), b.begin(), b.end()); a.insert(a.end(), c.begin(), c.end()); b.clear(); c.clear();
2) By using std::copy
:
a.reserve(a.size() + b.size() + c.size()); std::copy(b.begin(), b.end(), std::inserter(a, a.end())); std::copy(c.begin(), c.end(), std::inserter(a, a.end())); b.clear(); c.clear();
3) By using std::move
(from C++11
):
a.reserve(a.size() + b.size() + c.size()); std::move(b.begin(), b.end(), std::inserter(a, a.end())); std::move(c.begin(), c.end(), std::inserter(a, a.end())); b.clear(); c.clear();
To insert/append a vector's elements to another vector, we use vector::insert() function.
How do you append to a Vector in C++? Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace().
In my opinion, your first solution is the best way to go.
vector<>::insert
is designed to add element so it's the most adequate solution.
You could call reserve
on the destination vector to reserve some space, but unless you add a lot of vector together, it's likely that it wont provide much benefits: vector<>::insert
know how many elements will be added, you will avoid only one reserve
call.
Note: If those were vector
of more complex type (ie a custom class, or even std::string
), then using std::move
could provide you with a nice performance boost, because it would avoid the copy-constructor. For a vector of int
however, it won't give you any benefits.
Note 2: It's worth mentioning that using std::move
will cause your source vector
's content to be unusable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With