这个if语句有快捷方式吗?

时间:2019-08-19 03:18:57

标签: c++

我正在做作业,遇到了问题。请教我“ if”是否有任何捷径。

if ch=='a'||ch=='o'||ch=='y'||ch=='e'||ch=='u'||ch=='i'||ch=='A'||ch=='O'||ch=='Y'||ch=='E'||ch=='U'||ch=='I') then continue;

非常感谢您!

3 个答案:

答案 0 :(得分:3)

取决于您对shortcut的理解:如果只想编写更少的代码,则可以:

if(strchr("aoyeuiAOYEUI", ch)) { /* ... */ }

但这只是掩盖了工作,实际上,还有更多工作要做(检查有问题的字符终止的空字符)...

如果您认为方向相反,则可以使用查找表:

static int const Lookup[256] = { ['a'] = 1, ['o'] = 1, /* ... */ };
// values not specified explicitly are set to 0

if(Lookup[ch]) { /* ... */ }

这将花费一些内存,但是只有256个条目,这不会受到损害(如果您担心的话,如果在交易中使用charbool,您可以放心一些速度)。不过,它可能是最快的。同样,一个开关/案例也可能更有效(通常在内部创建一个跳转表,但是如果不将其保留给编译器,则无法保证):

switch(ch)
{
    case 'a': case 'o': /* ... */
        /* ... */
        break; // in case of continue, as in question, or even return,
               // there's no need for the break...
    default:
        /* what's to be done if NOT matching */
        break;
}

答案 1 :(得分:1)

首先,使用std::toupper()std::tolower()将需要比较的可能字符数减少一半。

char my_toupper(char ch)
{
    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}

然后,您可以使用std::find()std::string::find()switch语句来比较剩余的可能性:

#include <cctype>
#include <algorithm>

const char vowels[6] = "AOYEUI";

if (std::find(std::begin(vowels), std::end(vowels), my_toupper(ch)) != std::end(vowels))
    continue;
#include <string>
#include <cctype>

const std::string vowels("AOYEUI");

if (vowels.find(my_toupper(ch)) != std::string::npos)
    continue;
#include <cctype>

switch (my_toupper(ch))
{
    case 'A':
    case 'O':
    case 'Y':
    case 'E':
    case 'U':
    case 'I':
        continue;
}

答案 2 :(得分:0)

您可以使用setunordered_set。它可以让您知道它是否存在于一个操作中,而无需链接条件。

我将字符转换为小写,因此我们在集合中不需要那么多的条目,但是您可以轻松地在集合中同时包含大小写字符。

下面是一个示例,它循环显示可能的值并打印结果。

例如

#include <unordered_set>
#include <iostream>

int main() 
{
    std::unordered_set<char> s{'a', 'o', 'y', 'u', 'i'};
    char chars[] = {
        'a', 'o', 'y', 'u', 'i', 
        'A', 'O', 'Y', 'U', 'I', 
        'b', 'Z', 's', 'd'
    };

    for(char c: chars)
    {
        if(s.find(tolower(c)) != s.end())
            std::cout << c << " YES\n";
        else
            std::cout << c << " NO\n";
    }
}