C++ Solution supporting self-defined operators using maps and function pointer


  • 0
    J
    // a typedef creates a fake type, in this
    // case for a function pointer
    typedef int (*compare_cb)(int a, int b);
    int add(int a, int b){
        return a+b;
    }
    int sub(int a, int b){
        return a-b;
    }
    int multi(int a, int b){
        return a*b;
    }
    int divd(int a, int b){
        if(b==0)return -1;
        else return a/b;
    }
    
    
    class Solution {
    private:
        unordered_map<string, compare_cb>ops;//key: operator string, value: function pointer
    
        int getRes(int a, int b, compare_cb cmp){
            return cmp(a, b);
        }
        
        void defineFunct(){//define your operator and functions
            ops["+"]=add;
            ops["-"]=sub;
            ops["*"]=multi;
            ops["/"]=divd;
        }
        
    public:
        int evalRPN(vector<string>& tokens) {
            int res = -1;
            stack<int>nums;
            defineFunct();
    
            for(auto t:tokens){
                if(ops.find(t) != ops.end())//if operator
                {
                    //int temp;
                    if(nums.size()<2)return -1;//not enough inputs
                    int b = nums.top(); nums.pop();//get second operand
                    int a = nums.top(); nums.pop();//get first operand
                    res = getRes(a, b, ops[t]);//get results
                    nums.push(res);
                }else{//if operand
                    int n = stoi(t);
                    nums.push(n);
                }
            }
            
            if(res==-1 && nums.size()==1){//result stored in stack
                res = nums.top();
                nums.pop();
            }
            //cout << res <<endl;
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.