Re: using find_if/binary_function
Dilip 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.
it may not be possible in which case i will simply make 2 passes with
the functor. one to find the element and another to locate an empty
slot if the element is not found.
It is possible:
# include <algorithm>
# include <string>
# include <vector>
struct s
{
enum states
{
empty,
used
};
std::string name;
states state;
};
typedef std::vector<s> cont;
// returns an iterator to the element of name
// 'name' or, if it is not found, an iterator to
// the first empty element. if there is none, it
// returns c.end()
//
cont::iterator find(cont& c, const std::string& name)
{
cont::iterator empty_element = c.end();
for (cont::iterator itor=c.begin();
itor!=c.end();
++itor)
{
if (itor->name == name)
return itor;
if ((empty_element == c.end()) &&
(itor->state == s::empty))
{
empty_element = itor;
}
}
return empty_element;
}
Jonathan