在检查矢量边界的同时运行光标
Run cursor through vector while checking its bounds
我有一个光标,它的"位置"由代码的另一部分决定。我的意图是让这个光标检查向量的下一个和上一个对象,并检查条件。如果它是有效的,光标将占据该对象的位置。以下是我想法的一些示例代码:
class A
{
bool valid;
public:
A(bool v) {valid=b;}
bool IsValid() {return valid;}
};
void CheckNearbyValidity()
{
/*if the object to the right is valid, update position to this object*/
if(exampleVector.at(cursor-1).IsValid())
{
/*do stuff*/
cursor = (cursor-1);
}
/*if the object to the right isnt valid, try the same thing to the left*/
else if(exampleVector.at(position+1).IsValid())
{
/*do stuff*/
cursor = (cursor+1);
}
/*leave if none are valid*/
}
我在这里遇到的问题是,如果光标位于向量的开始或结束处,检查if条件会导致它抛出一个超出范围的异常。
我的解决方案是在查询矢量之前检查新的光标位置是否有效:
void CheckNearbyValidity()
{
/*if the object to the right is valid, update position to this object*/
if(cursor-1 >= 0)
{
if(exampleVector.at(cursor).IsValid())
{
/*do stuff*/
cursor = (cursor-1);
}
}
/*new position makes the next condition always true and returns cursor to the same position*/
if(cursor-1 < exampleVector.size())
{
if(exampleVector.at(cursor+1).IsValid())
{
/*do stuff*/
cursor = (cursor+1);
}
}
/*leave if none are valid*/
}
新的问题是,由于我不能再使用"else",这两个条件都是有效的,并且光标将保持在它开始的位置。
我解决这个问题的方法是将函数包围在while循环中,并在必要时中断:
void CheckNearbyValidity()
{
while(true)
{
if(cursor-1 >= 0)
{
if(exampleVector.at(cursor-1).IsValid())
{
/*do stuff*/
position = (cursor-1);
break;
}
}
if(cursor-1 >= 0)
{
if(exampleVector.at(cursor+1).IsValid())
{
/*do stuff*/
position = (cursor+1);
break;
}
}
break;
}
}
我的问题是,"single"while loop方法是个坏主意吗?有更好的方法来操作这个光标吗
您应该利用&&
:的力量
if (cursor-1 >= 0 &&
exampleVector.at(cursor-1).IsValid())
{
/*do stuff*/
position = (cursor-1);
}
else if (cursor+1 < exampleVector.size() &&
exampleVector.at(cursor+1).IsValid())
{
/*do stuff*/
position = (cursor+1);
}
这允许您像最初那样将两个语句连接在一起作为if-else
,只需要额外的验证步骤根据向量边界检查cursor
。
&&
执行短路评估。如果cursor-1 >= 0
的求值结果为false
,则代码跳过对exampleVector.at(cursor-1).IsValid()
的求值,并立即跳到对else
子句的求值。
同样,在else if
子句中,如果cursor+1 < exampleVector.size()
的求值结果为false
,则&&
短路,并且代码跳过对exampleVector.at(cursor+1).IsValid()
的求值,再次使其安全。
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 如何在Qt C++中更改光标
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- openGL GLFW 白屏,带加载光标正在运行
- 为什么当我在Visual c ++ studio 2010中运行应用程序时光标会转到最后一个文本框
- 在检查矢量边界的同时运行光标