用c++写一个8个状态的状态机源码要用数组
时间: 2024-03-24 20:36:31 浏览: 60
状态机源码,C++
好的,以下是基于数组的8个状态的状态机的C++源代码:
```c++
#include <iostream>
using namespace std;
enum State {
STATE_1,
STATE_2,
STATE_3,
STATE_4,
STATE_5,
STATE_6,
STATE_7,
STATE_8
};
const int NUM_STATES = 8;
// State transition table
State stateTable[NUM_STATES][NUM_STATES] = {
{ STATE_2, STATE_4, STATE_1, STATE_6, STATE_5, STATE_3, STATE_7, STATE_8 },
{ STATE_6, STATE_1, STATE_2, STATE_8, STATE_3, STATE_5, STATE_4, STATE_7 },
{ STATE_4, STATE_3, STATE_2, STATE_1, STATE_7, STATE_8, STATE_6, STATE_5 },
{ STATE_5, STATE_6, STATE_7, STATE_8, STATE_1, STATE_2, STATE_3, STATE_4 },
{ STATE_7, STATE_2, STATE_3, STATE_4, STATE_5, STATE_1, STATE_8, STATE_6 },
{ STATE_3, STATE_5, STATE_4, STATE_2, STATE_8, STATE_6, STATE_1, STATE_7 },
{ STATE_8, STATE_7, STATE_6, STATE_5, STATE_4, STATE_3, STATE_2, STATE_1 },
{ STATE_1, STATE_8, STATE_5, STATE_7, STATE_6, STATE_4, STATE_3, STATE_2 }
};
int main() {
State currentState = STATE_1;
while (true) {
cout << "In state " << currentState + 1 << endl;
// Get next state from state table
currentState = stateTable[currentState][rand() % NUM_STATES];
}
return 0;
}
```
在这个状态机中,我们使用了一个二维数组`stateTable`来存储状态之间的转移关系。该数组的行和列索引都是从0开始,因此我们需要在输出当前状态时将状态值加1。在`while`循环中,我们使用`rand()`函数来生成一个随机数,以从当前状态的转移表中选择下一个状态。需要注意的是,这个状态机是无限循环的,因此需要手动停止程序。
阅读全文