Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-02-14 16:27:44


yinglcs2_at_[hidden] wrote:
> I have a function in STL which add the 'area'
> attribute of a list of Rect.
>
> float getTotalAreaPerCent(BlockDataList& bdl) {
> return accumulate (bdl.begin(), bdl.end(), 0.0,
> add_area_per_cent<BlockData*, float>());
> }
>
> template< class T1, class T2> class add_area_per_cent
>> public binary_function<T2, T1, T2>
> {
> public:
> add_area_per_cent() { }
>
> T2 operator() (T2 initial, T1 element) {
> if (element != NULL) {
> return initial + element->getAreaPerCent();
> } else {
> return initial;
> }
> }
>
> };
>
> Can you please tell me how can I reduce the amount of
> code and use Boost bind library to achieve the same
> thing?

You can't simplify your code any further by using Bind, since your function
object doesn't hold any state. You can use the simpler function object:

struct add_area_per_cent
{
    float operator()( float initial, BlockData* element ) const
    {
        return element? initial + element->getAreaPerCent(): initial;
    }
}

or function:

float add_area_per_cent( float initial, BlockData* element )
{
    return element? initial + element->getAreaPerCent(): initial;
}

if you don't need the genericity, but your code is fine as it is.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net