2016-03-09 109 views
-2

正如你所知道多維數組時,我們定義了之前主必須爲除第一個所有尺寸界限。 我有一個2d矩陣,並希望將其用作函數的參數。該2D矩陣具有行和列,我必須初始化列... 我知道這些方法:(和不想使用命令行來定義列的值)在(C++)中使用二維數組作爲函數參數?

//1-using a number 
void sample(int array[][5]); 
int main(){.....} 

//2-using a static parameter 
#define x 5 
void sample(int array[][x]); 
int main(){.....} 

但其中非是有用的4我,做ü有任何其他的建議嗎?

其實這是我的主要代碼:

#define colu 7 
#define colu_ 7 

int compute(char mat1[][colu],int r1,char mat2[][colu_], int r2); 
int main(){ 
. 
. 
. 
int m; 
m=compute(mat1,r1,mat2,r2); 
cout<<m<<endl; 
return 0;} 

//**************** 
int compute(char mat1[][colu],int r1,char mat2[][colu_], int r2){ 
... 
} 
//**************** 

我需要通過這些二維矩陣中的「計算」功能。

+3

你能填寫詳細你想要什麼來完成,用代碼去與它一起? – dbush

+0

是的,我將剛纔... – shirin

+3

C或C++增加的問題?選一個。 –

回答

1

你可以使用模板來自動或直接定義列大小:

template <size_t col1, size_t col2> 
int compute(char mat1[][col1], int r1, char mat2[][col2], int r2) 
{ 
    std::cout << "c1: mat 1 is " << r1 << "x" << col1 << "\n"; 
    std::cout << "c1: mat 2 is " << r2 << "x" << col1 << std::endl; 

    return r1; 
} 

如果你的矩陣大小在編譯時已知,你可以使用它,就像這樣:

int main() { 

    char mat1[1][1] = { { 'a' } }; 
    char mat2[2][2] = { { 'b', 'c' },{ 'd', 'e'} }; 
    compute(mat1, 1, mat2, 2); 
    compute(mat1, 1, mat2, 1); 
    return 0; 
} 

然而,如果你需要char**來解決這個實現是不是真的有用...

+0

感謝您的幫助!你指導我!它的作品:) – shirin

1

如果你不希望使用參數,你可以隨時使用矢量的矢量:

void sample(vector<vector<int>>& array) 

然後你就可以得到與各自的大小:

array.size(); 
array[0].size(); // if at least there is a row 

同時請注意,在評論中指出,使用矢量向量與Matrix不同,因爲行可能具有不同的大小。

另一種選擇是有一個單一的載體,並使用一些數學來訪問特定的行西:

double matrix::get(size_t x1, size_t y1) 
{ 
    return m[ x1 * x + y1 ]; 
} 
+0

請記住,這可能以不同大小的行結束 - 所以不一定是2d矩陣,所以雖然我一定會選擇'vector',但我會主張使用包含在一個單獨的矢量(大小:x * y)簡單的存取類 –

+0

像[這]答位(http://stackoverflow.com/questions/29693700/c-2d-vector-got-error/29694032#29694032)也許 –

+0

謝謝你,是的,我知道這種方法。這將是我的最後一次嘗試......我更喜歡使用2d數組而不是將其轉換爲矢量。但感謝您的建議 – shirin

1

如果你能夠使用C99,使用VLA。在C++中,使用std::vector<std::vector<int>>而不是2D數組。

void sample(std::vector<std::vector<int>> const& array); 
+0

我用這個:void sample(int rows,int cols,int array [rows] [cols]);但收到它說的錯誤:「使用參數‘的cols’外函數體 的」 – shirin

+0

@shirin,使用'GCC -std = c99'它工作正常,我。你使用什麼編譯器和編譯器選項? –

1

如果陣列尺寸是在編譯時已知,你可以用一個模板:

template<int X, int Y> 
void foo(int (&array)[X][Y]) { 
    std::cout << X << ' ' << Y << '\n'; 
    for(const auto& arr : array) { 
     for(const auto& i : arr) { 
      std::cout << i << ' '; 
     } 
     std::cout << '\n'; 
    } 
} 

int main() { 
    int asdf[2][5] = { 
     { 1, 2, 3, 4, 5 }, 
     { 6, 7, 8, 9, 10 } 
    }; 
    foo(asdf); 
} 

,如果你使用動態分配new您的陣列,雖然這是行不通的。

+0

非常感謝你,使用模板的想法,因爲你和西蒙告訴我是一個好點:) – shirin