从矢量超出范围错误中恢复

时间:2011-12-30 12:31:00

标签: c++ exception-handling vector

是否可以从C ++中的矢量“遥不可及”错误中恢复?

喜欢这个功能:

vector<int> numbers;

bool isAccessable(int i)
{
   try
   {
  numbers[i];
   catch (...)
    {
    return false;
    }

return true;
}

它可能在C#中,但是c ++?

3 个答案:

答案 0 :(得分:3)

在C ++中,没有对operator []的范围检查,但是有for :: at()。

尝试

numbers.at(i);

代替。

答案 1 :(得分:3)

如果您只是想检查索引是否在范围内,那么只需:

return i < numbers.size();

(您还应该与零进行比较,或者将索引更改为无符号类型; size_t是通常用于数组索引的类型。)

如果您想尝试访问该值,并在索引超出范围时抛出异常,请使用at而不是[]

try {
    do_something_with(numbers.at(i));
    return true;
} catch (std::out_of_range const &) {
    return false;
}

答案 2 :(得分:1)

使用std::vector::at()成员函数。它抛出out_of_range例外。