如何正确缩短 C++ 中的 if 语句?

发布于 2024-12-05 04:01:53 字数 245 浏览 0 评论 0原文

好的,我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

深居我梦 2024-12-12 04:01:53

像这样的事情可能会起作用:

string s("%+-!");
if (s.find(letter) != string::npos) { ... } 

Something like this might work:

string s("%+-!");
if (s.find(letter) != string::npos) { ... } 
活泼老夫 2024-12-12 04:01:53

这是尽可能短的。不过你可以重写它,在 Boost 的帮助下,它可能是

if( boost::is_any_of( "%+-!" )( letter ) )

That's as short as it can. You could rewrite it though, with some help from Boost it could be

if( boost::is_any_of( "%+-!" )( letter ) )
世界等同你 2024-12-12 04:01:53

尝试使用 switch 语句代替 if。这并没有减少打字量,但它确实允许您只写一次“字母”。一些程序员喜欢 switch 语句的视觉布局。请注意,switch 仅适用于 char 等标量类型(不适用于 std::string)。

switch (letter)
{
  case '%':
  case '+':
  case '-':
  case '!':
     // if letter is %,+,-,!
     // code goes here for matching letter 
     break;
  default:
     // else do something different
     // code goes here for letter that doesn't match
}

请参阅页面底部 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).

switch (letter)
{
  case '%':
  case '+':
  case '-':
  case '!':
     // if letter is %,+,-,!
     // code goes here for matching letter 
     break;
  default:
     // else do something different
     // code goes here for letter that doesn't match
}

See bottom of page at http://www.cplusplus.com/doc/tutorial/control/ for a similar example.

追我者格杀勿论 2024-12-12 04:01:53

问题在于 || 运算符的任何一方彼此都不了解。它们是两个完全独立的表达方式。因此 "+" 等总是评估为 true (想想如果你只写 if ("+") 会发生什么 - 它衰减为一个非指针NULL

有时我发现使用 std::find 和一对迭代器来表达此类问题更清晰:

#include <iostream>
#include <algorithm>

void test(const char letter) {
  static const char c[] = {'%', '+', '-', '!'};
  static const char *begin=c, *end=&c[sizeof(c)/sizeof(*c)];
  if (std::find(begin, end, letter) != end) {
    std::cout << "Matched " << letter << std::endl;
  }
}

int main() {
  test('a');
  test('%');
  test('!');
}

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 wrote if ("+") - 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:

#include <iostream>
#include <algorithm>

void test(const char letter) {
  static const char c[] = {'%', '+', '-', '!'};
  static const char *begin=c, *end=&c[sizeof(c)/sizeof(*c)];
  if (std::find(begin, end, letter) != end) {
    std::cout << "Matched " << letter << std::endl;
  }
}

int main() {
  test('a');
  test('%');
  test('!');
}
全部不再 2024-12-12 04:01:53

我想最终的结果是尽可能少地输入内容,并尝试使用熟悉的语言(例如英语)来快速理解代码。

你的代码读起来像“我的信等于这个和这个和这个和这个”。可能有点啰嗦,但是很快就能理解。

不幸的是,C++ 编译器并没有真正做到“我的字母等于这些”。这对我们大多数人来说可能是英语,但对糟糕的编译器来说却不是:)

作为一名程序员,你有能力隐藏编译器素养的缺陷,保持你的代码易于理解并减少输入。

 if( letterIsOneOfThese( letter, "%+-!") )
 {
    // do something

 }


bool letterIsOneOfThese( const char letter, const char* letterList ) 
{
    int len = strlen( letterList );
    while( len-- )
    {
        if( letterList[len] == letter )
        {
            return true;
        }
    }

    return false;

}

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.

 if( letterIsOneOfThese( letter, "%+-!") )
 {
    // do something

 }


bool letterIsOneOfThese( const char letter, const char* letterList ) 
{
    int len = strlen( letterList );
    while( len-- )
    {
        if( letterList[len] == letter )
        {
            return true;
        }
    }

    return false;

}
—━☆沉默づ 2024-12-12 04:01:53
char op[4] = { '%', '+', '-', '!' };
char * opEnd(op + 4);
if (opEnd != find(op, opEnd, letter))

或者:

if (string("%+-!").find(letter) != string::npos)
char op[4] = { '%', '+', '-', '!' };
char * opEnd(op + 4);
if (opEnd != find(op, opEnd, letter))

Alternatively:

if (string("%+-!").find(letter) != string::npos)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文