Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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

like image 890
Abhishek Jain Avatar asked Oct 19 '13 11:10

Abhishek Jain


People also ask

What is vector subscript out of range?

Vector subscript out-of-range error occurs when an attempt is made to access a vector element using a subscript that is outside the index range. Out-of-range error is not the same as Segmentation fault (core dumped) all the time.

How do I fix debug assertion failed?

You may uninstall Microsoft Visual C++ Runtime Package from Program & Features then reinstall it again. Thereafter, check if the issue persists. You may run system file checker [SFC] scan on the computer which will replace the missing or corrupt files & check if the issue persists.

What does vector subscript out of range mean c++?

vector subscript out of range means "you asked for an element from the vector, but the vector is not of that size".

What is debug assertion failed Visual C++?

An assertion statement specifies a condition that you expect to hold true at some particular point in your program. If that condition does not hold true, the assertion fails, execution of your program is interrupted, and this dialog box appears. Debug the assertion or get help on asserts.


1 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;
}
like image 193
BartoszKP Avatar answered Oct 23 '22 08:10

BartoszKP