传递2d数组c ++

时间:2016-05-23 14:40:00

标签: c++ arrays function

我正在尝试创建一个交换两列的小程序,我必须使用函数才能做到这一点,但我刚开始使用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]) {

}

但我需要另一种方法

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

您可以使用模板功能

#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],您只需传递此类型的引用,然后让编译器推断出大小。