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

标签 c++ for-loop iterator

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

我创建了一个“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/

相关文章:

android - Ubuntu 中的 C/C++ 套接字,用于从 Android 麦克风输入接收音频流

ios - Sprite Kit 创建倒数计时器问题

javascript - 查找数组中重复字符的唯一索引

iterator - 迭代复制类型

c++ - 静态对象如何跨 DLL 和 Windows 二进制内存共享

c++ - Lambda 中的参数列表

c++ - 如何将抽象类指针作为 Q_PROPERTY?

dictionary - 为什么这两个 for 循环变体会给我不同的行为?

c# - C# 中相当于 Java 中的 List 和 Iterator 的是什么?

python - 是否有一种 pythonic 方法来迭代范围字典以构建新字典?