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]<<"\n";
cout<<"size of a is "<<a.size()<<"\n";
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?
This is by design. To offer maximum performance, operator[]
does not check the argument for validity. Just like with naked arrays, accessing an element outside the bounds of a vector results in undefined behaviour.
...although I can access
a[10]
successfully...
This is a permissible manifestation of undefined behaviour. It is equally permissible for your code to throw an exception, to crash, to pass all your tests but then blow up in your customer's face, to launch a nuclear strike etc.
You could use std::vector::at(index)
for bounds-checked access. It throws std::out_of_range
if the index is not valid.
Bounds checking vs no bounds checking does not have to be an all-or-nothing proposition: see How to make std::vector's operator[] compile doing bounds checking in DEBUG but not in RELEASE and tools like Valgrind.
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