I have a container of pointers to objects. The pointers are a base class, and the hierarchy implements a virtual function count(). I want to calculate a sum of count() in the container.
I currently do this with for_each and a lambda function:
size_t sum = 0;
std::for_each(ptrs_.begin(), ptrs_.end(), [&sum](ptr const *p) {
expr += p->count();
});
return sum;
Can anyone help me reimplement this with boost::bind and std::accumulate or other std algorithms?
If you don’t like
auto, or more likely if your compiler doesn’t, then of course you can paste the thing twice, or go looking for the return type ofmem_fun, or capture it using a function template:Then call it as:
Alternately, use the form of
std::accumulatethat takes a binary functor:Instead of writing
AddCount, you could of course use a lambda expression. I expect you can construct it using the stuff in<functional>too, but I’m not going to.I haven’t tested any of this code, so let the error-spotting begin!