Boost logo

Boost Users :

Subject: [Boost-users] Iterating over the seconds of a list of pairs
From: Zachary Turner (divisortheory_at_[hidden])
Date: 2009-08-08 02:49:16


I have an std::list<std::pair<double, float> > internal to a class.
I'd like to expose begin() and end() functions from this class, that
iterate over the second element of the list. So basically I want the
user of the class to only see a sequence of floats.
transform_iterator seems to fit the bill, but I think I'm seriously
overcomplicating this. I've tried the following and it's not working.
 I feel like this pair_second / pair_first, and iterator should either
already all be defined somewhere that I'm just not aware of, or be
much shorter to write than this.

        template<class First, class Second>
        struct pair_second : public std::unary_function<std::pair<First,
Second>, const Second&>
        {
                const Second& operator()(std::pair<First,Second>& pair) const {
return pair.second; }
        };

        template<class First, class Second>
        struct pair_first : public std::unary_function<std::pair<First,
Second>, const First&>
        {
                const First& operator()(std::pair<First,Second>& pair) const {
return pair.first; }
        };

        template<class pair_type>
        struct first_iterator
        {
                typedef boost::transform_iterator<
                        pair_first<typename pair_type::first_type, typename pair_type::second_type>,
                        typename pair_type
> type;
        };

        template<class pair_type>
        struct second_iterator
        {
                typedef boost::transform_iterator<
                        pair_second<typename pair_type::first_type, typename pair_type::second_type>,
                        typename pair_type
> type;
        };

                typedef typename first_iterator<double_float_pair>::type float_iterator;

                float_iterator begin()
                {
                        return float_iterator(items_.begin(), second_iterator<double_float_pair>());
                }
                float_iterator end()
                {
                        return float_iterator(items_.end(), second_iterator<double_float_pair>());
                }

Any advice would be appreciated.

Thanks
Zach


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