简体   繁体   中英

C++ pass an array of bitfields by reference

I'm trying put my map render (console, ASCII) to one function, but it don't compile. It should be look like this:

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);  
    //...
}

I try to do as in this answer: C++ pass an array by reference . (const tiles (tile&)[y][x])

Thanks to all, now it's work!

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);  
    //...
}

And i'll think about using vector. Sorry for such stupid question :)

You could so something like this:

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);
    //...
}

However, since this is C++, I don't see why you don't use a std::vector.

Also read this answer.

With a std::vector, you could do this for example:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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