我正在解决 leetcode 上的问题。我编写了代码,但收到一些运行时错误,提示引用绑定到未对齐的地址
I was solving a problem on leetcode. I did the code but I am receiving some runtime error saying reference binding to misaligned address
给定一个每日温度列表 T,return 一个列表,这样对于输入中的每一天,您必须等待多少天才能变暖。如果没有可能的未来日期,请改为输入 0。
例如,给定温度列表 T = [73, 74, 75, 71, 69, 72, 76, 73],您的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0].
注意:温度的长度将在 [1, 30000] 范围内。每个温度都是 [30, 100] 范围内的整数。
这是我写的代码。
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<pair<int, int>> s;
vector<int> res(T.size());
for(int i=T.size()-1; i>=0; i--) {
if(s.empty()) {
s.push(make_pair(T[i], i));
res[i] = 0;
} else {
while(s.top().first < T[i]) {
s.pop();
}
res[i] = s.top().second - i;
s.push(make_pair(T[i], i));
}
}
return res;
}
};
下面给出了我遇到的错误。
Error image
你还没有问任何问题,但我假设它是
"Why does this code trigger a runtime error?"
这个代码
while(s.top().first < T[i]) {
s.pop();
}
不检查 s
是否为空。
当s.empty()
为真时,s.pop()
将触发未定义行为。
另外,
res[i] = s.top().second - i;
也不检查 s
是否为空,如果是则触发未定义行为。
给定一个每日温度列表 T,return 一个列表,这样对于输入中的每一天,您必须等待多少天才能变暖。如果没有可能的未来日期,请改为输入 0。
例如,给定温度列表 T = [73, 74, 75, 71, 69, 72, 76, 73],您的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0].
注意:温度的长度将在 [1, 30000] 范围内。每个温度都是 [30, 100] 范围内的整数。
这是我写的代码。
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<pair<int, int>> s;
vector<int> res(T.size());
for(int i=T.size()-1; i>=0; i--) {
if(s.empty()) {
s.push(make_pair(T[i], i));
res[i] = 0;
} else {
while(s.top().first < T[i]) {
s.pop();
}
res[i] = s.top().second - i;
s.push(make_pair(T[i], i));
}
}
return res;
}
};
下面给出了我遇到的错误。 Error image
你还没有问任何问题,但我假设它是
"Why does this code trigger a runtime error?"
这个代码
while(s.top().first < T[i]) {
s.pop();
}
不检查 s
是否为空。
当s.empty()
为真时,s.pop()
将触发未定义行为。
另外,
res[i] = s.top().second - i;
也不检查 s
是否为空,如果是则触发未定义行为。