Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing constant Arrays with different sizes as function parameters in C++

Tags:

c++

c

visual-c++

I have constant multi-dimensional arrays of different sizes. I would like to pass them to a function. However, I would get the error missing subscript, the sizes of the arrays are different so I can't put the subscript in the array parameter. What is the solution to this problem?

Here is an example code. The actual arrays are bigger.

//ARRAY1
const double ARRAY1[3][2][2] =
{
    {
        {1.0,1.0},
        {1.0,1.0},
    }
    ,
    {
        {1.0,1.0},
        {1.0,1.0},
    }
    ,
    {
        {1.0,1.0},
        {1.0,1.0},
    }
}
//ARRAY2
const double ARRAY2[2][2][2] =
{
    {
        {1.0,1.0},
        {1.0,1.0},
    }
    ,
    {
        {1.0,1.0},
        {1.0,1.0},
    }
}

//How to declare the parameter?
double SomeFunctionToWorkWithBothArrays(const double arr[][][])
{

}
like image 262
Amin1Amin1 Avatar asked Jan 03 '11 14:01

Amin1Amin1


2 Answers

You could use a template.

template<size_t first, size_t second, size_t third> 
double SomeFunction(const double (&arr)[first][second][third]) {
    return first + second + third;
}

This function takes a reference to a three-dimensional array of doubles where all dimensions are known at compile-time. It's actually possible to take this reference via template, if desperate.

like image 103
Puppy Avatar answered Oct 03 '22 19:10

Puppy


Use std::vector instead of arrays. Vectors know their own size, so that would be no problem. You can use vectors of vectors as multi-dimensional arrays.

like image 33
Jon Avatar answered Oct 03 '22 19:10

Jon