Optimize Conditions

删除回忆录丶 提交于 2020-05-13 07:53:07

问题


I've a simple question about conditions in if, and for or while loops. Is there any way that allows me to verify this condition with fewer lines of code?

if (are_you_sure != "Si" && are_you_sure != "si"
 && are_you_sure != "No" && are_you_sure != "no")

I don't think i can minimize the code above, but I would like to be sure.

******EDIT******

Thanks for the answers! I minimized the code above with the code below:

int main()
{
    string choice;
    string list[4] = {"No", "no", "Yes", "yes"};

    cin >> choice;

    for (int i = 0; i < 4; ++i)
    {
        if (choice == list[i])
        {
            cout << "Is Here!";
            break;
        }
        else
        {
            cout << "\nNot found";
            cout << "\n" << i;
        }
    }
}

It helps me to understand how it works.


回答1:


You can write a lot less code, and make it more readable, if you have a function that does that for you:

if (none_of( are_you_sure, "Si", "si", "No", "no"))
  // ...

Of course, that function has to be written, but it's not too much code with c++17 fold-expressions:

template<typename T, typename ...Opts>
auto none_of(T val, Opts ...opts)
{
    return (... && (val != opts));
}  

This has some nice properties; it can take any number of arguments, and also be used with types other than strings:

int n = 42;
if (none_of( n, 1, 2, 3))
  // ...

Make sure to name the function well, as that affects readability a lot.



来源:https://stackoverflow.com/questions/61447353/optimize-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!