cpp 中的条件运算符是否评估两个操作数?

Does conditional operator in cpp evaluate both operands?

https://leetcode.com/problems/decode-ways/

我的解决方案:

class Solution {
public:
    int numDecodings(string s) {
        vector<int> dp(s.size(),0);
        
        for(int i=0;i<s.size();i++)
        {
            int x =0;
            if(s[i]-'0'>0 && s[i]-'0'<=9)
            {
                x = (i>0)? dp[i-1]:1;
            } 
            if(i!=0 && stoi(s.substr(i-1,2))<=26)
            {
                cout<<i<<" ";
                x = x + (i>=2 )? dp[i-2]:1;
            }    
            dp[i] =x;
        }
        return dp[s.size()-1];
       
    }
};

运行 此代码给出此错误

Line 924: Char 34: runtime error: addition of unsigned offset to 0x602000000010 overflowed to 0x60200000000c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:34

我的问题是条件运算符是否计算 (i>=2) 中的 dp[i-2]? dp[i-2]:1; 即使条件不满足?用普通的 if-else 替换它解决了我的问题。

这条线并没有像你想象的那样评估。 x = x + (i>=2 )? dp[i-2]:1;

根据 this page,加法运算符的优先级高于三元运算符。将三元表达式放在括号中应提供所需的行为。

x += ((i>=2 ) ? dp[i-2] : 1); 完成任务。即使我更改了运算符以删除多余的 x,括号仍然是必需的。

这一行:

x = x + (i>=2) ? dp[i-2] : 1;

很可能没有按照您的意愿进行。三元组?:的优先级低于+,所以语句实际变为:

x = (x + (i>=2)) ? dp[i-2] : 1;

这意味着您正在检查 x + (i>=2)trueness 而不仅仅是 i>=2。这就是为什么即使 i < 2 也可以计算 dp[i-2],因为整个表达式 x + (i>=2) 仍然可以为真。

您可以自己加上明确的括号来解决这个问题:

x = x + ((i>=2) ? dp[i-2] : 1);

或者这样重写:

x += i>=2 ? dp[i-2] : 1;