2014-10-04 23 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