c++ - How to catch out_of_range exception for range error (vector off-by-one error)
问题描述
I am trying to get a custom error message after a vector off by one error.
I am using code blocks.
for (int x; cin>>x; )
v.push_back(x);
for (int i = 0; i<=v.size(); ++i) //to print values
cout << "v[" << i <<"] == " << v[i] << '\n';
return 0;
I expected that after the error i<=v.size() I would get an error message, but instead I get a random error value for the last vector value entered.
解决方案
您需要使用at()
函数访问元素。从文档中:
返回对指定位置 pos 的元素的引用,并进行边界检查。
如果 pos 不在容器的范围内,则抛出 std::out_of_range 类型的异常。
所以你需要做的就是用[]
by替换元素访问at()
:
std::vector<int> vec;
// insert value into v
vec.push_back(...);
// Read your vector by checking out of bound access using .at() method
for (int i = 0; i<=vec.size(); ++i) {//to print values
std::cout << "v[" << i <<"] == " << vec.at(i) << std::endl;
}
您还可以像这样遍历 a 的每个元素std::vector
:
// Copy each element of the vector into element
for(auto element: vec) {
// Do stuff
}
您还可以访问向量中元素的 const / mutable 引用:
// Accessing constant reference to every element in the vector
for(const auto& const_element_ref: vec) {
// Do stuff
}
// Accessing mutable reference to every element in the vector, potentially modifying it
for(auto& element_ref: vec) {
// Do stuff
}
推荐阅读
- jdbc - 为复合行实现 SQLData 接口
- javascript - 有没有办法在每一步更改时调用一个函数?
- android - 为什么我可以在低于`build.gradle`中指定的`minSdkVersion`的设备上安装与我的设备兼容的应用程序版本?
- ansible - 如何在角色中访问 ansible 事实?
- java - 如何在android中实现字典
- web - 如何在模板 Web 组件(vanilla js)中链接 js 脚本?
- java - Statement.execute() 函数返回布尔值
- flutter - 在组按钮中添加项目
- javascript - 当页面返回 404 时如何将带有 typescript 的 create-react-app 部署到 Netlify
- android - Capacitor Deeplink 不适用于某些应用,但适用于其他应用