samedi 22 août 2020

Vector Subscript out of range when decrementing from 100 to 0

I debugged this error, and I cannot understand the reason as to why this vector subscript is going out of range. I have also looked at this link but it was to no avail:
Vector subscript out of range

I have a class called board with a private data member vector<int> m_Board_board. In the board constructor, I am initializing this variable from 1 to 100 and using the friend operator << function to print from last to the end like so:

#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

In my main function, I am printing out the board.

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

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

This creates the following error: https://i.stack.imgur.com/TWVQF.png

Now the bizarre thing is if I change my operator << function to print from start to the end, it works as expected!

#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

They are both doing the same thing, but one is throwing vector subscription out of range error, while the other works fine. Now before I get comments saying that I must use iterators, I tried them with iterators and the same thing happened, which led me to try using the normal integer loops to figure out if the problem was with using the iterators or not. However, it is not the iterators it is something weird!

However, in the first case when I am iterating from 99 to 0, it works perfectly but it does not print the first element (obviously!).

So, why is it going out of range when I am starting to decrement from 100 down to 0?

Aucun commentaire:

Enregistrer un commentaire