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.

2 Answers 2

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.

3
  • 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
    Commented Dec 15, 2016 at 5: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. Commented Dec 15, 2016 at 5:46
  • Thank you. Yeah , it is a coincidence I guess.
    – Feng
    Commented Dec 15, 2016 at 5: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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.