I need help with making this bit of code faster:
UnitBase* Formation::operator[](ushort offset)
{
UnitBase* unit = 0;
if (offset < itsNumFightingUnits)
{
ushort j = 0;
for (ushort i = 0; i < itsNumUnits; ++i)
{
if (unitSetup[i] == UNIT_ON_FRONT)
{
if (j == offset)
unit = unitFormation[i];
++j;
}
}
}
else
throw NotFound();
return unit;
}
So, to give some background, I have this class Formation
which contains an array of pointers to UnitBase
objects, called UnitFormation
. The UnitBase*
array has an equally sized array of numbers that indicate the status of each corresponding UnitBase object, called UnitSetup
.
I have overloaded the []
operator so as to return only pointers to those UnitBase objects that have a certain status, so if I ask for itsFormation[5]
, the function does not necessarily return UnitFormation[5]
, but the 5th element of UnitFormation that has the status UNIT_ON_FRONT
.
I have tried using the code above, but according to my profiler, it is taking way too much time. Which makes sense, since the algorithm has to count all the elements before returning the requested pointer.
Do I need to rethink the whole problem completely, or can this be made somehow faster?
Thanks in advance.