通过操作员[]和.at()访问向量的负索引
Accessing negative index of vector via operator[] and .at()
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()
被称为,您的程序死亡。结尾。
相关文章:
- 特征命名访问向量段
- 在无法访问向量的情况下查找迭代器的末尾
- 访问向量字段的键 - 枚举类还是命名空间中的枚举?
- 访问向量索引C++
- 如何通过迭代器访问向量中的嵌套对?
- 访问向量并将数据导出到文件
- 通用迭代器可以访问向量的元素,而无需使用模板C
- 如何使用指针访问向量元素的各个元素
- 使用 "find" 访问向量中的值
- 从触摸回调访问向量元素的方法时,不良访问错误
- 访问向量类中的成员变量
- 可以使用整数索引访问向量元素吗?
- 访问向量类成员时出现分段错误
- 从对象创建矢量包装器,该对象只允许使用索引访问向量
- C++ 访问向量动态数组中的违规读取位置0xFFFFFFFFFFFFFFFF
- 如何访问向量内的向量
- 访问向量C 中的分割故障
- 通过操作员[]和.at()访问向量的负索引
- 从DLL访问向量
- 用于访问向量的通用迭代器