You can take advantage of the fact that arrays in user defined types are copied and assigned when instances of that type are copied or assigned, for example
template <size_t N, size_t M>
struct Foo
{
int data[N][M];
};
template <size_t N, size_t M>
void func1(Foo<N, M> foo)
{
foo.data[1][2] = 42;
}
int main()
{
Foo<3, 3> f;
f.data[0][0]=2;
...
func1(f);
}
Here, func1
has a local copy of the foo
, which has its own copy of the array. I have used templates to generalize to arbitrary sizes.
Note that C++ provides the std::array
template, which you could use instead of Foo
, so in real code you would do something like this:
#include <array>
template <typename T, size_t N, size_t M>
void func1(std::array<std::array<T, N>, M> arr)
{
arr[1][2] = 42;
}
int main()
{
std::array<std::array<int, 3>, 3> a;
a[0][0]=2;
...
func1(a);
}
If you are stuck with pre-C++11 implementations, you can use either std::tr1::array
(header <tr1/array>
or boost::array
from the boost library. It is also a nice exercise to roll out your own.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…