cmh's recent activity

  1. Comment on Programming Challenge: Reverse Polish Notation Calculator in ~comp

    cmh
    (edited )
    Link
    A C++17 version - with constexpr compile time support. Slightly hacky fixed size stack to allow compile time generation. Expects completely valid input. #include <string_view> #include <cstdio.h>...

    A C++17 version - with constexpr compile time support. Slightly hacky fixed size stack to allow compile time generation. Expects completely valid input.

    #include <string_view>
    #include <cstdio.h>
    
    //from_chars isn't constexpr for standard reasons
    constexpr void from_chars_local(const char *s, const char *t, int &x) {
    	x = 0;
    	while (s != t) {
    		x = x * 10 + *s - '0';
    		s++;
    	}
    }
    
    constexpr int eval_rpn(const std::string_view &s) {
    	int stack[128] = {};
    	int sind = 0;
    
    	std::string_view::size_type i = 0, j = 0;
    	
    	while (i != s.size()) {
    		switch (s[i]) {
    		case '+':
    			stack[sind - 2] = stack[sind - 2] + stack[sind - 1]; sind -= 1;
    			break;
    		case '-':
    			stack[sind - 2] = stack[sind - 2] - stack[sind - 1]; sind -= 1;
    			break;
    		case '*':
    			stack[sind - 2] = stack[sind - 2] * stack[sind - 1]; sind -= 1;
    			break;
    		case '/':
    			stack[sind - 2] = stack[sind - 2] / stack[sind - 1]; sind -= 1;
    			break;
    		case ' ':
    			break; // can't i+=2 in constexpr
    		default:
    			j = s.find_first_of(' ', i);
    			from_chars_local(&s[i], &s[j], stack[sind++]);
    		}
    
    		i = i>j ? i + 1 : j + 1;
    	}
    
    	return stack[0];
    }
    
    int main()
    {
            static_assert(eval_rpn("15 7 1 1 + - / 3 * 2 1 1 + + -") == 5)
    }
    
    4 votes