2

I'm using a transform_iterator to access keys (and separately values) of a map.

But it seems that it is not preserving the bi-directionality of std::map::iterator ...

#include <map>

#include <iterator>
#include <assert.h>

#include <boost/iterator/transform_iterator.hpp>


typedef std::map<int,int> map;

template <typename Pt>
struct XFunc
{
    typedef typename Pt::first_type result_type;

    result_type& operator()(const Pt &p) { return p.first; }
};
typedef XFunc<map::value_type> xfunc;
typedef boost::transform_iterator<xfunc,map::iterator>  XIt; 

int main(int argc, char* argv[])
{
    map data;

    for (int i = 0; i < 10; ++i )
    {
        map::value_type pt( i, i * 2 );
        data.insert( pt );
    }

    map::iterator itend = data.end();

    map::iterator itlast = itend;
    std::advance(itlast,-1);

    assert(itend != itlast);  // succeeds !

    XIt xend = boost::make_transform_iterator(itend,xfunc());

    XIt xlast = xend;
    std::advance(xlast,-1);

    assert(xend != xlast); // fails !

    return 0;
}

What am I doing wrong ?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
JonT
  • 502
  • 4
  • 13
  • It works if you say `--xlast;` instead of `advance`... for me, the `advance` version is stuck in an infinite loop. – Kerrek SB Jan 09 '12 at 01:57
  • Hm, in GCC 4.6.2, the iterator is wrongly classified as an input iterator, and not a bidirectional iterator, so it gets into the infinite loop `while (__n--)`, where `n = -1`. The bidirectional version branches on the sign of `__n`, so that'd be the desirable one. – Kerrek SB Jan 09 '12 at 02:08
  • All the large dynamic advances I have are for positive distances, so this is practical workaround. Thank You. – JonT Jan 10 '12 at 02:17

0 Answers0