使用std::vector和.at()检查2D数组边界

2D array bounds checking using std::vector and .at()

本文关键字:检查 2D 数组 边界 at std vector 使用      更新时间:2023-10-16

我有一个很简单的问题,但是我找不到答案。

如何在二维vector < vector <type> >数组中使用.at(i) ?

我想有边界检查-开关.at(i)功能自动提供,但我只能访问我的数组使用array[i][j]开关不提供边界检查。

正确的语法是:

array.at(i).at(j)

由于.at(i)将在v[i]返回对vector的引用,因此使用.at(i).at(j)

使用vec.at(i).at(j),必须在try-catch块中使用,因为at()如果索引无效将抛出std::out_of_range异常:

try
{
      T & item = vec.at(i).at(j);
}
catch(const std::out_of_range & e)
{
     std::cout << "either index i or j is out of range" << std::endl;
}
编辑:

正如你在评论中所说的:

我实际上希望程序在引发异常时停止。- JBSSM 5 mins ago

在这种情况下,您可以在打印出超出范围的消息后,在catch块中重新抛出,这样您就可以知道它停止的原因。下面是如何重新抛出:
catch(const std::out_of_range & e)
{
     std::cout << "either index i or j is out of range" << std::endl;
     throw; //it rethrows the excetion
}