函数调用中的 C++ Int 数组类型

C++ Int array type in function call

我有一个数组初始化如下:

int example[5][5];
example[5][5] = 55;

还有一个函数:

void example_function(auto inArray, int z){
    cout << "example text = " << inArray[z][z] << endl;
}

我将它调用到这样的函数中:

example_function(example, 5);

如你所见,当它真正使用整数数组时,我将函数的参数设置为auto。

当我使用 typeid(table).name() 获取数组类型 example 时,它将类型输出为 A5_A5_i,其中五个来自初始化(例如 int example[3][4][5]会输出 A3_A4_A5_i)

在将参数类型从 int 更改为 auto 后,在 inArray 上使用 typeid(table).name() 时,我得到的类型名称为 PA5_i和上面说的不一样。

如何为函数中的参数获取合适的类型,是否有更好的方法

如果事先知道传递给函数的数组,在本例中为int example[5][5];,您可以使用以下内容,

void example_function(int (&inArray)[5][5], int z){
    cout << "example text = " << inArray[z][z] << endl;
}

这里我们引用数组来避免array decay.

如果大小可能会在运行时发生变化,请使用 std::vector

std::vector<std::vector<int>> example;

void example_function(std::vector<std::vector<int>> inArray, int z){
    cout << "example text = " << inArray[z][z] << endl;
}