为什么我的矢量下标超出范围?

Dre*_*Dre 2 c++ compiler-errors vector

继续收到此错误"矢量下标超出范围".我确定它是因为我的代码的这一部分.任何人都可以帮我看看我做错了什么

bool set::remove(SET_ELEMENT_TYPE removalCandidate)
{
  int subscript = positionOf(removalCandidate);
  while( (subscript < my_size) && (my_element[subscript] != removalCandidate))
  {
     subscript++;
  }
  if(subscript = -1)
  {
    if(subscript == my_size)
      return false;
    else {
      while (subscript < my_size)
      {
        my_element[subscript] = my_element[subscript + 1];
        subscript++;
      }
      my_size--;
      return true;
    }
    return false;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

jxh*_*jxh 6

您分配-1subscript在此if条件:

if(subscript = -1)
Run Code Online (Sandbox Code Playgroud)

这段代码的意图并不清楚.

You will access beyond your vector boundary in this loop at the point that the first access of subscript when it is -1,, and at the end of the loop when subscript is equal to my_size - 1.

while (subscript < my_size)
{
    my_element[subscript] = my_element[subscript + 1];
    subscript++;
}
Run Code Online (Sandbox Code Playgroud)

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

while (subscript + 1 < my_size)
{ //...
Run Code Online (Sandbox Code Playgroud)

This fixes out of bounds at the end of the while loop, but you should fix the if condition to not assign to subscript.