[C++] 简易有限状态机

switcher是切换状态用的,接受一个输入,返回加下来该转到哪个状态
func是该状态要执行的内容

#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <map>

struct State
{
	std::function<std::string(char)> switcher;
	std::function<void()> func;
};

struct FSM
{
	std::map<std::string, State> states;
	State *curr;
	bool running;

	// 注册一个状态
	void reg(const std::string &name, const State &state)
	{
		states.insert(std::pair<std::string, State>{name, state});
	}

	// 处理输入
	void process(char ch)
	{
		std::string result = curr->switcher(ch);
		if (result.empty())
		{
			running = false;
			return;
		}

		curr = &states.at(result);
		curr->func();
	}
};

std::string start_switcher(char ch)
{
	if (ch == '6')
		return "end";
	else
		return "start";
}

std::string end_switcher(char) { return ""; }

void start_func()
{
	std::cout << "start" << std::endl;
}

void end_func()
{
	std::cout << "end" << std::endl;
}

int main(int argc, char *argv[])
{
	State start;
	start.switcher = start_switcher;
	start.func = start_func;

	State end;
	end.switcher = end_switcher;
	end.func = end_func;

	FSM fsm;
	fsm.reg("start", start);
	fsm.reg("end", end);

	// 设置初始状态
	fsm.running = true;
	fsm.curr = &start;

	// 运行
	fsm.curr->func();
	while (fsm.running)
	{
		char ch;
		std::cin>>ch;
		fsm.process(ch);
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值