【问题标题】:Passing 2d array c++传递二维数组 C++
【发布时间】:2016-05-23 14:40:00
【问题描述】:

我正在尝试制作一个交换两列的小程序,我必须使用函数才能做到这一点,但我刚开始使用 c++,我无法理解我做错了什么。

#include <iostream>

using namespace std;

int colSwap(int ng, int ns, int pin[][ns]) {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 4; ++j) {
            cout << " i:" << i << " j:" << j << " " << pin[i][j] << " " << endl;
        }
        cout << endl;
    }
}

int main() {

    int ng = 3;
    int ns = 4;

    int pin[3][ns] = {{1, 2,  3,  4},
                     {5, 6,  7,  8},
                     {9, 10, 11, 12}};


    colSwap(ng,ns,pin);
    return 0;
}

我知道这样写

int colSwap(int pin[][4]) {

}

但我需要另一种方法

【问题讨论】:

标签: c++ arrays function


【解决方案1】:

虽然可以像在 C 中那样传递大小,但在 C++ 中是不可能的。原因是 C++ 没有variable-length arrays。 C++ 中的数组必须在编译时固定其大小。不,使大小参数const 不会使它们成为编译时常量。

我建议您改用std::array(或可能的std::vector)。

【讨论】:

    【解决方案2】:

    你可以使用模板函数

    #include <iostream>
    
    using namespace std;
    
    template <size_t R, size_t C>
    void colSwap(int(&arr)[R][C]) {
        for (int i = 0; i < R; ++i) {
            for (int j = 0; j < C; ++j) {
                cout << " i:" << i << " j:" << j << " " << arr[i][j] << " " << endl;
            }
            cout << endl;
        }
    }
    
    int main() {
    
        const int ng = 3;
        const int ns = 4;
    
        int pin[ng][ns] = {{1, 2,  3,  4},
            {5, 6,  7,  8},
            {9, 10, 11, 12}};
    
    
        colSwap(pin);
        return 0;
    }
    

    声明一个数组时,它的大小必须是固定的,所以ngns应该是const intpin的类型实际上是int[3][4],你可以只传递这个类型的引用,让编译器推导出大小。

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多