for (const auto& task : tasks) { //std::cout << "Task name: " << task.id << ", Completed: " << task.completed << ", Priority: " << task.priority << std::endl; } // 遍历任务列表,分配任务给可用的小车 for (auto& task : tasks) { if (task.completed == 0) { // 只分配未完成的任务 AGV* closest_agv = nullptr; int wait_time = 0; // 等待时间计数器 // 初始化为 nullptr while (closest_agv == nullptr && wait_time < 3) { // 最多等待 1 秒钟 // 查找可用的小车 for (auto& agv : agvs) { if (agv.getState()) { closest_agv = &agv; break; } } if (closest_agv == nullptr) { // 没有可用的小车,等待一段时间再查找 std::this_thread::sleep_for(std::chrono::seconds(1)); wait_time++; } } if (closest_agv != nullptr) { // 找到可用小车 // 找到最近的可用小车 int min_distance = INT_MAX; for (auto& agv : agvs) { if (agv.getState()) { int distance = abs(agv.getCurrentX()- task.start_x) + abs(agv.getCurrentY() - task.start_y); if (distance < min_distance) { min_distance = distance; closest_agv = &agv; } } } // 将任务分配给 AGV 对象的起点和终点坐标 closest_agv->setStartCoord(task.start_x, task.start_y); closest_agv->setEndCoord(task.end_x, task.end_y); closest_agv->setState(false); // 小车被占用 task.completed = 1; // 任务状态修改为进行中 std::cout << "agv_id" << closest_agv->getid() << "————" << "task_id"<<task.id << endl; } else { std::cout << "task_id-" << task.id << "No available AGV!" << endl; } } },修改爲黨沒有可用小車的時候直接退出
时间: 2023-11-27 22:51:12 浏览: 88
可以将最外层的for循环改为while循环,当所有任务都已经完成或者没有可用的小车时,退出循环。修改代码如下:
```c++
while (std::any_of(tasks.begin(), tasks.end(), [](const Task& t) { return t.completed == 0; })) {
bool task_assigned = false; // 标记是否有任务被分配
for (auto& task : tasks) {
if (task.completed == 0) {
AGV* closest_agv = nullptr;
int wait_time = 0;
while (closest_agv == nullptr && wait_time < 3) {
for (auto& agv : agvs) {
if (agv.getState()) {
closest_agv = &agv;
break;
}
}
if (closest_agv == nullptr) {
std::this_thread::sleep_for(std::chrono::seconds(1));
wait_time++;
}
}
if (closest_agv != nullptr) {
int min_distance = INT_MAX;
for (auto& agv : agvs) {
if (agv.getState()) {
int distance = abs(agv.getCurrentX()- task.start_x) + abs(agv.getCurrentY() - task.start_y);
if (distance < min_distance) {
min_distance = distance;
closest_agv = &agv;
}
}
}
closest_agv->setStartCoord(task.start_x, task.start_y);
closest_agv->setEndCoord(task.end_x, task.end_y);
closest_agv->setState(false);
task.completed = 1;
task_assigned = true;
std::cout << "agv_id" << closest_agv->getid() << "————" << "task_id"<<task.id << endl;
} else {
std::cout << "task_id-" << task.id << "No available AGV!" << endl;
break; // 直接退出循环
}
}
}
if (!task_assigned) {
std::cout << "All tasks completed!" << endl;
break; // 所有任务都已经完成,退出循环
}
}
```
这样,当没有可用的小车时,会直接退出循环,而不是继续等待。
阅读全文