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

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

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

  • 相关阅读:
    go websocket
    go websocket 调试报错 request origin not allowed by Upgrader
    uniapp中使用阿里巴巴图标iconfont
    TS视频一
    ReactiveCocoa
    weak 的内部实现原理
    谈Objective-C block的实现
    基础面试总结
    理解 iOS 的内存管理
    URL Scheme
  • 原文地址:https://www.cnblogs.com/zhuzhenwei918/p/8849644.html
Copyright © 2011-2022 走看看