C 向量下标超出范围,没有逻辑错误,无法弄清楚



当我运行此代码时,它会使我的调试断言失败,第1232行,向量下标,超出了范围。

Maze::Maze(bool verbose = false)
// verbose == true means an intro and prompts for input will be printed
{
  int i, j, dimension;
  if (verbose) {
    cout << "Welcome to the Rat in the Maze program, where we will find an"
     << "path from the start cell to the end cell of a maze so that Remyn"
     << "may escape.  You will first enter the data specifying the maze.n"
     << "After that, if escape is possible, we will show an escape pathn"
         << "Enter the number of rows and columns of the maze: " << endl;
  }   
  cin >> dimension;
  size = dimension+2; // add the hedge rows and columns
  if (verbose)
    cout << "Enter the row and column indices of the start: " << endl;
  cin >> start;
  if (verbose)
    cout << "Enter the row and column indices of the exit: " << endl;
  cin >> exitpos;

/Here is where I got the error:/
  M.reserve(size);
  for (i = 0; i < size; i++) {
    M[i].reserve(size);
    for (j = 0; j < size; ++j)
      M[i][j] = WALL;
  }
  if(verbose) {
    cout << "For each row, enter the column indices of the open squaresn";
    cout << "Terminate the row input with a non-positive value" << endl;
  }
  for (i = 1; i <= size-2; i++) {
    if (verbose)
      cout << "Row " << i << ": ";  
    cin >> j;
    assert(j < 1 || 1 <= j && j <= size-2);
    while (j > 0){
      M[i][j] = OPEN;
      cin >> j;
      assert(j < 1 || 1 <= j && j <= size-2);
    };
  }
  if (!(M[start.row][start.col] == OPEN)) 
    M[start.row][start.col] = OPEN;
}

m是一个明显的对象,定义为以下:

typedef vector<vector<state> > stateTable;

代码中没有逻辑错误,但是我遇到了此错误,我知道的一件事是我们的讲师在我在VC环境下进行此操作时在Linux环境下编写并编译了此代码。那是原因吗?

方法reserve不会创建向量的新元素。它只是为将来的元素保留记忆。因此,您可能无法使用下标操作员访问不存在的元素。

而不是方法reserve如果要创建新元素,则使用方法resize

例如

  M.resize(size);
  for (i = 0; i < size; i++) {
    M[i].resize(size);
    for (j = 0; j < size; ++j)
      M[i][j] = WALL;
  }

或只是写

M.resize(n, std::vector<state>( size, WALL) );
 M.reserve(size);
 for (i = 0; i < size; i++)
 {
     M[i].reserve(size);
     for (j = 0; j < size; ++j)
         M[i][j] = WALL;
 }

原因是向量的reserve()方法没有设置供使用的元素。以这种方式使用它们可以在访问M[i]M[i][j]的情况下提供未定义的行为。

更改M.reserve(size)M[i].reserve(size)的调用以使用resize()(即使用M.resize(size)M[i].resize(size)

区别在于resize()还确保元素准备就绪(除其他外)。

差异反映了resize()的目的是设置可用使用的元素的数量,而reserve()涉及控制resize()的频率以及调整容器大小的其他操作的频率 - 实际上重新计算内存。

最新更新