C++ STL: Push Back Array into Container

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 ) );

C++ STL: Output Container to Stream

We can output the elements of any container to any ostream using std::copy like this. But, it would be really nice if we could output any vector like this:

std::vector<MyClass> myVec;
std::cout << myVec;

To achieve that, we just need one more wrapper around std::copy, a function template that accepts vectors of any type:

template <typename T>
std::ostream& operator << (std::ostream& os, const std::vector<T>& vec)
{
    std::copy( vec.begin(), vec.end(), std::ostream_iterator<T>( os ) );
    return os;
}

Similar functions can be written for other STL containers.

C++ STL: Output Container Elements to Stream

The std::copy function (defined in <algorithm>) can be used to easily output elements of any STL container to any ostream. To do this, we can use the std::ostream_iterator (defined in <iterator>). std::ostream_iterator can be passed a ostream object and an optional delimiter string.

For example to output a vector of integers to std::cout:

#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>

std::vector<int> iVec;
// ...
std::copy(iVec.begin(), iVec.end(), std::ostream_iterator<int>( std::cout ));
// ...
std::copy(iVec.begin(), iVec.end(), std::ostream_iterator<int>( std::cout, "\n" )); // One integer per line