Qt学习之路—containers(3)

August 8th, 2013 by JasonLe's Tech Leave a reply »

下面介绍QMap<T>  QHash<T>  QStringList<T>

QMap<T>  QHash<T>两者有很多相似的地方,查询libaray。有如下解释。

http://qt-project.org/doc/qt-5.0/qtcore/qmap.html

The QMap class is a template class that provides a red-black-tree-based dictionary.

QMap<Key, T> is one of Qt’s generic container classes. It stores (key, value) pairs and provides fast lookup of the value associated with a key.

QMap and QHash provide very similar functionality. The differences are:

  • QHash provides faster lookups than QMap. (See Algorithmic Complexity for details.)
  • When iterating over a QHash, the items are arbitrarily ordered. With QMap, the items are always sorted by key.
  • The key type of a QHash must provide operator==() and a global qHash(Key) function. The key type of a QMap must provide operator<() specifying a total order.

最主要的是QHash 比 QMap 查询速度要快。

QHash<int,QString> hash;
hash.insert(1,”Lee”);hash.insert(2,”Song”);hash.insert(3,”Zhang”);
qDebug() << ” 2 ” << hash.value(2);

 

The QStringList class provides a list of strings.

QStringList inherits from QList<QString>. Like QList, QStringList is implicitly shared. It provides fast index-based access as well as fast insertions and removals. Passing string lists as value parameters is both fast and safe.

QStringList List;
QString string = “a,b,c,d,e,f,g”;
List = string.split(“,”);
List.replaceInStrings(“f”,”Fox”);
QString after = List.join(“,”);
qDebug() << after;

详细查询http://qt-project.org/doc/qt-5.0/qtcore/qstringlist.html

上述代码的关键是split与join的作用是相反的,一个是分离,另一个是组合。

另外QStringList重要的功能是替换一组相同的关键词,类似与split(),看一组代码,很直观。

QStringList files;
files << “$QTDIR/src/moc/moc.y”
<< “$QTDIR/src/moc/moc.l”
<< “$QTDIR/include/qconfig.h”;

files.replaceInStrings(“$QTDIR”, “/usr/lib/qt”);
// files: [ “/usr/lib/qt/src/moc/moc.y”, …]