C++ extend a vector with another vector
copy(v_prime.begin(), v_prime.end(), back_inserter(v));
From here
// reserve() is optional - just to improve performance
v.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));
v.insert(v.end(),v_prime.begin(),v_prime.end());
There are multiple ways to achieve your target.
std::vector::insert
The vector can be extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. You can follow one of below approaches. The second version uses C++11 and it can be considered as a more generic answer, as b could also be an array.
a.insert(a.end(), b.begin(), b.end());
a.insert(std::end(a), std::begin(b), std::end(b));
Sometimes in usage it is a best practice to use reserve function before using std::vector::insert. std::vector::reserve function increases the capacity of the container to a value that's greater or equal to new_cap. If new_cap is greater than the current capacity(), new storage is allocated, otherwise the method does nothing.
a.reserve(a.size() + distance(b.begin(), b.end()));
Use of reserve function is not required but may be advisable. And it is best practive to use reserve if you are repeatedly inserting into a vector for which you know the final size, and that size is large. Otherwise, it is better to let the STL grow your vector as needed.
std::copy
std::copy is the second option that you can consider to achieve your target. This function copies the elements in the range (first,last) into the range beginning at result.
std::copy (b.begin(), b.end(), std::back_inserter(a));
However use of std::copy is slower than use of std::vector::insert(), because std::copy() can't reserve enough space before-hand (it doesn't have access to the vector itself, only to an iterator which has), while std::vector::insert(), being a member function, can. Due to that std::copy is indeed slower than using std::vector::insert. Most of the people, over use std::copy without knowing this scenario.
boost::push_back
The third option that you can consider is the use of boost's push_back function.
boost::push_back(a, b);
I needed two different variants of the extend
function in C++14, where one supported move semantics for each element of the vector to be appended.
vec
is your v
, and ext
is your v_prime
.
/**
* Extend a vector with elements, without destroying source one.
*/
template<typename T>
void vector_extend(std::vector<T> &vec, const std::vector<T> &ext) {
vec.reserve(vec.size() + ext.size());
vec.insert(std::end(vec), std::begin(ext), std::end(ext));
}
/**
* Extend a vector with elements with move semantics.
*/
template<typename T>
void vector_extend(std::vector<T> &vec, std::vector<T> &&ext) {
if (vec.empty()) {
vec = std::move(ext);
}
else {
vec.reserve(vec.size() + ext.size());
std::move(std::begin(ext), std::end(ext), std::back_inserter(vec));
ext.clear();
}
}