与C++中的多个char进行比较

Dan*_*iel 1 c++ char

假设我有一个存储在a中的输入char c,并且在条件中我需要检查它是否是两个不同的字符,例如'n''N'.很明显,我可以使用逻辑OR运算符进行条件化:

if(c == 'n' || c == 'N')
...
Run Code Online (Sandbox Code Playgroud)

但是,如果只有两个以上的条件,则需要使用更多的逻辑运算符,编写,查看和编辑将变得冗长乏味.有没有办法压缩这个过程?为了使它看起来像这样的东西:

if(c == '[N][n]')
...
Run Code Online (Sandbox Code Playgroud)

有什么类似的存在吗?

sco*_*001 8

您可以创建匹配字符的字符串,并查看字符串中是否存在相关字符:

char c;
std::string good_chars = "nNyYq";
if(good_chars.find(c) != std::string::npos) {
    std::cout << "it's good!";
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ckl 5

低技术解决方案是使用switch声明.case如果你有很多匹配的字符,那么使用标签可以更容易地阅读和编辑.

bool matches(char c)
{
    switch (c)
    {
        case 'n':
        case 'N':
        case 'a':
        case 'b':
        case 'c':
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

更高级的解决方案是将字符存储在容器中.std::set将是一个选项:

bool matches(char c)
{
    // note: might want to use static storage for `chars`
    std::set<char> const chars =
    {
        'n',
        'N',
        'a',
        'b',
        'c',
    };
    return chars.find(c) != end(chars);
}
Run Code Online (Sandbox Code Playgroud)

std::string 允许更简洁的形式,就可读性和可维护性而言可能是好的或坏的:

bool matches(char c)
{
    // note: might want to use static storage for `chars`
    std::string const chars = "nNabc";
    return chars.find(c) != std::string::npos;
}
Run Code Online (Sandbox Code Playgroud)

请注意,不同的容器具有不同的算法复杂性特征,如果类似的功能match实际上应该成为性能瓶颈,这可能是相关的.