如何在没有循环的C ++中总结vector int的向量

Bow*_*eng 4 c++ stdvector

我尝试以vector<vector<int>>非循环的方式实现对a的所有元素的总结。
之前,我已经检查了一些相关的问题,如何总结C ++向量的元素?
因此,我尝试使用std::accumulate它来实现它,但是我发现很难重载Binary Operatorin std::accumulate并实现它。
因此,我对如何实现它感到困惑,std::accumulate还是有更好的方法?
如果不介意有人可以帮助我吗?
提前致谢。

Shl*_*oim 7

您需要使用std::accumulate两次,一次是vector使用二进制运算符表示外部函数,该运算符知道如何vector通过使用额外的调用来求和内部函数std::accumulate

int sum = std::accumulate(
    vec.begin(), vec.end(),                       // iterators for the outer vector
    0,                                            // initial value for summation - 0
    [](int init, const std::vector<int>& intvec){ // binaryOp that sums a single vector<int>
        return std::accumulate(
            intvec.begin(), intvec.end(), // iterators for the inner vector
            init);                        // current sum
                                          // use the default binaryOp here
    }
);
Run Code Online (Sandbox Code Playgroud)


Gil*_*llé 5

在这种情况下,我不建议使用,std::accumulate因为这会大大降低可读性。而且,此函数在内部使用循环,因此您将不会保存任何内容。只需将以下基于循环的解决方案与使用的其他答案进行比较std::accumulate

int result = 0 ;
for (auto const & subvector : your_vector)
    for (int element : subvector)
        result += element;
Run Code Online (Sandbox Code Playgroud)

结合使用迭代器,STL函数和lambda函数是否会使您的代码更容易理解和更快?对我来说,答案很明确。循环并不是邪恶的,特别是对于这种简单的应用程序。