简体   繁体   English

如何使用std算法重新实现这一点?

[英]How to reimplement this with std algorithms?

I have a container of pointers to objects. 我有一个指向对象的容器容器。 The pointers are a base class, and the hierarchy implements a virtual function count() . 指针是基类,层次结构实现虚函数count() I want to calculate a sum of count() in the container. 我想计算容器中count()的总和。

I currently do this with for_each and a lambda function: 我目前使用for_each和lambda函数执行此操作:

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? 任何人都可以帮我用boost::bindstd::accumulate或其他std算法重新实现这个吗?

auto getcount = std::mem_fun(&Base::count); // nothing to bind, we just need a functor

size_t sum = std::accumulate(
    boost::make_transform_iterator(ptrs_.begin(), getcount),
    boost::make_transform_iterator(ptrs_.end(), getcount),
    (size_t)0
);

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 of mem_fun , or capture it using a function template: 如果你不喜欢auto ,或者你的编译器不喜欢,那么当然你可以粘贴两次,或者去寻找mem_fun的返回类型,或者使用函数模板捕获它:

template <typename IT, typename FUNC, typename T>
T transform_accumulate(IT first, IT last, T init, FUNC func) {
    return std::accumulate(
        boost::make_transform_iterator(first, func),
        boost::make_transform_iterator(last, func),
        init
    );
}

Then call it as: 然后将其称为:

transform_accumulate(ptrs_.begin(), ptrs_.end(), size_t(), std::mem_fun(&Base::count));

Alternately, use the form of std::accumulate that takes a binary functor: 或者,使用带有二元仿函数的std::accumulate形式:

struct AddCount {
    size_t operator()(size_t result, Base *p) const {
        return result + p->count();
    }
};

size_t sum = std::accumulate(ptrs_.begin(), ptrs_.end(), size_t(), AddCount());

Instead of writing AddCount , you could of course use a lambda expression. 您可以使用lambda表达式,而不是编写AddCount I expect you can construct it using the stuff in <functional> too, but I'm not going to. 我希望你也可以使用<functional>的东西构建它,但我不会这样做。

I haven't tested any of this code, so let the error-spotting begin! 我没有测试过这些代码,所以让错误发现!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM