简体   繁体   English

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

[英]Why is my vector subscript out of range?

Keep getting this error "Vector subscript out of range". 不断收到此错误“向量下标超出范围”。 I'm sure its because of this part of my code. 我确定这是因为我的代码的这一部分。 Can anyone help me see what I'm doing wrong 谁能帮我看看我在做什么错

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;
}

You assign -1 to subscript in this if condition: if条件, if可以在此为subscript分配-1

if(subscript = -1)

The intention of this code is not clear. 此代码的意图尚不清楚。

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 . 在此循环中, subscript首次访问为-1,时将访问向量边界之外,而subscript等于my_size - 1时将在循环的末尾my_size - 1

while (subscript < my_size)
{
    my_element[subscript] = my_element[subscript + 1];
    subscript++;
}

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. 这是因为my_element[-1]在第一个元素后面,而my_element[my_size]在向量的最后一个元素之后读取一个。 You can change your test: 您可以更改测试:

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

This fixes out of bounds at the end of the while loop, but you should fix the if condition to not assign to subscript . 这样可以在while循环结束while解决问题,但是您应该解决if条件不分配给subscript

while( (subscript < my_size) && (my_element[subscript] != removalCandidate) )

Unless you are trying to have unique values in the Vector you don't need the && with the second part of your conditional. 除非您试图在Vector中使用唯一值,否则您不需要在条件的第二部分加上&&。 You are also not removing the 'removalCandidate' because you close the loop before getting to your IF statements. 您也不会删除“ removalCandidate”,因为在进入IF语句之前已关闭循环。

@0x499602D2 is right in that you will be checking your Vector with a subscript that is -1. @ 0x499602D2是正确的,因为您将使用下标-1检查Vector。 So you will always be out of range. 因此,您将永远不在范围之内。

Lastly, the subscript at the end of your while loop will equal my_size and so when referencing 最后,while循环末尾的下标将等于my_size,因此在引用时

my_element[subscript]

that will also be out of range every time if your Vector's size is 10 but the referencing of the Vector begins at zero. 如果您的Vector的大小为10,但每次对Vector的引用都从零开始,则每次也会超出范围。 So you should reference the Vector from 0 to (my_size-1). 因此,您应该引用从0到(my_size-1)的Vector。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM