Sometimes it is useful to be able iterate over all the elements of a std::map using standard algorithms like std::copy(), std::count(), std::min_element(), std::max_element(). These standard functions do not work out of the box using std::map::iterator. For example, if you want to print all the elements of a map to standard output, you can’t use the following popular copy-ostream_iterator idiom.
std::map <:string int=""> m;
std::copy (m.begin(), m.end(), std::ostream_iterator(std::cout, “\n”));
// does not compile
This is because value_type of the map::iterator is a pair. In other words, if iter is a map::iterator then *iter gives pair and not U. If we could somehow get hold of pair::second (i.e. type U) instead of pair all the above mentioned algorithms can be used out of the box.
The approach I took to solve this problem is to write an iterator adaptor that behaves likes any general bidirectional_iterator. In general, this approach allows map iterators to be used wherever Iterator-Pair idiom is useful. The code given below is kind of long but quite straight forward and idiomatic in nature.