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

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

本文关键字:访问 向量 索引 at 操作员      更新时间:2023-10-16
vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input[-1] <<endl;

使用上述代码,结果将是:index -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;

结果是:索引-1的输入为:libc abi.dylib:终止未被发现的类型std :: out_of_range:vector:vector。

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

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

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

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

第一个是未定义的行为。什么事情都可能发生。无论发生什么情况,您都不允许抱怨。

第二个例外,您不会抓住它,因此std::terminate()被称为,您的程序死亡。结尾。