#pragma once #include #include #include #include #include #include using namespace std; //去除所有空格 void RemoveSomeChar(string& text, char ascii); //截取非逻辑字符串 string GetKeyValueString(const string& str); void SplitKeyValueOprString(const string& str, string& key,string& value,string& opr); //****************节点结构体************************** //表达式二叉树形式:支持算数表达式、逻辑表达式解析(二者不可同时启用) struct TreeNode; //****************表达式类************************** using SMGetValueCallback = std::function; class CcosExpression { public: enum EN_TreeType //二叉树节点类型 { TT_Null, TT_Number, TT_bool, TT_Max }; CcosExpression(EN_TreeType treeType = TT_bool); ~CcosExpression(); //设置优先级 //参数数组中的char代表二元逻辑运算符(必须是单字符的特殊ASCII符号),int代表运算符优先级(取值必须>=0) //其中,必须有:'#'优先级最小, '('优先级次之, ')'优先级最大,其余逻辑符合理的安排在'('与')'之间即可 void SetPriorityMap(map& Map_type_level); void GetPriorityMap(map& Map_type_level); //构建二叉树,用于解析中缀表达式 bool CreateTree(string strText, list& nodeValueList); //销毁二叉树 void DestroyTree(TreeNode* root); //打印二叉树 void Show(vector>& strPrint); //计算二叉树 template bool CalculateExpression(T& value, SMGetValueCallback fun = nullptr) { bool ret{ false }; try { if (m_pRoot) { m_funGetValue = fun; if (typeid(T) == typeid(bool) && m_eTreeType == TT_bool) { value = GetBoolValue(m_pRoot); ret = true; } else if ((typeid(T) == typeid(int) || typeid(T) == typeid(float) || typeid(T) == typeid(double)) && m_eTreeType == TT_Number) { value = GetNumberValue(m_pRoot); ret = true; } else { //mLog::FERROR("treeType failed"); ret = false; } m_funGetValue = nullptr; } } catch (...) { //mLog::FERROR("CalculateExpression crash"); } return ret; } protected: void SetRootNode(stack& operatorStacks, vector& dataArray, TreeNode*& curNode);//设计一个单元的二叉树(一个父节点,两个子节点) void SetSingleNode(vector& dataArray, TreeNode*& curNode);//设计一个单节点的二叉树(一个父节点,无子节点) void SetRightTree(TreeNode* curNode, char operatorType, string rightData);//在当前节点的右子树最下方重新构建一个单元的二叉树 void SetTopTree(stack& operatorStacks, vector& dataArray, TreeNode*& curNode);//在当前节点上方重新构建一个单元的二叉树 void SetTree(stack& operatorStacks, vector& dataArray, TreeNode*& curNode, bool flag);//根据不同的情况(运算符的优先级)构建不同的二叉树单元 int CheckPriority(char operatorType);//判断优先级 bool IsLeftSymbol(stack stacks);//判断当前栈中是否包含'('操作符 int JudgeKeyValue(const string& data); //截取关键词 double GetNumberValue(TreeNode* node); //计算算数表达式 bool GetBoolValue(TreeNode* node); //计算逻辑表达式 private: EN_TreeType m_eTreeType{ TT_bool }; //节点类型 map glo_PriorityMap; //优先级列表, 逻辑、算数运算符:优先级 TreeNode* m_pRoot{ nullptr }; //根节点 SMGetValueCallback m_funGetValue{ nullptr }; //获取条件当前值 };