C++ code for state machine

前端 未结 6 863
暖寄归人
暖寄归人 2020-12-04 05:49

This was an interview question to be coded in C++:

Write code for a vending machine: Start with a simple one where it just vends one type of item. So

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 06:12

    I once wrote a state machine in C++, where I needed the same transition for a lot of state pairs (source → target pairs). I want to illustrate an example:

    4 -> 8   \
    5 -> 9    \_ action1()
    6 -> 10   /
    7 -> 11  /
    
    8 -> 4   \
    9 -> 5    \_ action2()
    10 -> 6   /
    11 -> 7  /
    

    What I came up with was a set of (transition criteria + next state + "action" function to be called). To keep things general, both the transition criteria and the next state were written as functors (lambda functions):

    typedef std::function TransitionCriteria;
    typedef std::function  TransitionNewState;
    typedef std::function TransitionAction;   // gets passed the old state
    

    This solution is nice if you have a lot of transitions which apply for a lot of different states as in the example above. However, for each "step", this method requires to linearly scan the list of all different transitions.

    For the examples above, there would be two such transitions:

    struct Transition {
        TransitionCriteria criteria;
        TransitionNewState newState;
        TransitionAction action;
    
        Transition(TransitionCriteria c, TransitionNewState n, TransitionAction a)
            : criteria(c), newState(n), action(a) {}
    };
    std::vector transitions;
    
    transitions.push_back(Transition(
        [](int oldState){ return oldState >= 4 && oldState < 8; },
        [](int oldState){ return oldState + 4; },
        [](int oldState){ std::cout << "action1" << std::endl; }
    ));
    transitions.push_back(Transition(
        [](int oldState){ return oldState >= 8 && oldState < 12; },
        [](int oldState){ return oldState - 4; },
        [](int oldState){ std::cout << "action2" << std::endl; }
    ));
    

提交回复
热议问题