c++ - 如何为关联容器应用 std::accumulate 算法?

标签 c++ algorithm visual-studio-2008 stl map

对于像 std::map 这样的映射,我如何计算它的值总和?
实际上,我是用仿函数和 std::for_each 算法实现的。但我也想使用 std::accumulate 算法来实现。
我不知道如何将它应用到 std::map。
这可能吗?

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

最佳答案

差不多。仿函数必须是二元运算符,第一个参数是返回值类型,第二个参数是范围类型:

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

所以你根本不需要有状态的仿函数,一个简单的函数就可以了:

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

关于c++ - 如何为关联容器应用 std::accumulate 算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6935118/

相关文章:

python - 缺少一个约束的约束满足问题

c++ - 平方根算法 C++

c++ - wxWidgets编译错误( fatal error LNK1120 : 26 unresolved externals)

c++ - C和C++的编译区别

c++ - 将 C++ HelloWorld 国际象棋引擎代码转换为 C 代码失败

c++ - Qt->QGraphicsView->QGraphicsItem 调整大小

c - 如何用自定义字符串快速填充缓冲区?

c++ - 带有 C++11 的 Visual Studio 2008

visual-studio - 双击文件时如何强制 Visual Studio 2008 使用 Open 实例?

c++ - 使用 __gnu_pbds 为多重集排序统计树