[英]Debug Assertion Failed: Vector subscript out of range
收到失败警报,不幸的是我不知道这意味着什么。 我试图搜索有关调试断言失败的其他问题,但找不到任何我认为与我遇到的问题相同的问题。 它明确指出 Line: 1501 Expression: Vector subscript out of range。 我以前使用过矢量并且没有任何问题,有人可以帮助解释我在这里缺少什么吗?
谢谢
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector <int> someVec;
vector <string> anotherVec;
someVec.push_back(1);
someVec.push_back(2);
someVec.push_back(3);
cout << "someVec size: " << someVec.size() << endl;
anotherVec[0] = "Fred";
anotherVec[1] = "Bob";
anotherVec[2] = "Holly";
anotherVec.push_back("John");
for (int val : someVec)
{
cout << val << endl;
}
cout << endl;
for (string name : anotherVec)
{
cout << name << endl;
}
return 0;
}
这一行:
vector <string> anotherVec;
声明一个大小为 0 的向量。然后像这样索引到向量中:
anotherVec[0] = "Fred";
调用未定义的行为。 相反,你可以这样做:
anotherVec.push_back("Fred");
或者,您可以在声明 vector 时为它分配足够的空间,如下所示:
vector <string> anotherVec(3);
然后您可以使用 0、1 或 2 对向量进行索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.