Boost logo

Boost Users :

From: Jeff F (TriumphSprint2000_at_[hidden])
Date: 2007-03-02 09:29:56


abir basak wrote:
> Hi,
> In some case I need a iterator which knows its position (index ) in
> the container, so that I can get the index back from iterator.
> The need is two fold.
> 1) This is needed for simultaneous traversal to different container.
> i.e i have vector<point> and vector<velocity> where each point
> corresponds to velocity at same position. Thus converting the iterator
> to the index helps.

Since your dealing with random access iterators, std::distance( c.begin(),
itr ) gives you that in constant time doesn't it, at least when you have
access to the container.

> But even better if I have a multi iterator, which can club a set of
> iterators, and allow to return all of them (like (*it).point() returns
> point, (*it).velocity() returns velocity etc. Also it defines ++, --
> etc the same way (i.e increments all these, or one in a logic , say
> next point is a jump in velocity by 2 etc), so that I can use
> boost::sub_range for these kind of iterator.

Doesn't http://www.boost.org/libs/iterator/doc/zip_iterator.html do what you
want?

> 2) I need to convert iterator to index, as I need to store certain
> portion of a container (which changes its size) in a class. There I
> can only store index as iterator may get invalidated.
> It is something like,
> void mark_if_useful(point_sub_range r){///an portion of the
> container point_iterator it = r.begin();
> for(; it != r.end() ; ++it){
> if ((*it).x == 123 ) {
> ///ok certain criterion is fulfilled
> ///I need to mark (ans store tis position)

    std::size_t idx = std::distance( r.begin(), it );

> ///I can't store *it as it is a pointer to a movable object
> ///However I can store (*it).index() may be it is 5th
> location in the vector, and (*it)>container() also the
> reference to the container
> ///may not be needed if the container is globally available.
> ///if some object also gets removed the the remove count from the
> container can be added to have a unique linear index (that can me done
> adding additional method to the container :) )
> }
> }
> }

Jeff


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