| Qt
的全域函式中,包括了一些適用Qt容器的泛型演算函式,像是qFind()可以指定容器直接進行搜尋,也可以指定起始與結束迭代器位址,進行指定值搜尋,
若搜尋到則傳回該值的迭代器位址,若沒有找到,則傳回容器end()方法的迭代器位址。qSort()可以對容器進行排序。qBinaryFind()可
以以二元搜尋的方式搜尋已遞增排序容器中指定的值。例如: QStringList list;
list << "caterpillar" << "momor" << "bush" << "justin"; // 以下顯示momor、bush、justin QStringList::iterator i = qFind(list.begin(), list.end(), "momor"); while(i != list.end()) { cout << (*i).toAscii().data() << endl; ++i; } cout << endl; // 排序 qSort(list.begin(), list.end()); // 以下顯示momor QStringList::iterator j = qBinaryFind(list.begin(), list.end(), "momor"); while(j != list.end()) { cout << (*j).toAscii().data() << endl; ++j; } qSort()預設使用遞增排序,如果要以遞減排序的方式,則可以傳入qGreater<T>(),類似的,qBinaryFind()也可以使用qGreater<T>()指定在遞減排序的容器中進行二元搜尋,例如: QStringList list; list << "caterpillar" << "momor" << "bush" << "justin"; // 遞增排序 qSort(list.begin(), list.end(), qGreater<QString>()); // 以下顯示momor、justin、caterpillar、bush QStringList::const_iterator iterator = list.begin(); while(iterator != list.end()) { cout << (*iterator).toAscii().data() << endl; ++iterator; } QStringList::iterator j = qBinaryFind(list.begin(), list.end(), "caterpillar", qGreater<QString>()); // 以下顯示caterpillar、bush while(j != list.end()) { cout << (*j).toAscii().data() << endl; ++j; } 您也可以自定義排序規則,例如依字串長度進行排序: bool lengthLessThan(const QString &str1, const QString &str2) {
return str1.length() < str2.length(); } QStringList list;
list << "caterpillar" << "momor" << "bush" << "justin"; qSort(list.begin(), list.end(), lengthLessThan); // 以下顯示bush、momor、justin、caterpillar QStringList::const_iterator iterator = list.begin(); while(iterator != list.end()) { cout << (*iterator).toAscii().data() << endl; ++iterator; } 與qSort()類似的qStableSort(),則是在比較兩個項目相同時,會保留兩個項目原有的先後順序。 在這邊僅列出幾個泛型演算的例子,更多泛型演算的函式,可以查詢Qt的 <QtAlgorithms> - Generic Algorithms 中之介紹。 |