正如我的评论所述,一种解决方案是认识到二维数组的数据布局位于连续内存中。因此,获取最小值、最大值和总和变得简单,因为您将以与一维数组相同的方式遍历二维数组。
这是使用C++算法函数的解决方案。
#include <algorithm>
#include <iostream>
#include <numeric>
int main()
{
int a[5][5] = {
{0,4,6,3,5},
{7,1,5,6,2},
{6,8,8,5,2},
{4,1,5,2,2},
{4,3,6,5,9} };
// Get both the position of the minimum and maximum element in the array
auto pr = std::minmax_element(&a[0][0], &a[4][5]);
// add up all elements between the min and max elements
int answer = std::accumulate(std::next(pr.first), pr.second, 0);
// output results
std::cout << answer;
}
Output:
100
是的,这就是整个代码。
那么做了什么?
首先,我们使用std::minmax_element https://en.cppreference.com/w/cpp/algorithm/minmax_element从指向第一个元素的指针开始遍历数组(&a[0][0]
) 传递给最后一个元素 (&a[4][5]
)。请注意该函数的参数——它起作用的原因是二维数组具有我之前提到的连续布局。因此,只需弄清楚起始位置和结束位置即可。
返回值std::minmax_element
is a std::pair<int*, int*>
指向最小元素(first
)和最大元素(second
)。这就是pr
表示。
完成后,我们可以使用以下命令快速添加最小和最大元素之间的项目std::累积 https://en.cppreference.com/w/cpp/algorithm/accumulate根据我们的指示pr
.
请注意,第一个参数std::accumulate
是找到最小值后的下一个值。这就是原因std::next
在第一个参数中——它将我们带到下一个值。