Bar*_*yne 11 c++ multidimensional-array stl-algorithm c++11 c++14
给定二维数组
std::array<std::array<int, 2>, 3> m = {{ {1, 2}, {3, 4}, {5, 6} }};
Run Code Online (Sandbox Code Playgroud)
我正在寻找所有元素的总和 - 在这种情况下,21.如果数组是一维的,我可以写
auto sum = std::accumulate(m.begin(), m.end(), 0);
Run Code Online (Sandbox Code Playgroud)
但对于我的二维数组,这失败了,这是一个可以理解的错误
no match for 'operator+' (operand types are 'int' and 'std::array<int, 2ul>')
Run Code Online (Sandbox Code Playgroud)
我怎样才能优雅地为我的2D数组计算这个总和(避免for循环,更喜欢STL算法)?
是否可以像一维情况一样使用单线,或者它变得更复杂?
Rak*_*111 19
它只是有点复杂.你必须嵌套2个std::accumulate电话.嵌套std::accumulate调用对嵌套数组中的元素求和,然后第一个std::accumulate将它们相加.
auto sum = std::accumulate(m.cbegin(), m.cend(), 0, [](auto lhs, const auto& rhs) {
return std::accumulate(rhs.cbegin(), rhs.cend(), lhs);
});
Run Code Online (Sandbox Code Playgroud)
由于泛型lambda,这是一个C++ 14解决方案,但对于C++ 11,您只需要明确指定类型.
从概念上讲,您希望展平数组m,然后对其应用累积.
使用Range-v3库(或将来的Ranges TS)就可以做到这一点(链接到wandbox).
std::array<std::array<int, 2>, 3> m = {{ {1, 2}, {3, 4}, {5, 6} }};
auto result = ranges::accumulate(ranges::join(m), 0); // flatten range then apply accumulate
Run Code Online (Sandbox Code Playgroud)
这就像Pete Becker在评论中提到的那样:"遍历数组的一行,当它到达行的末尾时,移动到下一行".没有制作子范围的副本.
| 归档时间: |
|
| 查看次数: |
1320 次 |
| 最近记录: |