In article <11*********************@u72g2000cwu.googlegroups. com>,
"Dilip" <rd*****@lycos.com> wrote:
Daniel T. wrote: You are just looking for the first place to put something right?
find_if( vec.begin(), vec.end(), is_available() );
struct is_available : unary_function< no_op, bool >
{
bool operator()( const no_op* o ) const {
bool result = false;
if ( !o || o->my_name == "EMPTY_SLOT" )
result = true;
return result;
}
};
Daniel
Thanks for your efforts.
Actually I am trying to:
1) locate an element first
2) if that element is not found, find first empty slot
3) if empty slot is also not found, don't bother with anything in the
functor -- the client will simply add a new element in to the vector.
i want to do all of this in one pass.
If you use the above functor, that will happen as a matter of course.
Think about it, the vector starts with all NULLs so the functor will
return the 1st slot. The second time through, it will either return the
first slot (if "EMPTY_SLOT" is true) or the 2nd slot (if "EMPTY_SLOT" is
false on the first element.)
i would never have a need to check with pointer validity (!o) because I
have arranged for my pointers to always be valid with some zombie state
to differentiate them from objects with real state.
Well, I'm not so sure how useful that is, but I thought "EMPTY_SLOT" was
the zombie state. OK, I see what you want. This can work if you move all
the EMPTY_SLOTs to the back of the container first.
struct has_name_or_empty : unary_function< no_op, bool >
{
string name;
has_name_or_empty( const string& name_ ): name( name_ ) { }
bool operator()( const no_op* o ) const {
return o->my_name == "EMPTY_SLOT" || o->my_name == name;
}
};
remove( vec.begin(), vec.end(), has_name_or_empty( "EMPTY_SLOT" ) );
find_if( vec.begin(), vec.end(), has_name_or_empty( theName ) );
That will move all the "empty" elements to the end then get what you
want. However, this is effectively going through the container twice.
There is probably something you can do with for_each, you are allowed to
use statefull functors in it... However, it's sounding like you should
just write your own algorithm:
template < typename FwIt >
FwIt find_name_or_empty( FwIt first, FwIt last, const string& name )
{
typename FwIt candidate = last;
while ( first != last ) {
if ( (*first)->my_name == name ) return first;
if ( candidate == last && (*first)->my_name == "EMPTY_SLOT" )
candidate = first;
++first;
}
return candidate;
}
You might want to work to make that a little more generic.