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;
}
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.
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.
vector subscript out of range means "you asked for an element from the vector, but the vector is not of that size".
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With