2014-10-04 57 views
0

我試圖把我的地圖渲染(控制檯,ASCII)到一個函數,但它不編譯。 它應該是這個樣子:C++通過引用傳遞位域數組

struct tiles { 
    unsigned is_visible : 1; 
    //... 
} tile[y][x]; 

void render_map(const tiles (tile&)[y][x]) { 
    for (int i = 0; i < y; i++) { 
     if (tile[y].is_visible == 0) { 
      //... 
     } 
    } 
} 

int main() { 
    render_map(tile); 
    //... 
} 

我嘗試做在這樣的回答:C++ pass an array by reference(瓦片&)[y] [x])

感謝所有,現在它的工作!

struct tiles { 
    unsigned is_visible : 1; 
    //... 
} tile[y][x]; 

void render_map(const tiles (&tile)[y][x]) { 
    for (int i = 0; i < y; i++) { 
     for (int j = 0; j < x; j++) { 
      if (tile[i][j].is_visible == 0) { 
       //... 
      } 
     } 
    } 
} 

int main() { 
    render_map(tile); 
    //... 
} 

我會考慮使用矢量。 對不起,這種愚蠢的問題:)

+0

你得到了什麼錯誤? – DOOM 2014-10-04 16:55:57

+0

使用矢量並像這樣傳遞'const vector >&' – 2014-10-04 16:57:22

回答

0

你可以這樣像這樣:

struct Tiles { 
    unsigned is_visible : 1; 
    //... 
}; 

const int x = 5; 
const int y = 5; 
Tiles tiles[x][y]; 

void render_map(const Tiles tile[x][y]) { 
    for (int i = 0; i < y; i++) { 
     if (tile[y].is_visible == 0) { // tile is a 2d array, not a 1D, thus error 
     //... 
     } 
    } 
} 

int main() { 
    render_map(tiles); 
    //... 
} 

然而,由於這是C++,我不明白爲什麼你不使用一個std ::向量。

也讀this回答。

有了一個std ::載體,例如,你可以這樣做:

void print_vector(std::vector< std:: vector<Tiles> >& v) { 
    for(unsigned int i = 0; i < v.size(); ++i) 
    for(unsigned int j = 0; j < v.size(); ++j) 
     j += 0; 
} 

int main() { 
    std::vector< std:: vector<Tiles> >v; 
    v.resize(2); // make space for two vectors of tiles 
    Tiles t; 
    t.is_visible = 0; 
    v[0].push_back(t); 
    v[1].push_back(t); 

    print_vector(v); 
    return 0; 
} 
+0

刪除'typedef';這是完全多餘的,並且無故延長/複雜化代碼。另外,你後來忽略它並使用'struct tiles',這也是多餘的。 C++不是C! – 2014-10-27 00:48:32

+0

不客氣。 – 2014-10-27 07:52:13