zoukankan      html  css  js  c++  java
  • c++三维静态数组的定义与作为函数的传递

      在c++中,我们可以定义三维数组,并且可以将之作为参数直接传递。

      定义:

    #include <iostream>
    #include <windows.h>
    using namespace std;
    const int x = 10;
    const int y = 10;
    const int z = 10;
    int main() {
        double foo[x][y][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                for (int k = 0; k < z; k++) {
                    foo[i][j][k] = 1.0;
                }
            }
        }
        cout << foo[0][0][0] << endl; // 1.0
        system("pause");
        return 0;
    }

      如上所示,我们设置的是静态数组,所以必须在定义三维数组之前确定其大小,为了程序的可维护性,建议使用const int进行定义。

      将三维数组作为参数传递:

    #include <iostream>
    #include <windows.h>
    using namespace std;
    const int x = 10;
    const int y = 10;
    const int z = 10;
    int bar(double arr[][y][z]);
    int main() {
        double foo[x][y][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                for (int k = 0; k < z; k++) {
                    foo[i][j][k] = 1.0;
                }
            }
        }
        cout << foo[0][0][0] << endl; // 1.0
        bar(foo);
        system("pause");
        return 0;
    }
    int bar(double arr[][y][z]) {
        cout << "function invoked value: " << arr[1][1][1] << endl;
        return 0;
    }

      如上所示,最终结果为:

    1
    function invoked value1

      注意,在传递三维数组作为参数时,数组的第一个[]中为空,而第二第三个不能为空。

      这样,对于大部分情况下的三维数组就可以轻松处理了。

  • 相关阅读:
    129. Sum Root to Leaf Numbers
    113. Path Sum II
    114. Flatten Binary Tree to Linked List
    112. Path Sum
    100. Same Tree
    300. Longest Increasing Subsequence
    72. Edit Distance
    自定义js标签库
    JS 实现Table相同行的单元格自动合并示例代码
    mysql 高版本only_full_group_by 错误
  • 原文地址:https://www.cnblogs.com/zhuzhenwei918/p/8849644.html
Copyright © 2011-2022 走看看