...and now that we've seen the fundamental mechanics involved in using transform_iterator for this problem, here's a really terse version using two other useful libraries; Boost.Bind and Boost.Function.
1) Write a function object that extracts the second element of the
pair.
2) Use the transform iterator adaptor to provide you with the type of
the iterators for your class.
3) Use the helper function make_transform_iterator in your begin() and
end() methods to create the iterators.
#include <list>
#include <utility>
#include "boost/iterator/transform_iterator.hpp"
#include "boost/function.hpp"
#include "boost/bind.hpp"
class some_class
{
public:
typedef std::list > container_type;
typedef boost::transform_iterator<
boost::function,
container_type::iterator> iterator_type;
iterator_type begin()
{
return boost::make_transform_iterator(
container_.begin(),
boost::bind(&container_type::value_type::second, _1));
}
iterator_type end()
{
return boost::make_transform_iterator(
container_.end(),
boost::bind(&container_type::value_type::second, _1));
}
private:
container_type container_;
};
We use boost::function to parameterize a very general unary function for transform_iterator. Then we use Boost.Bind to create a compatible function object that binds to the member second in std::pair.
The advantages of this approach are that it's short, elegant, and all the logic is locally defined. (It's also quite cool.) However, you must know your audience -- not everyone is comfortable reading and understanding code like this.
Cheers,
Bjorn Karlsson
www.skeletonsoftware.net