传递 2D 数组 c++

Passing 2d array c++

本文关键字:c++ 数组 2D 传递      更新时间:2023-10-16

我正在尝试制作一个交换两列的小程序,我必须使用函数才能做到这一点,但我刚刚开始使用 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 中传递这样的大小,但在 C++ 中是不可能的。原因是C++没有可变长度数组。C++ 中的数组在编译时必须固定其大小。不,将大小参数设为const不会使它们成为编译时常量。

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

您可以使用模板函数

#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 int的。pin的类型实际上是int[3][4],你可以只传递这种类型的引用,让编译器推断出大小。