如何正确缩短 C++ 中的 if 语句?
好的,我有一个 if 语句,其中多次比较特定值。我敢打赌有一种更短的方法可以做到这一点:
if(letter == "%" || letter == "+" || letter == "-" || letter == "!")
我尝试将其写为:
if(letter == "%" || "+" || "-" || "!")
但它工作不正确。
Okay, I have an if sentence in which I compare a specific value multiple times. I bet there is a shorter way to do this:
if(letter == "%" || letter == "+" || letter == "-" || letter == "!")
I tried writing it as:
if(letter == "%" || "+" || "-" || "!")
But it works incorrectly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样的事情可能会起作用:
Something like this might work:
这是尽可能短的。不过你可以重写它,在 Boost 的帮助下,它可能是
That's as short as it can. You could rewrite it though, with some help from Boost it could be
尝试使用 switch 语句代替 if。这并没有减少打字量,但它确实允许您只写一次“字母”。一些程序员喜欢 switch 语句的视觉布局。请注意,switch 仅适用于 char 等标量类型(不适用于 std::string)。
请参阅页面底部 http://www.cplusplus.com/doc/tutorial/control/< /a> 类似的例子。
Try a switch statement in-stead of an if. It's not less typing, but it does allow you to write "letter" only once. Some programmers like the visual layout of a switch statement. Note of caution, switch only works on scalar types like char (not std::string).
See bottom of page at http://www.cplusplus.com/doc/tutorial/control/ for a similar example.
问题在于
||
运算符的任何一方彼此都不了解。它们是两个完全独立的表达方式。因此"+"
等总是评估为 true (想想如果你只写if ("+")
会发生什么 - 它衰减为一个非指针NULL
)有时我发现使用
std::find
和一对迭代器来表达此类问题更清晰:The problem is that either side of the
||
operator has no knowledge of each other. They're two completely independent expressions. Consequently"+"
etc. always evaluate as true (think of what would happen if you just wroteif ("+")
- it decays to a pointer which is non-NULL
)Sometimes I find it is cleaner to express this kind of problem using
std::find
and pair of iterators:我想最终的结果是尽可能少地输入内容,并尝试使用熟悉的语言(例如英语)来快速理解代码。
你的代码读起来像“我的信等于这个和这个和这个和这个”。可能有点啰嗦,但是很快就能理解。
不幸的是,C++ 编译器并没有真正做到“我的字母等于这些”。这对我们大多数人来说可能是英语,但对糟糕的编译器来说却不是:)
作为一名程序员,你有能力隐藏编译器素养的缺陷,保持你的代码易于理解并减少输入。
I guess the end result is to type as little as possible and attempt to keep your code quick to comprehend by using something familiar like English.
Your code reads something like,'is my letter equal to this and this and this and this'. It may be a bit long winded but it is quite quick to comprehend.
Unfortunately c++ compilers don't really do 'is my letter equal to these'. Which may be English to most of us but not to poor compilers :)
As a programmer you have the power to hide the compiler literacy shortfalls, keep your code comprehendable and also type less.
或者:
Alternatively: