adapter to convert any iterator to random access iterator

719 views Asked by At

I have any container that does not provide random access iterators and the goal is to create an adapter that takes input such iterators and provide random access iterator interface to the container.

I am not sure how to use boost::iterator_facade as it is a bit confusing :-/ there are some examples on stack overflow but I am not sure how to use them ( here )

Any link/example could be helpful. (i read the examples in the boost they are a bit hard to digest considering my experience in boost

1

There are 1 answers

1
sehe On

You don't want to do this.

Either

  • Use a generalized range library with facilities to do "on the fly" caching, like Eric Niebler's Container Ranges concept from his Ranges proposal
  • explicitly code the intent, e.g. by creating a tag dispatched overload for your function that "reifies" an input range into a temporary container for random-access algorithms

If you really insist, yes you can probably implement your idea, but I don't see what it gains except hiding the runtime/storage cost. Especially, it won't be trivial with the need to keep lifetime around.¹


Slightly related: Boost Spirit has a boost::spirit::multi_pass adapter but that only upgrades from InputIterator to ForwardIterator (to allow backtracking).

¹ (What do you do when you have a temporary that's already a random access range? You cannot keep a reference to it, but you should also not unnecessarily copy it.)