[英]Having Trouble with 2-Dimensional Array of Structs C++
我已经搜索过该网站和Google,但还没有找到能解决我问题的任何东西。 我正在尝试编写一个游戏,该游戏包含玩家可以穿越的地形图。 我想将图块存储在10x10数组中,但是初始化数组时遇到问题。
我可以初始化数组的第一个维度,但是错误在于初始化第一个for循环内的第二个维度。
这是我的代码:
//tile on the "map"
struct tile
{
char type;
bool isWall;
};
void initializeMap(tile * map)
{
int index1, index2;
for(index1 = 0; index1 < 10; index1++)
{
map[index1] = new tile[10];
for(index2 = 0; index2 < 10; index2++)
{
}
}
}
int main()
{
tile * tileMap = new tile[10];
initializeMap(tileMap);
return 0;
}
我收到此错误:
C:\Users\----\Desktop\TextGame.cpp||In function 'void initializeMap(tile*)':|
C:\Users\----\Desktop\TextGame.cpp|39|error: no match for 'operator=' in '*(map + ((unsigned int)(((unsigned int)index1) * 2u))) = (tile*)operator new [](20u)'|
C:\Users\----\Desktop\TextGame.cpp|9|note: candidates are: tile& tile::operator=(const tile&)|
||=== Build finished: 1 errors, 0 warnings ===|
您正在尝试使用以下命令将实际对象设置为指针:
map[index1] = new tile[10];
map
是tile*
。 然而, map[index1]
是deferenced tile*
使得它实际上是一个tile
不能等于一个tile*
其new tile[10]
给你。
因此,您的代码将在以下方面更好地工作:
struct tile {
char type;
bool isWall;
};
/**
* Initialize the map
* @param map The array of tile pointers
*/
void initializeMap(tile** map) {
int index1, index2;
for (index1 = 0; index1 < 10; index1++) {
// Set each element of the tile* array
// to another array of tile pointers
map[index1] = new tile[10];
for (index2 = 0; index2 < 10; index2++) {
// Do Something
}
}
}
int main() {
// Create a pointer to a set of tile pointers
tile** tileMap = new tile*[10];
// Pass it to the initializer
initializeMap(tileMap);
return 0;
}
注意:从技术上讲,多数民众赞成不是二维数组,而是结构数组的数组。
也就是说,该注释反映了您的代码问题:您有一个数组数组,因此第一次分配应该分配一个数组,该数组的内容是指向其他数组的指针 :
tile** tilemap = new tile*[10];
for( std::size_t i = 0 ; i < 10 ; ++i )
tilemap[i] = new tile[10];
....
//Dealocation at program finish:
for( std::size_t i = 0 ; i < 10 ; ++i )
delete tilemap[i];
delete tilemap;
但是,如果您使用标准容器(例如std::vector
)而不是容易出错的手动内存管理,则可以改进您的代码:
std::vector<std::vector<tile>> tilemap( 10 );
for( std::size_t i = 0 ; i < 10 ; ++i )
tilemap.emplace_back( 10 );
我建议使用共享磁贴的std::vector
。 这将允许您使用不同的图块并将其存储到向量中:
struct Tile; // As you declared it.
struct Water_Tile : public Tile;
struct Mountain_Tile : public Tile;
struct Desert_Tile : public Tile;
// ...
typedef std::vector< boost::shared_ptr<Tile> > Tile_Container;
//...
Tile_Container my_world(10 * 10);
// ...
my_world[20] = new Water_Tile;
共享指针的一个好处是它可以为您处理内存管理(删除)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.