矢量下标超出范围错误
Vector subscript out of range error?
我是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;
}
注意:只有当您在迭代时更改向量中的元素数量时,这才适用,就像本例中发生的那样。如果在迭代过程中添加或删除元素,则可能会使迭代器无效。
相关文章:
- "myClock"未在此范围错误中声明
- 包含来自另一个文件的函数会导致范围错误(openFoam)
- Visual C:命名空间范围错误或晦涩功能?
- 在遍历字符串时,为什么我没有超出范围错误,即使我已经超出了它的长度?
- 此范围错误中未声明如何修复
- 尝试声明函数的局部变量,但得到范围错误
- c ++ to_string未在此范围错误 [Windows + Devcpp 环境] 中声明
- 将文件读取到向量的向量,超出范围错误
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- Eratosthenes C 的筛子 - 内存处的范围错误
- 向量:内存处的范围错误
- 测试完美哈希函数时超出范围错误
- 为什么此代码会给出 Vector 超出范围错误
- 在填充 Arduino 草图时出现范围错误
- 如何修复C++中矢量的"下标超出范围"错误?
- CPP-模板范围错误
- 在此范围错误中未声明函数错误
- C 表达式:向量下标出范围错误线:1733
- 无法在好友函数中实例化类?我没有得到在范围错误中声明
- 带有类的嵌套结构.范围错误