Accessing negative index of vector via operator[] and .at()

1.4k Views Asked by At
vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input[-1] <<endl;

Using the above the code, the result will be: input at index -1 is: 0. However, if we use follwoing :

vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input.at(-1) <<endl;

The result would be : input at index -1 is: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector.

Can some one explain the reason to me? Thank you.

2

There are 2 best solutions below

3
On BEST ANSWER

The at member does range-checks and responds appropriately.

The operator [] does not. This is undefined behavior and a bug in your code.

This is explicitly stated in the docs.

0
On

The first is undefined behavior. Anything could happen. You aren't allowed to complain, no matter what happens.

The second, an exception is thrown and you don't catch it, so std::terminate() is called and your program dies. The end.