views:

84

answers:

1

I have a vector of pointers to objects. I'd like to remove objects from this vector according to an attribute that's reported by a member function.

I'm trying to follow a nice example I found on how to delete certain pointers (and their associated objects) from the vector. The basic idea is to partition the vector, delete the chosen objects, and then delete the pointers to those objects. Below is the example (from Dr. Dobbs):

vector<Object *> v ;

v.push_back( new Object( ... ) ) ;
...
vector<Object *>::iterator last =
partition( v.begin(), v.end(), not1(predicate()) ) ;
for( vector<Object *>::iterator i = last ; i != v.end() ; ++i )
{
  delete *i ;
}
v.erase( last, v.end() ) ;

I'm stumped on the proper syntax for the predicate. My objects are of class Strain, and my vector is vector< Strain * > liveStrains. The predicate should be the Strain member function isExtinct(). The following doesn't work:

 vector< Strain * >::iterator last = partition( liveStrains.begin(), liveStrains.end(), not1(std::mem_fun_ref(&Strain::isExtinct)) );

I can see that I am trying to invoke a member function on a pointer to the object rather than the object itself. To get around this, tried changing the & to * (I'm obviously a newbie), and I tried creating a member function for the class Simulation that does the liveStrains updating in a member function. I'm not sure it's worth going into the details of what didn't work. I'm severely confused by the syntactical options available, or if what I'm trying to do is even allowed.

Thanks in advance for any help.

+1  A: 

The solution is to use std::mem_fun, which is made for pointers to objects, rather than std::mem_fun_ref.

Sarah