gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:50:36 25 4
gpt4 key购买 nike

我尝试实现对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com