Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c++ - Optimize Conditions

I've a simple question about conditions in if and for or while loops. Is there any way that lets me verify this condition with less 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...