【问题标题】:!st.empty() is throwing runtime error if kept after &&!st.empty() 如果保留在 && 之后会抛出运行时错误
【发布时间】:2023-01-25 14:07:52
【问题描述】:

while(!st.empty() && nums[i%n] >= st.top()) st.pop();

这段代码有效但是

while(nums[i%n] >= st.top() && !st.empty()) st.pop();

这不是!

我正在解决 leetcode 503(Next Greater Element II),我的答案是

    int n = nums.size();
    stack<int> st;
    vector<int> nge(n, -1);

    for(int i = 2*n-1; i >= 0; i--) {
        while(nums[i%n] >= st.top() && !st.empty()) st.pop();
        if(i < n && !st.empty()) nge[i%n] = st.top();
        st.push(nums[i%n]);
    }
    
    return nge;`

但它没有用,除非我把!st.empty()放在nums[i%n] &gt;= st.top()之前

【问题讨论】:

  • 听起来一切正常。如果 st.empty() 为真,那么访问 st.top() 将无效,因为它不存在。因此,您需要先测试 st.empty ,短路评估将使 st.top() 在没有时被评估。
  • 逻辑 AND 和 OR 运算符 &amp;&amp;|| 使用 short-circuit evaluation。简而言之,使用您显示的代码,即使堆栈为空,您也可以调用 st.top(),这会导致未定义的行为.

标签: c++ data-structures stl


【解决方案1】:

在第一个版本中,首先检查堆栈是否为空,然后才检查是否为nums[i%n] &gt;= st.top()。这很重要,因为如果堆栈为空,st.top() 将抛出错误,程序将崩溃。

在第二个版本中,您首先检查是否 nums[i%n] &gt;= st.top() ,然后才检查堆栈是否为空。在这种情况下,如果堆栈为空,st.top() 将抛出错误,程序甚至在达到第二个条件(!st.empty()) 之前就会崩溃。

所以它只有在你把!st.empty()放在nums[i%n] &gt;= st.top()之前才有效

在检查栈顶元素之前,您必须确保堆栈不为空。

更多:Short Circuit Evaluation

【讨论】:

  • 谢谢你,基兰!它帮助了很多。
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2013-06-04
  • 1970-01-01
相关资源
最近更新 更多