C++ 向量下标超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5920839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:11:11  来源:igfitidea点击:

Vector subscript out of range

c++vectorrangesubscript

提问by pighead10

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;

回答by Jon

If cis the count of elements in any vector, then the mistake is simply that in a vector with Nitems the item indexes are 0...[N-1]and not 1...N.

如果c是任何向量中元素的计数,那么错误很简单,即在带有N项的向量中,项索引是0...[N-1]而不是1...N

Therefore, make this correction:

因此,进行此更正:

for(int i=0; i < (c); i++) {

By the way, in C-like languages the archetype of a forloop that iterates Ntimes is, not coincidentally:

顺便说一句,在类 C 语言中for,迭代N时间的循环的原型并非巧合:

for(int i = 0; i < N; ++i)

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".

坚持这一点,除非你有一个很好的理由例外,并且你可以“免费”避免这种类型的错误。