调试断言失败。C++ 向量下标超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19465590/
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-27 22:51:15  来源:igfitidea点击:

Debug assertion failed. C++ vector subscript out of range

c++vector

提问by Abhishek Jain

the following code fills the vector with 10 values in first for loop. in second for loop i want the elements of vector to be printed. The output is till the cout statement before the j loop.Gives error of vector subscript out of range.

以下代码在第一个 for 循环中用 10 个值填充向量。在第二个 for 循环中,我希望打印向量的元素。输出直到 j 循环之前的 cout 语句。给出向量下标超出范围的错误。

#include "stdafx.h"
#include "iostream"
#include "vector"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{   vector<int> v;

    cout<<"Hello India"<<endl;
    cout<<"Size of vector is: "<<v.size()<<endl;
    for(int i=1;i<=10;++i)
    {
        v.push_back(i);

    }
    cout<<"size of vector: "<<v.size()<<endl;

    for(int j=10;j>0;--j)
    {
        cout<<v[j];
    }

    return 0;
}

回答by BartoszKP

Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0(0, 1, ..., 9). So in your second loop v[j]is invalid, when jis 10.

无论您如何索引推回,您的向量都包含从0( 0, 1, ..., 9)索引的 10 个元素。所以在你的第二个循环中v[j]是无效的, when jis 10

This will fix the error:

这将修复错误:

for(int j = 9;j >= 0;--j)
{
    cout << v[j];
}

In general it's better to think about indexes as 0based, so I suggest you change also your first loop to this:

一般来说,最好将索引视为0基础,因此我建议您也将第一个循环更改为:

for(int i = 0;i < 10;++i)
{
    v.push_back(i);
}

Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):

此外,要访问容器的元素,惯用的方法是使用迭代器(在这种情况下:反向迭代器):

for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
    std::cout << *i << std::endl;
}

回答by billz

vhas 10element, the index starts from 0to 9.

v10元素,索引从09

for(int j=10;j>0;--j)
{
    cout<<v[j];   // v[10] out of range
}

you should update forloop to

你应该将for循环更新为

for(int j=9; j>=0; --j)
//      ^^^^^^^^^^
{
    cout<<v[j];   // out of range
}

Or use reverse iteratorto print element in reverse order

或者使用反向迭代器以相反的顺序打印元素

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}

回答by suraj kumar

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

当您尝试通过尚未分配数据数据的索引访问数据时,通常会发生此类错误。例如

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

该代码将给出错误(向量下标超出范围),因为您正在访问尚未分配的 arr[10]。