Boost logo

Boost Users :

Subject: Re: [Boost-users] Iterating over the seconds of a list of pairs
From: Björn Karlsson (Bjorn.Karlsson_at_[hidden])
Date: 2009-08-09 12:23:26


...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<std::pair<double,float> > container_type;
  typedef boost::transform_iterator<
    boost::function<float& (container_type::reference)>,
    container_type::iterator> iterator_type;
  
  iterator_type begin()
  {
    return boost::make_transform_iterator(
      container_.begin(),
      boost::bind<float&>(&container_type::value_type::second, _1));
  }

  iterator_type end()
  {
    return boost::make_transform_iterator(
      container_.end(),
      boost::bind<float&>(&container_type::value_type::second, _1));
  }
  
private:
  container_type container_;
};

We use boost::function<float& (container_type::reference)> 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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net