找到最近的对象,从你的位置上适当的方式QT c++
Find the closest object from your position on a proper way QT c++
我试图从玩家的位置找到最近的生命包或敌人。我是这样写的:
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重命名为更清晰的名称,以便将来参考。
相关文章:
- 使用 QT C++过滤大数据的最佳方式
- 以编程方式在任何按钮上突出显示 Qt 鼠标悬停按钮
- Qt全局快捷方式扩展劫持快捷方式
- 在Qt Creator中应用代码更改的快捷方式是什么?
- 如何在Qt WebChannel中以独立于平台的方式在HTML/Javascript和C++之间进行通信?
- 尝试使用 Qt 库中的 QPixmap 将图像拆分为多个块。关于他的复制方法的工作方式,我有什么不明白的吗?
- 如何将Qt嵌入到另一个应用程序中(非阻塞方式)
- 如何为 QT Windows 应用程序设置不同的桌面快捷方式图标和任务栏图标不同
- C++ Qt - 检查 Steam 游戏是否以编程方式运行
- QT-写入SQL数据库时,空的qlineedits不会以null的方式传递
- 执行随机开关函数的QT方式是什么连续两次使用相同情况的方法
- 有没有办法在Qt中以编程方式中断鼠标拖动
- Qt中数据类(模型)和视图/控制器类之间的数据通信的正确方式是什么
- 在Qt中以高性能方式将(富)文本附加到QTextEdit或QTextBrowser中
- QT Designer-设置样式表 - 现在进行硬编码 - 想要以编程方式设置
- 触发快捷方式(QT)时的lambda表达
- 此应用程序已请求运行时以异常方式终止它 QT C++
- 使用 QPixmap 和 QLabel 在 Qt Creator 中以编程方式添加图像文件 (.PNG)
- Qt:对于生产者-消费者模式中的消费者来说,这是正确的退出方式吗
- 找到最近的对象,从你的位置上适当的方式QT c++