2013-08-06 73 views
1

我想获得搜索的所有“指数”。显然,“QStringList :: indexOf”一次返回一个索引......所以我必须做一个while循环。但它也“唯一”确实匹配。搜索QStringList的特定项目,然后其他可能包含项目

如果我想返回所有拥有“哈士奇”的物品的索引,那么可能是“狗”......然后是“狗2”。 我坚持比“QString :: contains”然后循环,来完成这个?还是有更多的“QStringList中类”相关的方式,我很想念

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

回答

2

可以使用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" 
+0

我想为简单起见,拿到指标,很容易只使用“QStringList :: contains”在一个循环中。 – jdl

+1

我不明白你为什么对循环犹豫不决。你需要编写一个循环来遍历索引,据我所知,为什么不将两个循环结合在一起并使用'contains'或'filter'? – erelender

+0

循环是我知道的唯一方式,我不确定他们是否更多地继承了我失踪的类......即:“过滤器”返回项目,但也许有一个标志设置为返回索引。 – jdl

1

这似乎是找到一个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; 
} 
相关问题