【发布时间】:2020-05-27 03:28:18
【问题描述】:
if (calculation == "help") {
cout << "add, subtract, multiplication, divide\nsquare root, sin, cos, power\n";
}
else if (calculation == "add") {
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
}
else if (calculation == "subtract") {
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
}
else if (calculation == "multiplication") {
cout << num1 << " x " << num2 << " = " << num1 * num2 << endl;
}
else if (calculation == "divide") {
cout << num1 << " / " << num2 << " = " << num1/ num2 << endl;
}
else if (calculation == "square root") {
cout << "The square root of the first number is " << sqrt(num1) << ". The square root of the second number is " << sqrt(num2) << "." << endl;
}
else if (calculation == "sin") {
cout << "The sine of the first number is " << sin(num1) << ". The sine of the second number is " << sin(num2) << "." << endl;
}
else if (calculation == "cos") {
cout << "The cosine of the first number is " << cos(num1) << ". The cosine of the second number is " << cos(num2) << "." << endl;
}
else if (calculation == "power") {
cout << num1 << " to the power of " << num2 << " = " << pow(num1, num2) << endl;
}
我有一个解决这些 if 语句的想法,例如创建地图或字典。我不相信您也可以在 C++ 中将字符串与 switch 语句一起使用。非常感谢任何帮助!
编辑:我可以使用地图。
map<string, int> Choices = {
{ "help", 0 },
{ "add", 1 },
{ "subtract", 2 },
{ "multiply", 3 },
{ "divide", 4 },
{ "square root", 5 },
{ "sine", 6 },
{ "cosine", 7 },
{ "power", 8 }
};
it = Choices.find(choice);
i = it->second;
如果有更快的方法,请告诉我。感谢大家的回复!
【问题讨论】:
-
把它们放在 enum 中并有一个 switch 代替。看this回答
-
让我们假设您(和问题的)原因是您被来自外部来源的字符串(例如消息)所困扰。由于您使用的是 C++,因此您可以使用 std::strings(啊,我看到您说过——是的,这是个好主意)作为键和您选择的类似函数的对象作为值来创建映射。您也可以尽早将它们转换为枚举(也可以使用地图),然后使用开关。
-
密钥会在其他地方使用吗?在
stp::map<std::string, std::function<void(int, int)>>中移动它只会在地图初始化中移动冗长的东西。不确定您是否真的提高了可读性。 -
您是否测试过性能并将解决方案与 map 和 if 语句进行比较。我可能是地图解决方案比 ifs 慢。在为性能编码时,您总是需要考虑处理器缓存以及预取器的工作方式。如果列表的类型只存储几个项目,数组通常比地图快。
标签: c++ if-statement