2017-05-05 16 views
0

我試過但它不工作! 任何一個可以幫我請,這是非常重要的:(如何在不使用指針的情況下將動態二維數組傳遞給函數?

#include <iostream> 
using namespace std; 
int a[100][100]; 

void read(int a[][100],int n) 
{ 
    int i,j; 
    for(i=0;i<n;i++) 
     for(j=0;j<n;j++) 
    cin>>a[i][j]; 
} 

int main() 
{ 
    int n; 
    cin>>n; 
    int a[n][n]; 
    read(a,n); 
} 
+1

'int a [n] [n];'是VLA而不是標準C++。 – Jarod42

+0

您應該切換參數。如果你之前寫了'int n',你可以使用數組大小​​的值:'void read(int n,int a [] [n])' – mch

+0

你有衝突的聲明'a [] []' –

回答

2

語法不清楚通過引用傳遞數組:導致

#include <iostream> 

void read(int (&a)[100][100], int n) 
{ 
    for(int i = 0; i < n; i++) 
     for(int j = 0; j < n; j++) 
      std::cin >> a[i][j]; 
} 

int main() 
{ 
    int n; 
    std::cin >> n; 
    int a[100][100]; 
    read(a, n); 
} 

void read(int (&a)[100][100], int n) 

但您可能更std::vector

#include <iostream> 
#include <vector> 

void read(std::vector<std::vector<int>> &mat) 
{ 
    for (auto& v : mat) { 
     for (auto& e : v) { 
      std::cin >> e; 
     } 
    } 
} 

int main() 
{ 
    int n; 
    std::cin >> n; 
    std::vector<std::vector<int>> mat(n, std::vector<int>(n)); 
    read(mat); 
} 
+0

是的,我會試試這個 –

0

由於這是C++標記的。我想推薦使用std::vector。這是非常有用的動態容器。您可以調整它的大小,清除它可以輕鬆填充它。一旦你明白它是基本的用法,它們會在你將來的C++開發中變得非常方便。我修改你稍微的代碼:

#include <iostream> 
#include <vector> 
using namespace std; 

void read(vector<vector<int> >& arr,int n) 
{ 
    int i,j; 
    for(i=0;i<n;i++) 
     for(j=0;j<n;j++) 
      cin>>arr[i][j]; 
} 
int main() 
{ 
    int N; 
    cin>>N; 
    vector<vector<int> > arr(N, vector<int>(N)); 
    read(arr, N); 
} 

他們對原始陣列很多優勢,如他們可以很容易地初始化,假設你想將所有初始化爲零:

vector<vector<int> > arr(N, vector<int>(N, 0)); 

您不必無論何時傳入函數,都要考慮添加數組的大小。與標準模板庫的像fillswap添加的方法。此外

for(i = 0; i < arr.size(); i++) { 
    for(j = 0; j < arr[i].size(); j++) { 
    // do stuff 
    } 
} 

:載體可以容易地處理這個問題。許多操作都可以輕鬆處理。