C ++多维数组函数参数

时间:2011-06-03 00:57:36

标签: c++

如何在不定义其大小的情况下将二维或多维数组作为函数的参数传递?

这是我的示例代码:

 void test(int *a) { 
    a[0][0] = 100; 
 } 
 int main()  { 
    int a[2][2]; 
    test(a); 
    cout<<a[0][0]; 
 }

5 个答案:

答案 0 :(得分:5)

您可以将模板用于静态尺寸

template<int first, int second> void func(int(&array)[first][second]) {
}

动态尺寸的矢量矢量

void func(std::vector<std::vector<int>> array) {
}

但是,你绝对无法做的是使用int**int[]会衰减为int*int[][]会衰减为int*[]。想一想 - 否则,语言将如何区分指针数组和多维值数组?你真的永远不应该使用原始数组,他们乞求麻烦,没有安全和隐含的转换wazoo。为静态数组提供一个安全std::array(如果你在C ++ 03中为boost::array),或为动态数组提供std::vector

答案 1 :(得分:3)

如果您只使用静态大小的堆栈分配数组,那么函数模板将完全符合您的要求:

#include <cstddef>
#include <ostream>
#include <iostream>

template<std::size_t N, std::size_t M>
void func(int (&arr)[N][M])
{
    std::cout << "int[" << N << "][" << M << "]\n";
    for (std::size_t n = 0; n != N; ++n)
        for (std::size_t m = 0; m != M; ++m)
            std::cout << arr[n][m] << ' ';
    std::cout << '\n' << std::endl;
}

int main()
{
    int i1[2][3] = { { 4, 5, 6 }, { 7, 8, 9 } };
    int i2[4][2] = { { 1, 3 }, { 5, 7 }, { 9, 11 }, { 13, 15 } };
    func(i1);
    func(i2);
}

答案 2 :(得分:0)

将指针传递给数组。例如,如果您有一个二维int数组,则需要传递int** p以及数组的维度。

答案 3 :(得分:0)

对于内置数组,您必须指定所有维度的大小,但最后一个维度或索引不起作用。

如果你的目标只是拥有一个任意大小的多维数组的函数,我会考虑boost :: multi_array_ref(或boost :: const_multi_array_ref)

更新: 因为通过指针看起来是最受关注的答案(虽然我认为multi_array_ref很好......除非提升不可用或者其他东西)然后这是一个扁平化数组并且不限制数组的示例维度(尽管您仍需要大小信息才能使其有用)

void f(int* array /* should probably pass in the size here - in this case, 4 */)
{
   array[3] = 9;
}

int main()
{
   int array[2][2] = { {1,2}, {3,4} };

   // Note: The array is flattened here. If you truly need to remember the multi-dimensional nature, you need to pass in enough information to specify all the dimensions... maybe something like a vector<size_t> (that's what the multi_array_ref uses). I guess if you have a limited number of dimensions then a couple size_t will work for you

   test(&array[0][0]);

   std::cout << array[1][1] << std::endl;
   return 0;
}

答案 4 :(得分:-3)

int a[][]

可以传递为:

function name(int **arr) {
    //your code, you can then access it just like you would have accesses your array:
       arr[3][2]
}