Tip of the Day: Generic Containers

by Scott MacDonald on June 29th, 2011
No CommentsComments

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();
}
#include <vector>
#include <iostream>

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

Categories: C++, Programming, Tip