c++ 如何一次比较多个QString?

cld4siwp  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(140)

qt中,除了写入许多str1 == str2 || ...之外,还有另一种比较多个字符串的方法

QString a = "red";
QString b = "yellow";
QString c = "blue";
QString d = "green";
QString e = "gray";

if (a == b || a == c || a == d || a == e)
{
}
balp4ylt

balp4ylt1#

一个简单的方法是创建一个包含所有允许的字符串的容器,然后使用它的find函数来查看它是否在容器中。根据你选择的容器,它可能没有自己的find函数。在这种情况下,你仍然可以依赖std::find来简单地查找字符串。
下面的示例使用std::set来存储要查找的所有有效字符串,并使用其find成员函数来处理搜索,而不对要忽略的字符串执行任何其他检查。

#include <set>
#include <vector>
#include <iostream>

int main()
{
    std::set<QString> validLabels{ "yellow", "blue", "green", "gray" };
    std::vector<QString> needles{ "red", "yellow", "blue", "green", "gray" };
    for (const auto& needle : needles)
    {
        if (validLabels.find(needle) != validLabels.end())
        {
            std::cout << "Found " << needle << "\n";
        }
        else
        {
            std::cout << "Did not find " << needle << "\n";
        }
    }
}

下面的示例使用std::vector存储所有允许的字符串,并使用std::find查找该字符串。

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<QString> validLabels{ "yellow", "blue", "green", "gray" };
    std::vector<QString> needles{ "red", "yellow", "blue", "green", "gray" };
    for (const auto& needle : needles)
    {
        if (std::find(validLabels.begin(), validLabels.end(), needle) != validLabels.end())
        {
            std::cout << "Found " << needle << "\n";
        }
        else
        {
            std::cout << "Did not find " << needle << "\n";
        }
    }
}

这两个示例都生成以下输出

Did not find red
Found yellow
Found blue
Found green
Found gray

相关问题