带有过度约束类的梦魇表达式树
Nightmare Expression Tree with over-constrained class
我无意中让我的学生过度约束了一个用于解决以下问题的共享类。我意识到这可能是这个网站的居民可能会喜欢的一个问题。
第一个team/函数getNodes接受一个字符串,该字符串使用带符号整数和+、-、*和/四种操作表示前缀表达式,并使用类Node生成相应的以空结尾的令牌链表,令牌通过"右"指针链接。
第二个team/函数getTree接受一个类似的字符串,将其传递给getNodes,并将结果节点链接为一个表达式树。
第三个团队/函数evaluate接受一个类似的字符串,将其传递给getTree,并计算结果表达式树以形成答案。
后面是过度约束的exp .h。这个问题必须通过只写上面定义的三个函数来解决,不写其他函数。
#ifndef EXPTREE_H_
#define EXPTREE_H_
using namespace std;
enum Ops{ADD, SUB, MUL, DIV, NUM};
class Node {
private:
int num;
Ops op;
Node *left, *right;
public:
friend Node *getNodes(string d);
friend Node *getTree(string d);
friend int evaluate (string);
};
int evaluate(string d);
Node *getNodes(string d);
Node *getTree(string d);
#endif
唯一可以使用的库是这些
#include <iostream>
#include <vector>
#include <string>
#include "exptree.h"
对于那些担心我的学生的人,我今天会指出,只要有几个更好的函数,这个问题就会很容易解决。我知道表达式树可以编码有理数而不仅仅是整数。我今天也会指出这一点。
这是我根据他们的规格给他们的驱动程序。
#include <iostream>
#include <string>
#include "exptree.h"
using namespace std;
void test(string s, int target) {
int result = evaluate(s);
if (result == target)
cout << s << " correctly evaluates to " << target << endl;
else
cout << s << "(" << result
<< ") incorrectly evaluates to " << target << endl;
}
int main() {
test("42", 42);
test("* - / 4 2 1 42", 42);
test("* - / -4 +2 -1 2", -2);
test("* - / -4 +2 -1 2 ", -2);
test("* 9 6", 54);
return 0;
}
你能以尽可能优雅的方式写出这三个函数来解决这个噩梦般的问题吗?
在这些约束条件下,getNodes
和getTree
函数的编写非常简单,所以我直接跳到有趣的部分。您自然会对表达式树进行递归求值,但这里不允许这样做,因为eval函数只接受一个字符串。当然,您可以将剩下的树重新组合成一个前缀表达式,并在其上递归地调用eval,但这将是愚蠢的。
首先,我将表达式树转换为后缀表达式,使用显式堆栈作为穷人的递归。然后用标准操作数栈对其求值
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "exptree.h"
int evaluate(string d){
Node* tree = getTree(d);
//convert tree to postfix for simpler evaluation
vector<Node*> node_stack;
node_stack.push_back(tree);
Node postfix_head;
Node* postfix_tail = &postfix_head;
while(node_stack.size() > 0){
Node* place = node_stack.back();
if(place->left == 0){
if(place->right == 0){
postfix_tail->right = place;
node_stack.pop_back();
} else {
node_stack.push_back(place->right);
place->right = 0;
}
} else {
node_stack.push_back(place->left);
place->left = 0;
}
}
//evaluate postfix
Node* place = postfix_head.right;
vector<int> stack;
while(place != 0){
if(place->op != NUM){
int operand_a, operand_b;
operand_b = stack.back();
stack.pop_back();
operand_a = stack.back();
stack.pop_back();
switch(place->op){
case ADD:
stack.push_back(operand_a + operand_b);
break;
case SUB:
stack.push_back(operand_a - operand_b);
break;
case MUL:
stack.push_back(operand_a * operand_b);
break;
case DIV:
stack.push_back(operand_a / operand_b);
break;
}
} else {
stack.push_back(place->num);
}
place = place->right;
}
return stack.back();
}
我认为"没有额外的功能"是一个太苛刻的要求。实现例如getTree
的最简单的方法可能是递归的,它需要定义一个额外的函数。
Node* relink(Node* start) // builds a tree; returns the following node
{
if (start->op == NUM)
{
Node* result = start->right;
start->left = start->right = NULL;
return result;
}
else
{
start->left = start->right;
start->right = relink(start->left);
return relink(start->right);
}
}
Node* getTree(string d)
{
Node* head = getNodes(d);
relink(head);
return head;
}
我可以通过使用显式堆栈实现递归(由std::vector
实现),但这是丑陋和模糊的(除非你想让你的学生练习)。
不管它的价值,这是我在发布问题之前编写的解决方案
#include <iostream>
#include <vector>
#include "exptree.h"
using namespace std;
Node *getNodes(string s) {
const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;
Node *list;
int sign, num;
s += " "; // this simplifies a lot of logic, allows trailing white space to always close off an integer
list = (Node *) (num = sign = 0);
for (int i=0; i<s.size(); ++i) {
char c = s[i]; // more efficient and cleaner reference to the current character under scrutiny
if (isdigit(c)) {
if (sign == 0) sign = 1; // if sign not set, then set it. A blank with a sign==0 now signifies a blank that can be skipped
num = 10*num + c - '0';
} else if (((c=='+') || (c=='-')) && isdigit(s[i+1])) { // another advantage of adding blank to string above so don't need a special case
sign = (c=='+') ? 1 : -1;
} else if ( !isspace(c) && (c != '+') && (c != '-') && (c != '*') && (c != '/')) {
cout << "unexpected character " << c << endl;
exit(1);
} else if (!isspace(c) || (sign != 0)) { // have enough info to create next Node
list->left = (list == 0) ? (list = new Node) : (list->left->right = new Node); // make sure left pointer of first Node points to last Node
list->left->right = 0; // make sure list is still null terminated
list->left->op = (c=='+' ? ADD : (c=='-' ? SUB : (c=='*' ? MUL : (c=='/' ? DIV : NUM)))); // choose right enumerated type
list->left->num = (list->left->op==NUM) ? sign*num : MININT; // if interior node mark number for evaluate function
num = sign = 0; // prepare for next Node
}
}
return list;
}
Node *getTree(string s) {
Node *nodes = getNodes(s), *tree=0, *root, *node;
vector<Node *> stack;
if (nodes == 0) return tree;
root = tree = nodes;
nodes = nodes->right;
for (node=nodes; node != 0; node=nodes) {
nodes = nodes->right;
if (root->op != NUM) { // push interior operator Node on stack til time to point to its right tree
stack.push_back(root);
root = (root->left = node); // set interior operator Node's left tree and prepare to process that left tree
} else {
root->left = root->right = 0; // got a leaf number Node so finish it off
if (stack.size() == 0) break;
root = stack.back(); // now pop operator Node off the stack
stack.pop_back();
root = (root->right = node); // set its left tree and prepare to process that left tree
}
}
if ((stack.size() != 0) || (nodes != 0)) {
cout << "prefix expression has missing or extra terms" << endl;
exit(1);
}
return tree;
}
int evaluate(string s) {
// MININT is reserved value signifying operator waiting for a left side value, low inpact since at edge of representable integers
const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;
Node *tree = getTree(s);
vector<Node *> stack;
int v = 0; // this is value of a leaf node (a number) or the result of evaluating an interior node
if (tree == 0) return v;
do {
v = tree->num;
if (tree->op != NUM) {
stack.push_back(tree);
tree = tree->left; // prepare to process the left subtree
} else while (stack.size() != 0) { // this while loop zooms us up the right side as far as we can go (till we come up left side or are done)
delete tree; // done with leaf node or an interior node we just finished evaluating
tree = stack.back(); // get last interior node from stack
if (tree->num == MININT) { // means returning up left side of node, so save result for later
tree->num = v;
tree = tree->right; // prepare to evaluate the right subtree
break; // leave the "else while" for the outer "do while" which handles evaluating an expression tree
} else { // coming up right side of an interior node (time to calculate)
stack.pop_back(); // all done with interior node
v = tree->op==ADD ? tree->num+v : (tree->op==SUB ? tree->num-v : (tree->op==MUL ? tree->num*v : tree->num/v)) ;
}
}
} while (stack.size() != 0);
return v;
}
- (C++)分析树以计算返回错误值的简单算术表达式
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 提升精神:解析布尔表达式并简化为规范范式
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用正则表达式regex_search在字符串中查找字符串
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 概念中的cv限定符需要表达式参数列表
- 为什么constexpr的性能比正常表达式差
- 对于结构,表达式必须是可修改的ivalue
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 将fold表达式与std::一起用于两个元组
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 标记 '","' 之前的预期主表达式
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 带有用户定义类的c++折叠表达式
- 即使使用调试编译标志,表达式也是"optimized out"
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 带有过度约束类的梦魇表达式树