【问题标题】:Searching QStringList for specific items and then others that may contains an item在 QStringList 中搜索特定项目,然后搜索可能包含项目的其他项目
【发布时间】:2013-08-06 14:22:59
【问题描述】:

我想获得搜索的所有“索引”。显然“QStringList::indexOf”一次返回一个索引......所以我必须做一个while循环。但它也“仅”进行完全匹配。

如果我想返回所有拥有“husky”的项目的索引......然后可能是“dog”......然后是“dog 2”。 我是否坚持比“QString::contains”然后循环来完成这个?还是我缺少更多与“QStringList 类”相关的方式

QStringList dogPound;
dogPound    << "husky dog 1"
            << "husky dog 2"
            << "husky dog 2 spotted"
            << "lab dog 2 spotted";

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    您可以使用QStringList::filter 方法。它返回一个新的QStringList,其中包含从过滤器传递的所有项目。

    QStringList dogPound;
    dogPound    << "husky dog 1"
                << "husky dog 2"
                << "husky dog 2 spotted"
                << "lab dog 2 spotted";
    
    QStringList spotted = dogPound.filter("spotted");
    // spotted now contains "husky dog 2 spotted" and "lab dog 2 spotted"
    

    【讨论】:

    • 我认为为简单起见,要获取索引,在循环中使用“QStringList::contains”会更容易。
    • 我不明白你为什么对循环如此犹豫。据我了解,您需要编写一个循环来迭代索引,那么为什么不将两个循环组合在一起并使用“包含”或“过滤器”呢?
    • 循环是我知道的唯一方法,我不确定它们是否是我所缺少的类的更多继承......即:“过滤器”返回项目,但也许有一个标志可以设置返回索引。
    【解决方案2】:

    这似乎是在 QStringList 中查找特定 QString 位置的最直接的方法:

    #include <algorithm>
    
    #include <QDebug>
    #include <QString>
    #include <QStringList>
    
    
    int main(int argc, char *argv[])
    {
        QStringList words;
        words.append("bar");
        words.append("baz");
        words.append("fnord");
    
        QStringList search;
        search.append("fnord");
        search.append("bar");
        search.append("baz");
        search.append("bripiep");
    
        foreach(const QString &word, search)
        {
            int i = -1;
            QStringList::iterator it = std::find(words.begin(), words.end(), word);
            if (it != words.end())
                i = it - words.begin();
    
            qDebug() << "index of" << word << "in" << words << "is" << i;
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多