Qt5 Tutorial QMap - 2020
In this tutorial, we will learn about QMap.
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.
#include <QCoreApplication> #include <QMap> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QMap<int, QString> Map; Map.insert(1,"A"); Map.insert(2,"B"); Map[3] = "C"; foreach(int i, Map.keys()) qDebug() << Map[i]; QMapIterator<int, QString> iter(Map); while(iter.hasNext()) { iter.next(); qDebug() << iter.key() << " : " << iter.value(); } return a.exec(); }
Output should look like this:
"A" "B" "C" 1 : "A" 2 : "B" 3 : "C"
To insert a (key, value) pair into the map, we can use insert():
Map.insert(1,"A"); Map.insert(2,"B");
or use operator[]():
Map[3] = "C";
We can store multiple values per key by using insertMulti() instead of insert().
If we want to navigate through all the (key, value) pairs stored in a QMap, we can use an iterator. QMap provides both Java-style iterators (QMapIterator and QMutableMapIterator) and STL-style iterators (QMap::const_iterator and QMap::iterator). The example above shows how to iterate over a QMap<QString, int> using a Java-style iterator:
QMapIterator<int, QString> iter(Map); while(iter.hasNext()) { iter.next(); qDebug() << iter.key() << " : " << iter.value(); }
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization