gpt4 book ai didi

c++ - 通过减少 if 语句使代码更高效

转载 作者:太空狗 更新时间:2023-10-29 20:36:21 25 4
gpt4 key购买 nike

我正在制作一个食谱分配器程序,它将根据以下内容打印食谱:

  • 食物的辣度
  • 做饭需要的时间

以后我可能会添加更多内容。

#include <iostream>
#include <string>
using namespace std;

int main()
{
string input = "";
string recipe1 = "A mild recipe that takes 10 mins";
string recipe2 = "A mild recipe that takes 20 mins";
string recipe3 = "A medium recipe that takes 10 mins";
string recipe4 = "a mild recipe that takes 20 mins";

cout << "Hello to the recipe dispenser 2000" << endl << "I will now begin with some questions to get the perfect recipe for you" << endl << "Do you like your food mild, medium, or hot?" << endl;
getline (cin, input);
if(input == "mild")
cout << "Would you like a recipe that takes 10 or 20 mins?" << endl;
getline (cin, input);
if(input == "10" or input == "10 mins")
cout << recipe1 << endl;
}

但是我现在的代码看起来效率很低,因为我必须写出总共 6 个 if 语句才能完成代码。

有什么办法可以缩短吗?
例如给每个食谱添加一些标签什么的,比如[10, mild]recipe1,然后代码会根据标签输出响应。

任何想法都会受到赞赏。

最佳答案

int main()
{
string input = "";
int inp;
map< string,map<int,string> > recipe;
recipe["mild"][10]="A mild recipe that takes 10 mins";
recipe["mild"][20]= "A mild recipe that takes 20 mins";
recipe["medium"][10]= "A medium recipe that takes 10 mins";

cout << "Hello to the recipe dispenser 2000" << endl << "I will now begin with some questions to get the perfect recipe for you" << endl << "Do you like your food mild, medium, or hot?" << endl;
getline (cin, input);
cout << "Would you like a recipe that takes 10 or 20 mins?" << endl;
cin>>inp;
try
{
cout<<(recipe.at(input)).at(inp);
}
catch(exception &e)
{
cerr<<input<<" , "<<inp<<" has not been invented yet!\n";
}
return 0;
}

在我看来,STL 的使用非常优雅。希望这对您有用。
引用

关于c++ - 通过减少 if 语句使代码更高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com