An Insignificant Comment First
You might change your accessor function to the simpler form
return unitCode == uCode;
Now To What We're Here For
You're better off looking for the position of the element rather than its index. Getting an element from its index is an O(n) operation, whereas getting an element from its position is an O(1) operation. So, with the STL and a little help from boost::bind()
:
#include <algorithm>
#include <boost/bind.hpp>
// ...
std::string uCode("uCode to search for");
std::list<Unit*>::iterator pos = std::find_if(unitCollection.begin(),
unitCollection.end(),
boost::bind(&Unit::isUnit,
_1, uCode));
The STL does have std::mem_fun()
, which, along with std::bind2nd()
would give the same result. The problem is that mem_fun()
only works with member functions that take no arguments. boost::bind()
on the other hand is much more powerful, and does solve the problem here very nicely. You should expect it in the next standard, which should be here immediately after the Messiah arrives.
But If You Don't Have Boost
If don't already have boost in your project then you really, really should install it. If the standard library is C++'s wife, then Boost is C++'s young lover. They should both be there, they get along fine.
Having said that, you can extract the function into a standalone function object as Peter mentioned already:
struct has_uCode {
has_uCode(cont std::string& uc) : uc(uc) { }
bool operator()(Unit* u) const { return u->isUnit(uc); }
private:
std::string uc;
};
Then, you can call std::find_if()
like so:
std::list<Unit*>::iterator pos = std::find_if(unitCollection.begin(),
unitCollection.end(),
has_uCode("this and that"));
And a Little Bit of Performance Consideration
One more thing: I don't know how uCode's look like, but if they're big then you might speed things up by maintaing hashes of these strings so that in your search predicate you only compare the hashes. The hashes might be regular integers: comparing integers is pretty fast.
One more one-more-thing: If you run this search procedure often you might also consider changing your container type, because this really is an expensive procedure: in the order of the list's length.