Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++ STL: Output Container to Stream

📅 2010-Apr-30 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ containers, cpp, stl, streams, vectors ⬩ 📚 Archive

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.