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

人气:925 发布:2022-10-16 标签: c++ stl c++11 indexoutofboundsexception vector

问题描述

vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input[-1] <<endl;
使用上面的代码,结果将是:index-1处的输入为:0。 但是,如果我们使用以下命令:

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

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

有人能给我解释一下原因吗?谢谢。

推荐答案

at成员执行范围检查并做出相应响应。

operator []不需要。这是未定义的行为,也是代码中的错误。

文件中明确说明了这一点。

659