. Advertisement .
..3..
. Advertisement .
..4..
I am working on cpp, but I found the following warning message:
Debug assertion failed. C++ vector subscript out of range
Is there any way to stabilize the issue “c++ vector subscript out of range”? I read a lot of topics about this, but all of them were trying to install anything. Is this the correct way, or any recommendation for me? Please find the beginning command below:
#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;
}
The cause:
This error happens because arr[10] is out of range, it has not been assigned yet. No matter how you index pushbacks, your vector has 10 elements indexed within the range from
0
(0
or1
) to9
, and all other0
elements. Therefore, your second loop containsv[j]
, from1
to9
.Solution:
To fix the error, you can do as below:
It will be better if you think of indexes as
0
-based. Therefore, we recommend you also replace your first loop by this:Moreover, iterators also can have access to the contents of a container. In this case, iterators can be used (in this example is a reverse iterator).
v
contains10
element. The index starts at0
to9
.You should update the
for
loopYou can also use reverse iterator for printing elements in reverse order