首页 > 解决方案 > 从 100 递减到 0 时向量下标超出范围

问题描述

我调试了这个错误,我不明白为什么这个向量下标超出范围。我也看过这个链接,但没有用:
Vector subscript out of range

我有一个board用私有数据成员调用的类vector<int> m_Board_board。在board构造函数中,我将这个变量从1to初始化,100并使用friend operator <<函数从 last 到 end 打印,如下所示:

#ifndef BOARD_H
#define BOARD_H

#include <iostream>
#include <vector>

using std::vector;
using std::ostream;

class Board
{
private:
   vector<int> m_Board_board;
public:
   Board()
   {
      for (int i = 1; i < 101; ++i)  {
         m_Board_board.push_back(i);
      }
   }

   friend ostream& operator << (ostream& os, Board board)
   {
      for (int i = 100; i > 0; --i) {
         os << board.m_Board_board[i] << '\n';
      }
      return os;
   }
};

#endif // !BOARD_H

在我的main功能中,我正在打印电路板。

#include "Board.h"    
using std::cout;

int main()
{
   Board board;
   cout << board;
   system("pause");
}

这会产生以下错误:https ://i.stack.imgur.com/TWVQF.png

现在奇怪的是,如果我将operator <<功能更改为从头到尾打印,它会按预期工作!

#ifndef BOARD_H
#define BOARD_H

#include <iostream>
#include <vector>
using std::vector;
using std::ostream;

class Board
{
private:
   vector<int> m_Board_board;

public:
   Board() 
   {
      for (int i = 1; i < 101; ++i) {
         m_Board_board.push_back(i);
      }
   }

   friend ostream& operator << (ostream& os, Board board)
   {
      for (int i = 0; i < 100; ++i) {
         os << board.m_Board_board[i] << '\n';
      }
      return os;
   }
};
#endif // !BOARD_H

他们都在做同样的事情,但一个是 throwing vector subscription out of range error,而另一个工作正常。现在,在我收到评论说我必须使用迭代器之前,我用迭代器尝试了它们并且发生了同样的事情,这导致我尝试使用正常的整数循环来确定问题是否与使用迭代器有关。但是,这不是迭代器,而是很奇怪!

但是,在第一种情况下,当我从99to迭代时0,它可以完美运行,但不会打印第一个元素(显然!)。

那么,当我开始从100下降到时,为什么它会超出范围0

标签: c++classc++11operator-overloadingstdvector

解决方案


他们没有做同样的事情!

m_Board_board有 100 个元素,这意味着索引从0, 1, 2,..., 99第一个代码开始,在循环中

for (int i = 100; i > 0; --i) {

您正在启动索引100。这是试图访问向量 vis 中不存在的元素std::vector::operator[],即访问越界未定义行为。那就是任何事情都可能发生。在您的情况下,您遇到了程序崩溃。

你应该从开始99有定义的行为

friend ostream& operator << (ostream& os, Board const& board) /* noexcept */
//                                              ^^^^^^^--> also pass the object by const-ref
{
   for (int i = 99; i >= 0; --i) {
      os << board.m_Board_board[i] << '\n';
   }
   return os;
}

或者在反向迭代器的帮助下做

#include <algorithm> //  std::copy
#include <iterator>  

friend ostream& operator << (ostream& os, Board const& board) /* noexcept */
//                                              ^^^^^^^--> also pass the object by const-ref
{
   std::copy(board.m_Board_board.crbegin(), board.m_Board_board.crend(),
      std::ostream_iterator<int>(os, "\n"));
   return os;
}

这是一个工作演示


推荐阅读