views:

83

answers:

2

Hi all,

I have the following code (just typed it in here, might have typos or stuff):

typedef boost::ptr_vector<SomeClass> tvec;
tvec v;

// ... fill v ...

tvec vsnap;

for(tvec::iterator it = v.begin(); it != v.end(); ++it)
{
   if((*v).anyCondition)
       vsnap.push_back( it ); // (*it) or &(*it) doesn't work
}

My problem is now that i cant push_back an iterator in any way, I just don't get the pointer out of the iterator.

Is there an easy way i didnt see, or are boosts ptr_vector the false choice for this case?

Thanks in advance.

A: 

You need to clone the objects held by the first vector:

for(tvec::iterator it = v.begin(); it != v.end(); ++it)
{
   if((*v).anyCondition)
      vsnap.push_back(new_clone(*it));
}
Joe Gauterin
A: 

Dereferencing a ptr_vector::iterator gives you a reference. Then you can use & to get the address of that reference, so vsnap.push_back(&(*it)) should compile. What error are you getting?

Besides, note that your usage is incorrect. The old ptr_vector owns the object, no matter what you do with the object's address. So with your code you'd have two ptr_vectors owning the same object. Then they would both try to delete it, and you'd crash. You probably want to transfer ownership instead:

vsnap.push_back(v.release(it));

Of course, this removes the object from the old vector before adding it to the new one. If you want the object to stay in both vectors, you can use std::vector or std::vector >. Another alternative is to keep the first one a boost::ptr_vector but make the second one a std::vector that owns nothing and just points to objects in the original vector. Then you would have to be careful with lifetimes.

Stefan Monov