簡體   English   中英

調試斷言失敗。 C++ 向量下標超出范圍

[英]Debug assertion failed. C++ 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;
}

無論您如何索引推回,您的向量都包含從0 ( 0 , 1 , ..., 9 ) 索引的 10 個元素。 所以在你的第二個循環中v[j]是無效的,當j10

這將修復錯誤:

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

一般來說,最好將索引視為基於0 ,因此我建議您也將第一個循環更改為:

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

此外,要訪問容器的元素,慣用的方法是使用迭代器(在這種情況下:反向迭代器):

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

v10元素,索引從09

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

您應該將for循環更新for

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

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

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

當您嘗試通過尚未分配數據數據的索引訪問數據時,通常會發生此類錯誤。 例如

//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];
}

該代碼將給出錯誤(向量下標超出范圍),因為您正在訪問尚未分配的 arr[10]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM