3
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.

Feng
  • 67
  • 1
  • 9

2 Answers2

9

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.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
  • Could you please tell me what bug could be? It seems for every input vector, its index at -1 is always 0 when I use operator[]. – Feng Dec 15 '16 at 05:45
  • 1
    @FengZhou That is a coincidence that you see a `0` at that position. It is still an illegal statement. You are looking outside the contents of the vector. The content you are not allowed to look at contains a `0`. – Captain Giraffe Dec 15 '16 at 05:46
  • Thank you. Yeah , it is a coincidence I guess. – Feng Dec 15 '16 at 05:50
3

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436