1.在 C++ 中,你可以通过嵌套循环来对三维数组的所有元素求和。以下是一个示例程序,展示了如何实现这一功能:
#include <iostream>
using namespace std;
int main() {
// 定义一个三维数组
const int x = 2, y = 3, z = 4;
int array[x][y][z] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
// 初始化求和变量
int sum = 0;
// 使用嵌套循环遍历所有元素并求和
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
for (int k = 0; k < z; ++k) {
sum += array[i][j][k];
}
}
}
// 输出结果
cout << "三维数组所有元素的和为: " << sum << endl;
return 0;
}
2.使用 std::vector
定义一个三维数组,并利用内置的 std::accumulate
函数来对所有元素求和是可以实现的。以下是一个示例程序,展示了如何实现这一功能:
#include <iostream>
#include <vector>
#include <numeric> // 包含 std::accumulate
using namespace std;
int main() {
// 定义一个三维 vector 数组
vector<vector<vector<int>>> array = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
// 将三维数组展平为一维数组
vector<int> flat_array;
for (const auto& matrix : array) {
for (const auto& row : matrix) {
flat_array.insert(flat_array.end(), row.begin(), row.end());
}
}
// 使用 std::accumulate 计算和
int sum = std::accumulate(flat_array.begin(), flat_array.end(), 0);
// 输出结果
cout << "三维数组所有元素的和为: " << sum << endl;
return 0;
}