mercredi 29 juillet 2020

Does conditional operator in cpp evaluate both operands?

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

my solution:

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];
       
    }
};

Running this code gives this error

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

My question is does the conditional operator evaluate dp[i-2] in (i>=2 )? dp[i-2]:1; even if the condition doesn't satisfy? Replacing it with a normal if-else solved my problem.

Aucun commentaire:

Enregistrer un commentaire