gpt4 book ai didi

c++ - For 循环在 Iterator-For-Loop 中

转载 作者:太空宇宙 更新时间:2023-11-04 16:14:43 24 4
gpt4 key购买 nike

我正面临一个我不知道解决方案的问题。最后我总是遇到段错误。

我创建了一个“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*>实例。这意味着 beginend以下 for 中使用的迭代器循环引用不同 std::vector实例:

for(auto it = std::begin(game.getMapVector()); 
it != std::end(game.getMapVector());
it++)

可能的解决方案:

  • 存储getMapVector()的结果到局部变量并将其用于迭代
  • 更改getMapVector()返回对 const 的 ( std::vector<Map*>) 引用

关于c++ - For 循环在 Iterator-For-Loop 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23990386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com