我正在学习C++,动态数组让人很困惑。
所以我用一维阵列作为2D(x+宽度*y)来制作一个游戏的TileMap系统。 每个单元格保存一个用于平铺绘制的索引。 但我想做一个选项来调整Tilemap的大小。 参数用于调整边框大小。
所以问题是:
我做新数组创建和删除正确吗?
在数据上移动的正确逻辑是什么? 我发现索引分配错误。
void TileMap::ResizeMap(int left, int top, int right, int bottom){ //resize by cell
int w = width -left +right; //new width
int h = height -top +bottom; //new height
int* tmp = tilemap; //preparing for deleting old pointer
tilemap = new int[w * h]{-1}; //new TileMap grid populated with -1(empty) indexes
//move old map to new map grid
for (int y = 0; y < width; ++y){
for (int x = 0; x< height; ++x){
if (x+left >= 0 && y+top >= 0 && x+left < w && y+top < h){
tilemap[width*(y+top) + x+left] = tmp[width*y + x];
}
}
}
delete [] tmp; //remove old array
tmp = NULL;
width = w; //Save new width
height = h; //save new height
}
//including Construct and deconstruct
TileMap::TileMap(TileSet& newTileSet, Vector2 mapPosition, int Columns, int Rows){
tileset = &newTileSet;
cell_size = tileset->tile_size;
position = mapPosition;
width = Columns;
height = Rows;
tilemap = new int[width * height];
std::fill(tilemap, tilemap+width*height, -1);((float)height*cell_size.y));
}
TileMap::~TileMap(){
delete [] tilemap;
delete tileset;
}
我做新数组创建和删除正确吗?
int* tmp = tilemap;
tilemap = new int[w * h]{-1};
delete [] tmp;
不,因为您删除了其他内容,所以我们不知道tilemap
是什么,但是假设它是静态的,即全局的int*
,这会泄漏最后分配的映射,而且它会在第一次执行这个函数时导致未定义的行为,因为您可能会遵循空指针。
只需使用std::vector
即可。