给出这样的矩阵:
state1_input1 state1_input2 state1_input3 state2_input1 state2_input2 state2_input3 state3_input1 state3_input2 state3_input3
当你处于状态n并接收输入m时,你会看到行n,列m以找出新状态。假设您有3种可能的状态和4种可能的输入,那么您需要做的就是:
state = transition_table[state][input]
根据您的描述,您不需要二维数组,1维是好的。它应该这样:
void foo() { int States[2] = {1,2}; int currentState = 1;///initial state, let's say int oldState;///prev. state while(true) { if(currentState == 1 && *add any other condition that you need*) { <...>do something<...> oldState = currentState;//saving the old state, in case you need it. currentState = states[currentState]; //changing the state } else if( currentState == 2 && *add any other condition that you need*) { <...>some other code<...> } }
所以你有一系列的状态。然后根据输入参数计算该数组的索引(你说你使用旧状态和其他东西)。之后,您只需通过该索引从数组中获取新状态。 我的解释有点混乱,所以如果你需要澄清某些部分,请留言。