繁体   English   中英

C ++通过引用传递位域数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM