Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++ STL: Push Back Array into Container

📅 2010-Jul-11 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ arrays, containers, cpp, stl ⬩ 📚 Archive

Pushing the elements of an array into the back of a STL container, in a single statement, is easy using the STL std::copy algorithm. This algorithm relies on the destination having enough space to hold the source elements. So, a convenient way to apply it on a container without allocating the required space is to use a std::back_inserter. This works on all containers that have a push_back method: vector, list and deque.

#include <algorithm>
#include <iterator>
std::copy( fooArray, fooArray + ARRAY_SIZE, std::back_inserter( fooVector ) );