[英]C++ pass an array of bitfields by reference
我正在嘗試將地圖渲染(控制台,ASCII)放到一個函數中,但是無法編譯。 它應該看起來像這樣:
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 ++通過引用傳遞數組 。 (常量圖塊(tile&)[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);
//...
}
我會考慮使用向量。 很抱歉這樣愚蠢的問題:)
您可以這樣做:
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 :: vector。
另請閱讀此答案。
使用std :: vector,您可以例如執行以下操作:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.