Tuesday, July 31, 2012

C++ std::list Chop off end of list

A little code here.

I have a list of X,Y,Goodness values.  I want to randomly select one entry from the top Goodness entries with some leeway for what 'top goodness' is.

  // Now sort the list by goodness, largest goodness at front.
  fits.sort(compare_PlacementRule_goodness);

  // Keep entries within a certain closeness to the maximm value.
  BuildingRect::xyPairGoodness & pg = fits.front();
  float topval = pg.goodness - r->m_placementRuleAllowance;
  // If topval is negative then no elements will get cut out.
  if(topval > 0.0f)
  {
    for(std::list<BuildingRect::xyPairGoodness>::iterator it = fits.begin(); it != fits.end(); ++it)
    {
      float g = it->goodness;
      if(g < topval)
      {
        // Cut rest of list off.
        fits.erase(it, fits.end());
        break;
      }
    }
  }


and the compare is

bool compare_PlacementRule_goodness(BuildingRect::xyPairGoodness first, BuildingRect::xyPairGoodness second)
{
  // We want the highest positive goodness at the top of the list.
  if (first.goodness > second.goodness) 
  {
    return true;
  }
  else 
  {
    return false;
  }
}

And as usual the greater than and less than symbols get munged.

TF

No comments: