Created
February 11, 2020 16:42
-
-
Save EvanMu96/71ab30e3714ea7abfb19383d1dc9b305 to your computer and use it in GitHub Desktop.
translate inexpr into suffexpr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <string> | |
using namespace std; | |
// the operation only contains add and substract | |
enum operation {ADD, SUB}; | |
//for leaf node(digit), the value only exist in left val | |
struct inexpr | |
{ | |
inexpr* obj1; | |
inexpr* obj2; | |
int val; | |
operation op; | |
int getval() | |
{ | |
int result = 0; | |
if(obj1) | |
{ | |
result += obj1->getval(); | |
} | |
if(obj2) | |
{ | |
result += obj2->getval(); | |
} | |
if(!obj1 && !obj2) | |
{ | |
result += val; | |
} | |
return result; | |
} | |
}; | |
// interprete inexpr into AST | |
inexpr* build_inexpr(string str) | |
{ | |
inexpr* result = nullptr; | |
if(str.empty()) | |
{ | |
return result; | |
} | |
int num_op = 0; | |
vector<int> op_pos; | |
int divide_index = 0; | |
for(int i = 0; i < str.size(); i++) | |
{ | |
if(str[i] == '+' || str[i] == '-') | |
{ | |
num_op++; | |
op_pos.push_back(i); | |
} | |
} | |
if(num_op == 0) | |
{ | |
result = new inexpr; | |
result->val = stoi(str); | |
result->obj1 = nullptr; | |
result->obj2 = nullptr; | |
} | |
else | |
{ | |
int index = op_pos[num_op / 2]; | |
result = new inexpr; | |
result->op = str[index] == '+' ? ADD : SUB; | |
result->obj1 = build_inexpr(str.substr(0, index)); | |
result->obj2 = build_inexpr(str.substr(index+1)); | |
} | |
return result; | |
} | |
void view(inexpr* head) | |
{ | |
if(head->obj1) | |
{ | |
view(head->obj1); | |
} | |
if(head->obj2) | |
{ | |
view(head->obj2); | |
if(head->op == ADD) | |
{ | |
cout << " + "; | |
} | |
else | |
{ | |
cout << " - "; | |
} | |
} | |
if(!head->obj1 && !head->obj2) | |
{ | |
cout << head->val << " "; | |
} | |
} | |
void test_build(string foo) | |
{ | |
inexpr* result = build_inexpr(foo); | |
view(result); | |
cout << endl; | |
} | |
int main() | |
{ | |
test_build("1+2+3+3+4"); | |
test_build("1+34+3"); | |
inexpr* size_test = new inexpr; | |
cout << "for a structure" << " : " << sizeof(size_test) << endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment