首页 > 解决方案 > 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.

标签: c++

解决方案


您需要使用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
}

推荐阅读