向量下标超出范围
我收到向量下标超出范围错误。我以前遇到过,但它打印“之前”,但不打印“之后”,所以我很困惑为什么其中一行会导致它。
cout << "before" << endl;
vector<vector<char>> animals;
vector<vector<char>> food;
vector<char> other;
int lastline = 0;
for(int i=1;i<=(c);i++){
cout << "after" << endl;
I'm getting the vector subscript out of range error. I've had it before, but it prints 'before' but it doesn't print 'after' so I'm confused at to why one of these lines would be causing it.
cout << "before" << endl;
vector<vector<char>> animals;
vector<vector<char>> food;
vector<char> other;
int lastline = 0;
for(int i=1;i<=(c);i++){
cout << "after" << endl;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
c
是任何向量中元素的计数,那么错误就在于,在具有N
项的向量中,项索引为0...[N -1]
而不是1...N
。因此,进行此更正:
顺便说一下,在类 C 语言中,迭代
N
次的for
循环的原型并非巧合:坚持使用此方法,除非您有这是一个非常非常好的例外理由,并且您可以“免费”避免此类错误。
If
c
is the count of elements in any vector, then the mistake is simply that in a vector withN
items the item indexes are0...[N-1]
and not1...N
.Therefore, make this correction:
By the way, in C-like languages the archetype of a
for
loop that iteratesN
times is, not coincidentally:Stick with this unless you have a very very good reason to make an exception, and you get to avoid this type of bug "for free".