在检查矢量边界的同时运行光标



我有一个光标,它的"位置"由代码的另一部分决定。我的意图是让这个光标检查向量的下一个和上一个对象,并检查条件。如果它是有效的,光标将占据该对象的位置。以下是我想法的一些示例代码:

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()的求值,再次使其安全。

最新更新