我正面临一个我不知道解决方案的问题。最后我总是遇到段错误。
我创建了一个“Map”类,我在其中存储了以下信息,并且该 Map 在 Gameclass 中存储为 Vector
class Map
{
private:
unsigned int map_id_;
unsigned int map_width_;
unsigned int map_height_;
std::vector< std::vector< int > > fields_;
Game *game_;
class Game
{
private:
...
std::vector< Map* > *v_map_;
...
std::vector< Map* > Game::getMapVector()
{
return *v_map_;
}
在游戏类中,我填写了信息,包括字段 vector 。
for(int i = 0; i < height; i++)
{
std::vector< int > row;
for (int j = 0; j < width; j++)
{
is.read(reinterpret_cast<char*>(&fields), 1);
counter = counter - 1;
row.push_back(int(fields));
}
fields_vector.push_back(row);
}
如果我尝试在读取过程中直接输出我的 map ,一切都会完美无缺。
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
std::cout << fields_vector[i][j];
}
std::cout << std::endl;
}
到目前为止一切正常。但是现在,如果我在自动迭代器中使用 for 循环调用它,就会出现段错误。
如果我尝试使用 std::cout << (*it)->getMapFields()[1][1]
只输出一个元素在第一个 for 循环中,我在这个位置得到了正确的输出。
for(auto it = std::begin(game.getMapVector()); it != std::end(game.getMapVector()); it++)
{
std::cout << "ID: " << (*it)->getMapId()
<< ", width: " << (*it)->getMapWidth()
<< ", height: " << (*it)->getMapHeight() << std::endl;
for (int i = 0; i < (*it)->getMapHeight(); i++)
{
for (int j = 0; j < (*it)->getMapWidth(); j++)
{
std::cout << (*it)->getMapFields()[i][j];
}
std::cout << std::endl;
}
}
有什么我没看到的吗?也许在自动迭代器中使用 for 循环是不可能的?
在此先感谢您的帮助,菲利普
一个错误是:
std::vector< Map* > Game::getMapVector()
返回一个新的 std::vector<Map*>
实例。这意味着 begin
和 end
以下 for
中使用的迭代器循环引用不同 std::vector
实例:
for(auto it = std::begin(game.getMapVector());
it != std::end(game.getMapVector());
it++)
可能的解决方案:
- 存储
getMapVector()
的结果到局部变量并将其用于迭代
- 更改
getMapVector()
返回对 const
的 ( std::vector<Map*>
) 引用
我是一名优秀的程序员,十分优秀!