通过operator []和.at()访问向量的负索引

Fen*_*eng 3 c++ stl vector indexoutofboundsexception c++11

vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input[-1] <<endl;
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,结果将是:索引-1处的输入是:0.但是,如果我们使用follwoing:

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

结果是:索引-1处的输入是:libc ++ abi.dylib:以类型为std :: out_of_range:vector的未捕获异常终止.

有人可以向我解释原因吗?谢谢.

Cap*_*ffe 9

at成员进行范围检查并做出适当的响应.

operator []没有.这是未定义的行为和代码中的错误.

这在文档中明确说明.