Debug Assertion Failed. C++ Vector Subscript out of Range

Debug Assertion Failed. C++ Vector Subscript out of Range

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.

#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;
}

3 Answers

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 j is 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 0 based, so I suggest you change also your first loop to this:

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

v has 10 element, the index starts from 0 to 9.

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

you should update for loop to

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

Or use reverse iterator to print element in reverse order

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

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.