Code snippets‎ > ‎C++‎ > ‎Boost‎ > ‎

Iterators

Adaptor_iterator

The following snippet creates an iterator over the values of an std::map (like if it would be a vector or list):
#include <iostream>
#include <map>
#include <string>
 
#include <boost/iterator/transform_iterator.hpp>
 
template <class Pair>
class select1st {
public:
    typedef Pair argument_type;
    typedef typename Pair::first_type result_type;
 
    result_type operator()(const argument_type &arg) const { return arg.first; }
};
 
template <class Pair>
class select2nd {
public:
    typedef Pair argument_type;
    typedef typename Pair::second_type result_type;
 
    result_type operator()(const argument_type &arg) const { return arg.second; }
};
 
int main(int argc, char *argv[]) {
    typedef std::map<std::string, int> Map;
    typedef select2nd<Map::value_type> Transform;
    typedef boost::transform_iterator< Transform, Map::iterator > list_iterator;
 
    Map map;
    map["one"] = 1;
    map["two"] = 2;
    map["three"] = 3;
 
    list_iterator it(boost::make_transform_iterator(map.begin(), Transform()));
    list_iterator end(boost::make_transform_iterator(map.end(), Transform()));
 
    std::copy(it, end, std::ostream_iterator<int>(std::cout, "\n"));
 
    return 0;
}
Comments