Monday 15 August 2011

c++ - Why is my vector subscript out of range? -


Place this error in "Vector Subscript Out of range". I'm sure this is due to this part of my code. Somebody can see what I'm doing wrong

  bool set :: remove (SET_ELEMENT_TYPE removalCandidate) {int subscript = positionOf (removeCandidate); While ((subscript & lt; my_size) & amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; (my_element [subscript]] = RemovalCandidate) {subscript ++; } If (subscript = -1) returns {if (subscript == my_size); And {while (subscript & lt; my_size) {my_element [subscript] = my_element [subscript + 1]; Subscript ++; } my size--; Back true; } return false; } Return 0; }    

You assign -1 to subscript In this condition:

  if (subscript = -1)   

this code is intended to be clear is not.

You will be able to access this loop beyond your vector limit when the first access to subscript is when it is -1, , and at the end of the loop subscript is equal to my_size - 1 .

  while (subscript & lt; my_size) {my_element [subscript] = my_element [subscript + 1]; Subscript ++; }   

This is because my_element [-1] is behind the first element, and my_element [my_size] reading a past You can change your test of the last element of your vector:

  while (subscript + 1 my_size) {// ...   

It finally fixes out of range while loop, but you should decide to not assign if condition to subscript .

No comments:

Post a Comment