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

标签 c++

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

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

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

#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/

相关文章:

c++ - 将 C++ 中的结构转换为 Ruby

c++ - 跨编译器读写原始对象到磁盘(istream)

c++ - 复制构造函数初始化列表

c++ - 安装 Visual Studio 2015 时出现错误,有关 "Microsoft Visual C++ 2015 Redistributable"

c++ - 体系结构 x86_64 : error 的 undefined symbol

c++ - 为什么无法访问的代码在 C++ 中不是错误?

c++ - 哪种方法更适合霍夫曼编码我想用它们的频率读取字符

c++ - ctime std::命名空间冲突

c++ - constexpr - "Evaluate value at compile time"到底是什么意思?

c++:在多线程程序中写入文件