c++中对空队列使用front()函数报错

问题发生在写leetcode994腐烂的橘子的时候。这道题只要朴素的广搜就能A,我第一次提交的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int orangesRotting(vector<vector<int>>& grid) {
queue<vector<int>> q;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; // 方向数组,分别指向上下左右四个方向
int m=grid.size(),n=grid[0].size(),cnt=0,ans;
// 已腐烂的橘子入队
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
if (grid[i][j]==2){
vector<int> a={i,j,0}; // (x坐标,y坐标,腐烂时间)
q.push(a);
}
if (grid[i][j]==1) cnt++; //新鲜橘子个数
}
}
// 广度优先搜索
while (!q.empty()){
vector<int> a=q.front(); //出队
q.pop();
// 传染邻格的橘子
for (int i=0;i<4;i++){
int x=a[0]+dir[i][0],y=a[1]+dir[i][1];
if (x>=0&&x<m&&y>=0&&y<n&&grid[x][y]==1){
cnt--; //新鲜橘子减少
vector<int> temp={x,y,a[2]+1};
q.push(temp); // 刚腐烂的橘子入队
grid[x][y]=2;
}
}
ans=q.front()[2]; //最后一个橘子出队前,ans将更新为其腐烂时间
}
if (cnt==0) return ans; // 不存在新鲜橘子
else return -1;
}

然后出现了以下报错:

1
Line 1037: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebec6 for type 'int', which requires 4 byte alignment (stl_vector.h)

经过检查,发现是“ans=q.front()[2];”这行代码未进行判空,导致在队列为空时引用了front()函数而产生错误。

将改行代码修改为“if (!q.empty()) ans=q.front()[2];”后问题解决。