When I was using vector class, I found out that there is no compilation error or run time error when indexing out of range of a vector. The problem can be shown by the following code
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<double> a(10,0.0);
a[10]=10.0;
cout<<"a[10]="<<a[10]<<"
";
cout<<"size of a is "<<a.size()<<"
";
return 0;
}
The result of running this code is
a[10]=10
size of a is 10
with no error reported. Another thing to notice is that a.size()
still returns 10
, although I can access a[10]
successfully.
My question is that is there a way to let the program report an error when one tries to index out of the range of a vector?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…