优化这段代码 auto Agvs = this->getAgvs(); int agvNumber = 0; int allEnergy = 0; for (auto &agv : Agvs) { auto agvState = agv->getState(); if (agvState != AgvState::Offline) { auto agvEnergy = agv->getEnergy(); allEnergy =allEnergy + agvEnergy; agvNumber = agvNumber + 1; } } if (agvNumber != 0) { double num = allEnergy / agvNumber; QString m_averageEnergy = QString::number(num,'f',2); return m_averageEnergy; } else { return 0; }
时间: 2024-03-27 09:39:44 浏览: 135
基于改进时间窗的AGVs调度仿真研究与系统开发
可以尝试使用 STL 中的算法来优化代码。可以使用 std::accumulate 算法来计算 Agv 的总能量和数量,使用 std::count_if 算法来计算在线 Agv 的数量。这样可以减少循环次数,提高代码效率。下面是优化后的代码:
```
auto Agvs = this->getAgvs();
int allEnergy = std::accumulate(Agvs.begin(), Agvs.end(), 0, [](int sum, const auto& agv) {
if (agv->getState() != AgvState::Offline) {
return sum + agv->getEnergy();
}
return sum;
});
int agvNumber = std::count_if(Agvs.begin(), Agvs.end(), [](const auto& agv) {
return agv->getState() != AgvState::Offline;
});
if (agvNumber != 0) {
double num = static_cast<double>(allEnergy) / agvNumber;
QString m_averageEnergy = QString::number(num, 'f', 2);
return m_averageEnergy;
} else {
return "0";
}
```
阅读全文