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 ?

3
  • It works if you say --xlast; instead of advance... for me, the advance version is stuck in an infinite loop.
    – Kerrek SB
    Jan 9, 2012 at 1: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 9, 2012 at 2:08
  • All the large dynamic advances I have are for positive distances, so this is practical workaround. Thank You.
    – JonT
    Jan 10, 2012 at 2:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.