Printing Generic C++ Containers

Always wanted a simple utility function to print our an arbitrary STL container? Well, so long as your container type support directional iterators… this method I wrote will work perfectly! Its a great example for why templates are awesome

#include <sstream>

template<typename T>
std::string dumpContainer( const T& container, std::string sep )
{
    typename T::const_iterator itr;
    std::stringstream sstream;

    for ( itr = container.begin(); itr != container.end(); ++itr )
    {
        // insert a seperator char for all but the first element
        if ( itr != container.begin() )
        {
            sstream << sep;
        }

        sstream << *itr;
    }

    return sstream.str();
}

And now how to use the function:

#include <vector>
#include <iostream>

int main( int argc, char* argv[] )
{
    std::vector<int> values = { 1, 2, 3, 5 };
    std::cout << dumpContainer( values, ", " ) << std::endl;
}