c++ - 如何在没有循环的情况下在C++中总结vector int的 vector

标签 c++ stdvector

我尝试实现对 vector<vector<int>> 的所有元素的总结以非循环方式。
之前查过一些相关问题,How to sum up elements of a C++ vector? .
所以我尝试使用 std::accumulate实现它,但我发现我很难重载 Binary Operatorstd::accumulate并实现它。
所以我很困惑如何用 std::accumulate 来实现它或者,还有更好的方法?
如果不介意有人可以帮助我吗?
提前致谢。

最佳答案

您需要使用 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
    }
);

关于c++ - 如何在没有循环的情况下在C++中总结vector int的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58681103/

相关文章:

c++ - std::weak_ptr 和 std::find 的 std::vector

c++ - 带大括号的 std::vector init 调用复制构造函数两次

c++ - std::vector 的奇怪行为

c++ - 如何格式化此输出 C++

c++ - std::deque<std::string> 有效计算内存中的大小

c++ - 常数乘法的奇怪值

c++ - 如何判断 std::vector 是否调整了自身大小,以及如何解释指向 vector 内值的指针不再有效?

c++ - 构造期间的非常量生成器单遍初始化

c++ - "{"标记之前的预期类名

c++ - 试图了解 "pointer to member"