c++ - 如何检查一组值中的一个是否相等?

标签 c++

<分区>

我希望能够使用如下所示的 if 语句:

if (input == Positive)
{
    // Do something
}

实际做的事情看起来像这样:

if (input == "yes" ||input ==  "Yes" ||input ==  "YES" ||input ==  "Ya" ||input ==  "ya" (etc all the rest of positive words/ways to say yes))
{
    // Do something
}

我在想我会把我的代码保存在一个静态库中(虽然我对它们了解不多,所以如果有更好的方法请随时纠正我)这样我就可以从我使用的任何 future 程序中访问它而且我不必一遍又一遍地复制粘贴相同的代码。有什么办法吗?或者类似的东西?

非常感谢:)

最佳答案

有很多方法可以测试是否包含在内。最自然的是使用集合:

#include <set>
#include <string>
    static const std::set<std::string> positive_answers =
        { "yes", "Yes", "YES", "Ya", "ya" };

    if (positive_answers.count(input) > 0) {

        // Do something
    }

这是上面的完整程序版本:

#include <iostream>
#include <set>
#include <string>

int main()
{
    std::string input = "YES";

    static const std::set<std::string> positive_answers =
        { "yes", "Yes", "YES", "Ya", "ya" };

    if (positive_answers.count(input) > 0) {
        std::cout << "Agreed\n";
    } else {
        std::cout << "Disagreed\n";
    }
}

您可以考虑使用可变参数模板:

template<typename T, typename... U>
bool is_in(T candidate, U... positives)
{
    const std::set<std::string> positive_answers{{positives...}};
    return positive_answers.count(candidate) > 0;
}

这样使用:

    if (is_in(input, "yes", "Yes", "YES", "Ya", "ya"))

这可行,但如果 input 是 C 风格的字符串 (char*),请小心,因为这将使用指针的比较函数。

关于c++ - 如何检查一组值中的一个是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57992749/

相关文章:

c++ - 将枚举转换为 int

c++ - C++ 中的 Delphi Format() 模拟

android - 如何为 Android 使用 libx265 编译 FFmpeg?

c++ - 如何使 DEBUG 宏可移植

c++ - 与二维数组有关的循环崩溃程序

c++ - 根据 size() 排序 vector

c++ - 如何初始化一个有n个默认值的队列?

c++ - MPICH 通信失败

c++ - 为什么 Numerical Recipes 头文件中没有 include 守卫?

c++ - 错误LNK2019,如何解决? *更新*