优化条件 [英] Optimize Conditions
问题描述
我有一个关于if
和for
或while
循环中条件的简单问题.
有什么方法可以让我用更少的代码行来验证这种情况?
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.
推荐答案
如果您有可以帮助您做到这一点的函数,则可以编写更少的代码,并使代码更具可读性:
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"))
// ...
当然,必须编写该函数,但是使用c ++ 17 fold-expressions并不需要太多代码:
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.
这篇关于优化条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!