[英]Multi-dimensional array
我需要創建一個函數,該函數的參數是一個多維數組,其中二維是用戶指定的,例如
int function(int a, int b, int array[a][b])
{
...
}
我將如何在C ++中做到這一點?
尺寸在編譯時是否已知? 在這種情況下,請將它們轉換為模板參數,然后按引用傳遞數組:
template<int a, int b>
int function(int(&array)[a][b])
{
...
}
客戶端代碼示例:
int x[3][7];
function(x);
int y[6][2];
function(y);
假設在編譯時不知道維數,則用一維數組模擬二維數組:
int& getat(int x, int y, int r, int c, int *array) {return array[y*c+x];}
int function(int a, int b, int *array) {
getat(4, 2, a, b, array) = 32; //array[4,2] = 32
}
或者,為了安全起見,將其全部包裝在一個類中:
template <class T>
class array2d {
std::vector<T> data;
unsigned cols, rows;
public:
array2d() : data(), cols(0), rows(0) {}
array2d(unsigned c, unsigned r) : data(c*r), cols(c), rows(r) {}
T& operator()(unsigned c, unsigned r) {
assert(c<cols&&r<rows);
return data[r*cols+c];
}
};
或者最好的方法是使用Boost的多維數組 ,它比凡人都能寫的任何東西都要好。
我不確定是否可以正常工作,因為您的問題和代碼不同,根據您的代碼,該函數可以具有3個參數,因此可以正常工作:
int function(int a, int b, int** &array)
{
array = new int*[a];
for (int i =0;i<a;i++)
array[i] = new int[b];
// I don't know why you are returning int, probably doing something here....
}
但是您的問題說您的函數只能接受一個參數,因此:
像這樣:
class Foo {
public:
Foo(int d1, int d2)
{ a = d1; b = d2; }
int a,b;
int** array;
};
int function(Foo &f)
{
f.array = new int*[f.a];
for (int i = 0;i<f.a;i++)
f.array[i] = new int[f.b];
// I don't know why you are returning int, probably doing something here....
}
盡管我發現這是一個壞主意,但實際上該function
可能是無參數方法:
class Foo {
public:
Foo(int d1, int d2)
{ a = d1; b = d2; }
void Create() // Or could do this right in the Constructor
{
array = new int*[a];
for (int i = 0;i<a;i++)
array[i] = new int[b];
}
private:
int a,b;
int** array;
};
但這仍然不是一個好主意,因為您正在重新發明輪子,因為STL中有一個完美的類可以為您完成所有工作:
vector< vector<int> > v; // Now v is a 2D array
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.