Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>4 -&gt; 8 \ 5 -&gt; 9 \_ action1() 6 -&gt; 10 / 7 -&gt; 11 / 8 -&gt; 4 \ 9 -&gt; 5 \_ action2() 10 -&gt; 6 / 11 -&gt; 7 / </code></pre> <p>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):</p> <pre><code>typedef std::function&lt;bool(int)&gt; TransitionCriteria; typedef std::function&lt;int(int)&gt; TransitionNewState; typedef std::function&lt;void(int)&gt; TransitionAction; // gets passed the old state </code></pre> <p>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.</p> <p>For the examples above, there would be two such transitions:</p> <pre><code>struct Transition { TransitionCriteria criteria; TransitionNewState newState; TransitionAction action; Transition(TransitionCriteria c, TransitionNewState n, TransitionAction a) : criteria(c), newState(n), action(a) {} }; std::vector&lt;Transition&gt; transitions; transitions.push_back(Transition( [](int oldState){ return oldState &gt;= 4 &amp;&amp; oldState &lt; 8; }, [](int oldState){ return oldState + 4; }, [](int oldState){ std::cout &lt;&lt; "action1" &lt;&lt; std::endl; } )); transitions.push_back(Transition( [](int oldState){ return oldState &gt;= 8 &amp;&amp; oldState &lt; 12; }, [](int oldState){ return oldState - 4; }, [](int oldState){ std::cout &lt;&lt; "action2" &lt;&lt; std::endl; } )); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload