My question is a small generalization of this . For discussion, I will focus on iterating over the map keys. I would like to have a general helper function, key_iteratorwhich takes a map iterator and returns a map key iterator. For example, the following code:
#include "key_iterator.hpp"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
int main(int argc, char** argv)
{
std::map<std::string, int> m;
m["One"] = 1;
m["Two"] = 2;
std::copy(key_iterator(m.begin()), key_iterator(m.end()), std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}
should output the following result:
One Two
As suggested in the solution to the above question, boost :: transform_iterator seems to be a suitable starting point for the implementation key_iterator. I have a halfway solution that looks like this for key_iterator.hpp:
#pragma once
#include <functional>
#include <map>
#include <boost/iterator/transform_iterator.hpp>
template <typename Key, typename Value>
class KeyGetter : public std::unary_function<std::pair<Key,Value>, Key>
{
public:
const Key& operator()(const std::pair<Key,Value>& p) const {return p.first;}
};
template<typename Key, typename Value>
boost::transform_iterator<KeyGetter<Key,Value>, typename std::map<Key,Value>::iterator>
key_iterator(typename std::map<Key,Value>::iterator itr)
{
return boost::make_transform_iterator<KeyGetter<Key,Value>, typename std::map<Key,Value>::iterator>(itr, KeyGetter<Key,Value>());
}
but with this implementation, the Key and Value types are not automatically output, and I need to manually provide them in order to compile:
std::copy(key_iterator<std::string,int>(m.begin()), key_iterator<std::string,int>(m.end()), std::ostream_iterator<std::string>(std::cout, " "));
Any thoughts on how to do this the way I want?