我尝试实现对 vector<vector<int>>
的所有元素的总结以非循环方式。
之前查过一些相关问题,How to sum up elements of a C++ vector? .
所以我尝试使用 std::accumulate
实现它,但我发现我很难重载 Binary Operator
在 std::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/