Pages

Printing map not using ostream_iterator

My simple dumping function for containers has a few limitations, the worst of them probably is that it doesn't work for maps.

The fact is maps are based on std::pair, no "put to" operator on ostream is defined for it in the std namespace, but ostream_iterator really needs it there to do its job.

So I have taken a different approach. Instead of using the standard copy() algorithm coupled with ostream_iterator, I'm using here for_each() and I'll add a local "put to" operarator definition for my pair.

Here is my new version of the function:

template <typename InputIterator>
inline void dump(std::ostream& os, InputIterator begin, InputIterator end,
const char* const delimiter = " ")
{
typedef std::iterator_traits<InputIterator>::value_type T;
std::for_each(begin, end, [&] (T t) { os << t << delimiter; } );
}

I have used a lambda function to keep the code sleek and compact. If you compiler does not allow lambda yet, you can use the boost implementation.

The overload for "normal usage" on standard output has not changed:

template <typename InputIterator>
inline void dump(InputIterator begin, InputIterator end)
{
dump(std::cout, begin, end);
std::cout << std::endl;
}

As also the overload for dumping all the items in the container stays the same:

template <typename Container>
inline void dump(const Container& c) { dump(c.begin(), c.end()); }

Given this new version of dump(), I define a map and a operator "put to" working for its undelying pair:

typedef std::map<int, int> MII;
typedef MII::value_type MII_VT;
std::ostream& operator<<(std::ostream& s, const MII_VT& p)
{
return s << '(' << p.first << ", " << p.second << ')';
}

And here is a sample code for testing:

MII mii;
for(int i = 0; i < 10; ++i)
mii[i] = i * i;

dump(mii);

No comments:

Post a Comment