2015-10-06 127 views
-3
#include <bits/stdc++.h> 
using namespace std; 

#define HODOR  long long int 
#define INF   1234567890 
#define rep(i, a, b) for(int i = (a); i < (b); ++i) 
#define dwn(i, a, b) for(int i = (a); i >= (b); --i) 
#define REP(c, it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) 
#define DWN(c, it) for(typeof((c).end()) it = (c).end()-1; it >= (c).begin(); --it) 
#define ss(n)  scanf("%s",n) 
#define FILL(x,y) memset(x,y,sizeof(x)) 
#define pb   push_back 
#define mp   make_pair 
#define ALL(v)  v.begin(), v.end() 
#define sz(a)  ((int)a.size()) 
#define SET(v, i) (v | (1 << i)) 
#define TEST(v, i) (v & (1 << i)) 
#define TOGGLE(v, i) (v^(1 << i)) 
#define gc   getchar 
#define pc   putchar 


template<typename X> inline void inp(X &n) { 
    register int ch=gc();int sign=1;n=0; 
    while(ch < '0' || ch > '9'){if(ch=='-')sign=-1; ch=gc();} 
    while( ch >= '0' && ch <= '9') n = (n<<3)+(n<<1) + ch-'0', ch=gc(); 
    n=n*sign; 
} 

inline void inps(char *n) { 
    register int ch=gc(); 
    int sign=1; 
    int i=0; 
    while(ch != '\n'){ n[i]=(char)ch; ++i; ch=gc();} 
    n[i]='\0'; 
} 

int MaxPath(int arr[][100],int n) { 
    for (int i = 0; i < n; ++i) { 
     for (int j = 0; j < n; ++j) { 
      cout<<arr[i][j]<<" "; 
     } 
     cout<<endl; 
    } 
} 

int main() { 
    int t,n; 
    inp(t); 

    while(t--) { 
     inp(n); 
     int arr[n][n]; 

     for (int i = 0; i < n; ++i) { 
      for (int j = 0; j < n; ++j) { 
       inp(arr[i][j]); 
      } 
     } 

     float result = MaxPath(arr,n); 
    } 

    return 0; 
} 

Error seems like this : error: cannot convert ‘int ()[n]’ to ‘int ()[100]’ for argument ‘1’ to ‘int MaxPath(int (*)[100], int)’傳遞一個多維數組在C++

我看到的stckoverflow很多帖子,但沒有一個似乎工作

+0

我強烈建議您使用文本編輯器的片段功能而不是這些宏。這些按位可能很容易變成函數而不是宏,或者你可以使用'std :: bitset'。 – chris

+0

好吧,thnx爲 –

+0

代碼現在很好地縮進 –

回答

1

你可以作爲一個指針傳遞給一個指針爲int這樣

int MaxPath(int** arr,int n) 

但對於這個工作,你就必須申報INT ARR [N] [N]不同

int main() { 
    int t,n; 
    inp(t); 

    while(t--) { 
     inp(n); 
     int** arr = new int*[n]; 

     for (int i = 0; i < n; i++) 
      arr[i] = new int[n]; 

     for (int i = 0; i < n; ++i) { 
      for (int j = 0; j < n; ++j) { 
       inp(arr[i][j]); 
      } 
     } 

     float result = MaxPath(arr,n); 
    } 
    //deallocate arr 
    for (int i = 0; i < n; i++) 
    { 
     delete[] arr[i]; 
    } 

    delete []arr; 

    return 0; 
} 
0

編譯器需要能夠在MaxPath中計算數據項的存儲地址。這隻有在知道矩陣寬度的情況下才有可能。

最簡單的解決方案之一是創建某種類型的矩陣類,在矢量之上實現兩維(或多維)類型。它看起來像這樣:

#include <vector> 
#include <stdio.h> 

template<class T> class matrix 
{ 
    std::vector<T> v; 
    int width; 
public: 
    matrix(int w, int h): v(w*h),width(w) {} 
    T &operator()(int x, int y) { return v[x+y*width]; } 
    const T &operator()(int x, int y) const { return v[x+y*width]; } 

}; 


void f(matrix<int> &m) 
{ 
    printf("%d\n",m(1,2)); 
} 

int main() 
{ 
    matrix<int> m(5,5); 

    m(1,2)=42; 
    f(m); 
} 

這只是一個小例子,你可能要延長矩陣類現實世界的應用。