因此,我有一个作业,其中有一个转向信号灯,并允许汽车一个一个通过。方向以顺时针顺序更改。我实现了一个代码,该代码读取初始启动方向,每个方向的车辆通过,并读取车牌,方向和通过时间。从E到S到W到N时会发生问题,但是它卡住了,我遇到矢量超出范围
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct cars
{
string name;
char dr;
int t;
};
bool init(vector<cars> &arr, char direct)
{
for (auto i = 0; arr.size(); i++)
{
if (arr.at(i).dr == direct)
{
return true;
}
}
return false;
}
char direct_shift(char e)
{
if (e == 'N')
{
return 'E';
}
else if (e == 'E')
{
return 'S';
}
else if (e == 'S')
{
return 'W';
}
else if (e == 'W')
{
return 'N';
}
else
{
return '\0';
}
}
int main() {
vector <cars> keeper;
queue <cars> que;
char track; //starting direction
int car_num; //starting car num
string n;
char d;
int sec;
cin >> track;
cin >> car_num;
while (cin >> n >> d >> sec) //takes the input if plate, direction and time
{
cars temp;
temp.name = n;
temp.dr = d;
temp.t = sec;
keeper.push_back(temp);
}
for (int i = 0; i < keeper.size(); i++) {
cout << keeper[i].name << " " << keeper[i].dr << " " << keeper[i].t << endl;
} //checks if it all inputted it
char curr_dir = track;
while (not keeper.empty())
{
for (auto i = 0; i < keeper.size(); i++) {
reset:
if (init(keeper, curr_dir) == true)
{
if (keeper[i].dr == curr_dir) {
que.push(keeper.at(i)); //pushes vector at i into queue
keeper.erase(keeper.begin() + i); // deletes vector at index i
cout << que.front().name << " Going to " << que.front().dr << " at " << que.front().t << endl;
que.pop();
curr_dir = direct_shift(curr_dir);
break;
}
}
else
{
curr_dir = direct_shift(curr_dir);
}
}
}
}
答案 0 :(得分:-1)
由于以下功能,我认为您遇到了问题:
bool init(vector<cars> &arr, char direct) {
for (auto i = 0; arr.size(); i++) {
if (arr.at(i).dr == direct) {
return true;
}
} return false;
}
如果尝试访问不存在的索引, arr.at(i)
将引发out_of_range
异常。这意味着在访问索引之前,您需要确保向量不为空/大小不超过
bool init(vector<cars> &arr, char direct) {
//the loop now checks for (!arr.empty())
for (vector<cars>::size_type i = 0; i <arr.size(); ++i) {
if (arr.at(i).dr == direct) {
return true; }
} return false;
}