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;
}
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.
Source: Stackoverflow.com