逻辑判断原则

耗尽温柔 提交于 2020-02-09 07:08:14

判定多个条件时,遵循从左到右,短路原则。

Q:

  if ( conditionA && conditionB ) 和 if ( conditionA || conditionB ),是先判断conditionA还是conditionB ?跟编译器有没有关系?

A:

  先判断conditionA再判断conditionB和编译器无关
  不过对于&&只要conditionA为假conditionB就不判断了
  对于||只要conditionA为真conditionB就不判断了
  因为结果已经知道了

在调程序的时候发现如下代码会报错:

    int largestRectangleArea(vector<int>& heights) {
        heights.push_back(0);
        stack<int>staIndex;
        int area = 0;
        for(int i = 0; i < heights.size(); i ++){        //while(!staIndex.empty() && heights[i] <= heights[staIndex.top()]) Correct!
            while( heights[i] <= heights[staIndex.top()] && !staIndex.empty() ){//Wrong!int h = heights[staIndex.top()];
                staIndex.pop();
                int leftId = staIndex.size() == 0? -1: staIndex.top();
                int width = i - leftId - 1;
                area = max(area, h * width);
            }

            staIndex.push(i);
        }
        return area;
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!