How do i remove these if else statements using a conditional (ternary) operator
ID: 3748458 • Letter: H
Question
How do i remove these if else statements using a conditional (ternary) operator to convert tokens to dimensions.
if (tokens.size() == 0)
continue;
if (tokens.at(0) == "SQUARE") {
tokens.resize(2, "0");
Square* s = new Square;
s->length = atof(tokens.at(1).c_str());
myBag.push_back(s);
myBagType.push_back('S');
}
else if (tokens.at(0) == "RECTANGLE") {
tokens.resize(3, "0");
Rectangle* r = new Rectangle;
r->length = atof(tokens.at(1).c_str());
r->width = atof(tokens.at(2).c_str());
myBag.push_back(r);
myBagType.push_back('R');
}
else if (tokens.at(0) == "TRIANGLE") {
tokens.resize(3, "0");
Triangle* t = new Triangle;
t->length = atof(tokens.at(1).c_str());
myBag.push_back(t);
myBagType.push_back('T');
else if (tokens.at(0) == "EOF") {
continue;
}
else {
cout << tokens.at(0) << " invalid object" << endl;
}
Explanation / Answer
syntax for ternory operator:
(condition)? truth_part : False_part
using this operator we can replace else if in the following example.
(tokens.at(0) == "SQUARE")? goto SQR : (( tokens.at(0) == "RECTANGLE")? goto RECT :
(tokens.at(0) == "TRIANGLE")? goto TRI : (tokens.at(0) == "EOF")? goto EOF :goto ELSE);
SQR:
tokens.resize(2, "0");
Square* s = new Square;
s->length = atof(tokens.at(1).c_str());
myBag.push_back(s);
myBagType.push_back('S');
goto END;
RECT:
tokens.resize(3, "0");
Rectangle* r = new Rectangle;
r->length = atof(tokens.at(1).c_str());
r->width = atof(tokens.at(2).c_str());
myBag.push_back(r);
myBagType.push_back('R');
goto END;
TRI:
tokens.resize(3, "0");
Triangle* t = new Triangle;
t->length = atof(tokens.at(1).c_str());
myBag.push_back(t);
myBagType.push_back('T');
goto END;
EOF: continue
goto END;
ELSE: cout << tokens.at(0) << " invalid object" << endl;
goto END;
END: exit();
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.