使用std::vector和.at()检查2D数组边界
2D array bounds checking using std::vector and .at()
我有一个很简单的问题,但是我找不到答案。
如何在二维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
}
相关文章:
- 如何在C++中检查2D数组中负值的输入验证
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 检查2D阵列中的有效性
- 如何检查 2D 数组在 c++ 中是否按升序排列?
- C 检查2D矢量是否遇到了障碍
- 如何检查2D数组中是否存在所有请求的值
- 如何检查2D阵列中的字符是否出现多次?C
- 框 2D 同时检查多个碰撞
- 找到一种正确"(快速而准确)的方式来查找检查 2D 游戏碰撞的内容。C++
- 检查 2D 数组中的相似数字
- C++ 从 2D 数组对角线检查
- 检查 2D 数组中是否存在元素,如果为 true,则返回一些内容
- 此 c++ 语句检查什么?(方框2d)
- 检查2d数组中相邻单元时出错
- 用贴图检查2D平台游戏中的碰撞
- 如何检查boost r-tree中的任何2d点是否在给定的三角形中
- 使用std::vector和.at()检查2D数组边界
- 检查2D数组中的对象是否为Null
- 检查2D Array中相邻的对角线位置
- 如何检查2D数组中的特定值