c++ - “Deque 迭代器不可取消引用”错误
问题描述
我正在尝试遍历一个双端队列并擦除到达时间最短的元素。该函数前几次工作,然后给我“迭代器不可取消引用”错误并停止工作。
我的Processor.h
:
#pragma once
#include <deque>
#include "Job.h"
#include <ctime>
using namespace std;
class Processor {
public:
deque<Job> priorityQueue;
Job runningJob;
bool isProcessing;
int processingTime;
int runningTime;
int overallJobs;
int numJobs[4]; //0 is A, 1 is B, 2 is C, 3 is D
int runningJobNumber;
int interruptedJobs;
Processor();
void simulate();
Job findNextJob();
};
我的findNextJob()
:
Job Processor::findNextJob() {
Job nextJob = priorityQueue.front();
deque<Job>::const_iterator iter = priorityQueue.begin();
deque<Job>::const_iterator location;
while (iter <= priorityQueue.end()) {
if (iter->arrivalTime < nextJob.arrivalTime) {
nextJob = *iter;
location = iter;
iter++;
}
else {
iter++;
}
}
priorityQueue.erase(location);
return nextJob;
}
最后,我在哪里调用函数:
void Processor::simulate() {
srand(time(NULL));
char newJobType;
while (processingTime <= 50) {
newJobType = 65 + rand() % 4;
Job newJob(newJobType);
newJob.arrivalTime += runningTime;
processingTime += newJob.processingTime;
priorityQueue.push_back(newJob);
cout << endl << newJob.type << " " << newJob.arrivalTime;
runningTime++;
}
runningTime = 0;
int jobFinishTime;
Job nextJob;
nextJob = findNextJob();
while (priorityQueue.size()) {
cout << endl << runningTime << ") " << "Queue size: " << priorityQueue.size();
if (!isProcessing) {
cout << " CPU 1 Idle;";
if (nextJob.arrivalTime == runningTime) {
runningJob = nextJob;
//irrelevant code here
nextJob = findNextJob();
}
}
if (isProcessing && (runningJob.arrivalTime + runningJob.processingTime) != runningTime) {
//irrelevant code here
if (nextJob.arrivalTime <= runningTime) {
runningJob = nextJob;
//irrelevant code here
nextJob = findNextJob();
}
}
if (nextJob.priority > runningJob.priority && nextJob.arrivalTime <= runningTime) {
//irrelevant code here
}
runningTime++;
}
}
findNextJob()
成功运行两三次然后给我错误。任何帮助,将不胜感激。
解决方案
在 C++ 中,结束迭代器“指向”最后一个元素之后的位置。
findNextJob 允许迭代器iter
等于priorityQueue.end()
,因此取消引用它是无效的。
while (iter <= priorityQueue.end()) {
// ...
}
推荐阅读
- python - relation in between a categorical dependent variable and combination of independent variables
- c++ - 在hackerearth中获取TLE
- c# - C# Show Sql table in console application
- google-apps-script - Google Data Studio 社区连接器 - 如何跨多个查看者将凭据共享给第 3 方端点?
- excel - 在已关闭的工作簿中搜索行,然后将行中的特定数据单元格(不是整行)复制到我当前的工作簿中
- amazon-web-services - 是否有 AWS 服务来分块和并发执行对 Lambda 的批量请求?
- javascript - js数组不显示内容
- python - Pandas:修改特定级别的Multiindex,多次使用replace方法
- javascript - 为什么 XHR 成功并在 chromeDevTools 中显示但未定义且无法由 JSON.parse() 解析
- android - 用户撤销权限