
yinglcs2@yahoo.com 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
()); } public binary_function
{ template< class T1, class T2> class add_area_per_cent 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.