How to use Boost bind library with STL accumulate algorithm

Y

yinglcs

I have a function in STL which add the 'area'
attribute of a list of Rect.



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;
}
}

};

float getTotalAreaPerCent(BlockDataList& bdl) {
return accumulate (bdl.begin(), bdl.end(), 0.0,
add_area_per_cent<BlockData*, float>());
}
Can you please tell me how can I reduce the amount of
code and use Boost bind library to achieve the same
thing?

Thank you.
 
M

Michiel.Salters

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;
}
}

};

float getTotalAreaPerCent(BlockDataList& bdl) {
return accumulate (bdl.begin(), bdl.end(), 0.0,
add_area_per_cent<BlockData*, float>());
}
Can you please tell me how can I reduce the amount of
code and use Boost bind library to achieve the same
thing?

Reduce amount of code:
- Remove ctor, it's not needed.
- Make it a struct, no public: line needed

Boost::bind isn't really a solution.

What would work is a projection iterator. That would be an iterator
wrapper
for a BlockDataList::iterator,with an operator* that returns
m_iter->getAreaPerCent();
In that case, you can simply call the 4-argument form of
std::accumulate.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top