Home > Software design >  How to compare multiple QStrings at once?
How to compare multiple QStrings at once?

Time:12-28

In qt there's another way to compare multiple strings than writing many 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)
{
}

CodePudding user response:

One simple approach is to create a container with all of allowable strings and use its find function to see if it's in the container. Depending on the container you select it may not have it's own find function. In that case you can still rely on std::find to simply find the string.

The following example uses a std::set to store all the valid strings you want to find and uses its find member function to handle the searching without doing any additional checks for strings you may want to ignore.

#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";
        }
    }
}

The following example uses a std::vector to store all allowable strings and uses std::find to find the string.

#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";
        }
    }
}

Both examples generate the following output

Did not find red
Found yellow
Found blue
Found green
Found gray
  •  Tags:  
  • c qt
  • Related