gpt4 book ai didi

c++ - 在检查边界的同时通过 vector 运行光标

转载 作者:行者123 更新时间:2023-11-28 07:16:55 24 4
gpt4 key购买 nike

我有一个游标,其“位置”由代码的另一部分确定。我的意图是让这个游标检查 vector 的下一个和上一个对象并检查条件。如果它有效,则光标将占据该对象的位置。这是我的想法的一些示例代码:

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*/
}

我这里遇到的问题是,如果游标在vector的开头或者结尾,检查if条件会导致抛出超出范围的异常。

我的解决方案是在查询 vector 之前检查新的光标位置是否有效:

 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;
}
}

我的问题是,“单一”while 循环方法是个坏主意吗?有没有更好的方法来操作这个光标?

最佳答案

您应该利用 && 的力量:

    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针对 vector 边界。

&&执行短路评估。如果cursor-1 >= 0评估为 false , 然后代码跳过评估 exampleVector.at(cursor-1).IsValid()并立即跳转到评估 else条款。

同样,在 else if 中子句,如果cursor+1 < exampleVector.size()评估为 false , &&短路,代码跳过评估 exampleVector.at(cursor+1).IsValid() ,再次使其安全。

关于c++ - 在检查边界的同时通过 vector 运行光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20085368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com