矢量下标超出范围错误

Vector subscript out of range error?

本文关键字:范围 错误 下标      更新时间:2023-10-16

我是c++编程的新手,当我运行它时,它成功编译并输出数组的元素,但我得到一个错误,说"矢量下标超出范围"。这个代码出了什么问题?我看了其他一些问题,似乎其他问题都没有类似的向量例子。

#include <iostream>
#include <vector>
#include <random>
#include <time.h>
using namespace std;
int main() {
srand(time(NULL));
    int arraysize;
cout << "Enter the size of your array:" << endl;
cin >> arraysize;
vector<int> numbers(arraysize);
vector<int>::size_type sizecheck = numbers.size();
cout << "This is the unsorted array:" << endl;
for (int z = 0; numbers[z] < sizecheck; z++)
{
    numbers[z] = rand() % 10 + 1;
    cout << numbers[z] << endl;
}
return 0;
}

在给定无限内存的情况下,您的代码实际上是一个无限循环,但是,由于为向量分配的内存量有限,因此它表现出未定义的行为。numbers将值初始化(将每个元素设置为0),这意味着条件始终为0 < sizecheck。一旦z达到向量中的元素数量,就会超出数组边界,并进入未定义的行为区域。

您的IDE或您正在使用的任何东西已经捕捉到错误,但您可以使用更安全的变体at()而不是operator[]。这将引发异常并提供有用的信息。例如:

for (int z = 0; numbers.at(z) < sizecheck; z++)
{
    numbers.at(z) = rand() % 10 + 1;
    cout << z << " " << numbers.at(z) << endl;
}
0 2
1 8
2 10
3 9
4 8
5 2
6 3
7 4
8 4
9 2
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 10) >= this->size() (which is 10)

正如评论中所述,您可能想要做的是z < sizecheck,尽管为了安全起见,您应该将z设置为std::vector<int>::size_type类型。

@remyabel已经给出了绝对正确的答案,但除此之外,在对vector等标准组件进行循环时,您还应该考虑使用iterator,而不是索引for循环。

例如

vector<int>::iterator it;
for(it = numbers.begin(); it != numbers.end(); ++it)
{
    *it = rand() % 10 + 1;
    cout << *it << endl;
}

注意:只有当您在迭代时更改向量中的元素数量时,这才适用,就像本例中发生的那样。如果在迭代过程中添加或删除元素,则可能会使迭代器无效。