我正在尝试为我的大学项目编写一个程序,该程序应该执行先到先服务调度,我对这个功能想了很多,但我不知道如何实现它工作时,我总是得到段错误:11,我也尝试使用temp.at(j),但它给了我段错误:6 ,我尝试最小化 vector ,以便通过在函数外部声明 vector 来将 vector 进行入站,然后使用 temp.size() 而不是 Processes 但它也没用。
void FCFS(Process ProcessDetails[], int Processes)
{
vector<int> temp;
vector<int> temp1;
int first = 0; //first value to compare with.
for(int j = 0; j < Processes; j++){ // to make sure that it passes through all elements.
for(int i = 0; i < Processes; i++){ // pass each PID and Burst time to vector temp and temp1.
if(ProcessDetails[i].ArrivalTime == first){
temp.operator[](j) = ProcessDetails[i].PID;
temp1.operator[](j) = ProcessDetails[i].BurstTime;
}
}
first++;// increase first value to declare the round is finished and start a new one.
}
for(int i = 0; i < Processes; i++){ // pass the sorted vector values back to the arrays.
ProcessDetails[i].PID = temp.operator[](i);
ProcessDetails[i].BurstTime = temp1.operator[](i);
}
}
程序工作正常,直到达到此功能,请帮忙。
最佳答案
vector 的行为operator[]()
如果用于访问不存在的元素,则未定义。
由于您使用了默认构造的 vector ,因此它们的大小为零 - 因此它们没有可供访问的元素。
如果您使用.at()
成员函数,它将检查索引并在索引无效时抛出异常(类型为 std::out_of_range
,在标准头 <stdexcept>
中声明)。您可以通过将代码包装在适当的 try
中来确认这一点。/catch
block 。
要消除该问题,您需要在使用 push_back()
之前调整 vector 的大小(例如,使用 resize()
添加元素,使用 operator[]()
调整其大小等)。 。并确保索引有效,因为 operator[]()
不调整 std::vector
的大小.
此外,temp[j]
相当于 temp.operator[](j)
。对于提供 operator[]()
的类型函数时,编译器处理像 temp[j]
这样的转向表达式调用temp.operator[](j)
.
关于c++ - 段错误: 11 c++ when using vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517703/