找到最近的对象,从你的位置上适当的方式QT c++

Find the closest object from your position on a proper way QT c++

本文关键字:方式 QT 位置 c++ 最近 对象      更新时间:2023-10-16

我试图从玩家的位置找到最近的生命包或敌人。我是这样写的:

for(auto &hp : model->getAllHealthPacks()){
    if(!hp->getUsed()){
        int x = hp->getXPos();
        int y = hp->getYPos();
        int q = (x*x)+(y*y);
        if(q < smallest){
            smallest = z;
            hpfound = hp;
            foundAHp++;
        }
    }
}

现在我想知道,这实际上是不正确的。有更好的和专业的方法来改进我的代码吗?(λ,……)?

代码总体上还不错,但仍有改进的余地。首先,您可以将变量hp设置为常量,因为您没有修改它的内容。

您还可以创建一个类来将坐标存储在单个对象中,如下所示

class Coordinate{
    std::pair<int,int> coords;
...
};

最后的代码看起来像这样:

for(const auto &hp : model->getAllHealthPacks()){
    if(!hp->getUsed()){
        Coordinate coord(hp->getCoord());
        int q = coord.getX()*coord.getX()+coord.getY()*coord.getY();
        if(q < smallest){
            smallest = z;
            hpfound = hp;
            foundAHp++;
        }
    }
}

您还应该将q重命名为更清晰的名称,以便将来参考。