如何应用std :: accumulate算法的联想容器? [英] How to apply std::accumulate algorithm for associative containers?

查看:244
本文介绍了如何应用std :: accumulate算法的联想容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于像std :: map的地图,我如何积累它的值的总和?

其实,我做了一个函数和std :: for_each算法。但我也想使用std :: accumulate算法。

我不知道如何应用它到std :: map。

这是可能吗? / p>

For a map like std::map, how do I accumulate it's values' sum?
Actually, I made it with a functor and std::for_each algorithm. But I'd also like to make this using std::accumulate algorithm.
I have no idea how to apply it to std::map.
Is this even possible?

struct Accumurator
    : std::unary_function<std::pair<int, int>, void>
{
    Accumurator()
        : totalValue_(0)
    {
    } 

    void operator()(const std::pair<int, int>& p)
    {
        totalValue_ += p.second;
    }

    int result() const
    {
        return totalValue_;
    }

    int totalValue_; 
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::map<int, int> m;
    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 10));
    m.insert(make_pair(3, 10));
    m.insert(make_pair(4, 10));
    m.insert(make_pair(5, 10));
    m.insert(make_pair(6, 10));

    int totalSum = std::for_each(m.begin(), m.end(), Accumurator()).result();

    // How can I apply accumulate algorithm for associative containers.
    // int totalSum = accumulate(m.begin(), m.end(), ???);

    return 0;
}


推荐答案

函数必须是一个二进制运算符,它将返回值类型作为第一个参数,并将范围类型作为第二个参数:

Almost. The functor must be a binary operator taking the return value type as the first and the range type as the second argument:

x = Functor(init, *it++);
x = Functor(x, *it++);
x = Functor(x, *it++);
// ... until it == end

有状态函数,一个简单的函数会做:

So you don't need a stateful functor at all, a simple function will do:

int map_acc(int lhs, const std::pair<int, int> & rhs)
{
  return lhs + rhs.second;
}

const int sum = std::accumulate(m.begin(), m.end(), 0, map_acc);

这篇关于如何应用std :: accumulate算法的联想容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆