2013-08-06 96 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; 
} 
相關問題