【发布时间】:2013-01-19 04:21:40
【问题描述】:
我使用抽象数据类型来评估表达式树,这与以前的不同方式相反,我不确定如何准确地使用 map 函数。
好的,这个函数
int arithmetic_expression::evaluate_Expression(std::map< std::string, int > ipMap)
{
if (tree != NULL){
return(tree->evaluate(ipMap));
}
else
return(0);
}
调用这个函数,在这个函数中我不确定要返回什么
int Tree::evaluate(std::map< std::string, int > ipMap){
//not sure what to put in return to evaluate the expression
if(NodeType==TYPE_OPERATOR)
{
return())
}
我以前是这样用不同的方式做的
int arithmetic_expression::evaluate_Expression()
{
if (topPtr != NULL)
return(evaluateTree(topPtr));
else
{
std::cout<< "Invalid expression: returning 0"<< std::endl;
return(0);
}
}
}
}
int arithmetic_expression::evaluateTree(TreeNodePtr rootPtr)
{
if ((rootPtr->Op=="+") | (rootPtr->Op=="-")|(rootPtr->Op=="*")|(rootPtr->Op== "/"))
{
if (rootPtr->Op=="+")
{
return(evaluateTree(rootPtr->leftPtr)+ evaluateTree(rootPtr->rightPtr));
}
if (rootPtr->Op=="-")
{
return(evaluateTree(rootPtr->leftPtr)- evaluateTree(rootPtr->rightPtr));
}
if (rootPtr->Op=="*")
{
return(evaluateTree(rootPtr->leftPtr)* evaluateTree(rootPtr->rightPtr));
}
if (rootPtr->Op=="/")
{
return(evaluateTree(rootPtr->leftPtr)/ evaluateTree(rootPtr->rightPtr));
}
}
else
{
int Number;
std::istringstream(rootPtr->Op) >> Number;
return(Number);
}
【问题讨论】:
-
|是 按位或。你的意思可能是||。 -
基于我在之前的程序中所做的。我如何实现相同的东西,但使用地图的东西。如果 nodetype = + 然后返回评估(leftPtr->ipmap)+评估(rightPtr->ipmap)等,我会这样做吗?有点像上一个
标签: c++ tree expression infix-notation postfix-notation