QMap Class▲
-
Header: QMap
-
qmake: QT += core
-
Group: QMap is part of tools, Implicitly Shared Classes
Detailed Description▲
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 average 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. Since Qt 5.8.1 it is also safe to use a pointer type as key, even if the underlying operator<() does not provide a total order.
Here's an example QMap with QString keys and int values:
QMap&
lt;QString, int
&
gt; map;
To insert a (key, value) pair into the map, you can use operator[]():
map["one"
] =
1
;
map["three"
] =
3
;
map["seven"
] =
7
;
This inserts the following three (key, value) pairs into the QMap: ("one", 1), ("three", 3), and ("seven", 7). Another way to insert items into the map is to use insert():
map.insert("twelve"
, 12
);
To look up a value, use operator[]() or value():
int
num1 =
map["thirteen"
];
int
num2 =
map.value("thirteen"
);
If there is no item with the specified key in the map, these functions return a default-constructed value.
If you want to check whether the map contains a certain key, use contains():
int
timeout =
30
;
if
(map.contains("TIMEOUT"
))
timeout =
map.value("TIMEOUT"
);
There is also a value() overload that uses its second argument as a default value if there is no item with the specified key:
int
timeout =
map.value("TIMEOUT"
, 30
);
In general, we recommend that you use contains() and value() rather than operator[]() for looking up a key in a map. The reason is that operator[]() silently inserts an item into the map if no item exists with the same key (unless the map is const). For example, the following code snippet will create 1000 items in memory:
// WRONG
QMap&
lt;int
, QWidget *&
gt; map;
...
for
(int
i =
0
; i &
lt; 1000
; ++
i) {
if
(map[i] ==
okButton)
cout &
lt;&
lt; "Found button at index "
&
lt;&
lt; i &
lt;&
lt; endl;
}
To avoid this problem, replace map[i] with map.value(i) in the code above.
If you want to navigate through all the (key, value) pairs stored in a QMap, you can use an iterator. QMap provides both Java-style iterators (QMapIterator and QMutableMapIterator) and STL-style iterators (QMap::const_iterator and QMap::iterator). Here's how to iterate over a QMap<QString, int> using a Java-style iterator:
QMapIterator&
lt;QString, int
&
gt; i(map);
while
(i.hasNext()) {
i.next();
cout &
lt;&
lt; i.key() &
lt;&
lt; ": "
&
lt;&
lt; i.value() &
lt;&
lt; endl;
}
Here's the same code, but using an STL-style iterator this time:
QMap&
lt;QString, int
&
gt;::
const_iterator i =
map.constBegin();
while
(i !=
map.constEnd()) {
cout &
lt;&
lt; i.key() &
lt;&
lt; ": "
&
lt;&
lt; i.value() &
lt;&
lt; endl;
++
i;
}
The items are traversed in ascending key order.
Normally, a QMap allows only one value per key. If you call insert() with a key that already exists in the QMap, the previous value will be erased. For example:
map.insert("plenty"
, 100
);
map.insert("plenty"
, 2000
);
// map.value("plenty") == 2000
However, you can store multiple values per key by using insertMulti() instead of insert() (or using the convenience subclass QMultiMap). If you want to retrieve all the values for a single key, you can use values(const Key &key), which returns a QList<T>:
QList&
lt;int
&
gt; values =
map.values("plenty"
);
for
(int
i =
0
; i &
lt; values.size(); ++
i)
cout &
lt;&
lt; values.at(i) &
lt;&
lt; endl;
The items that share the same key are available from most recently to least recently inserted. Another approach is to call find() to get the STL-style iterator for the first item with a key and iterate from there:
QMap&
lt;QString, int
&
gt;::
iterator i =
map.find("plenty"
);
while
(i !=
map.end() &
amp;&
amp; i.key() ==
"plenty"
) {
cout &
lt;&
lt; i.value() &
lt;&
lt; endl;
++
i;
}
If you only need to extract the values from a map (not the keys), you can also use foreach:
QMap&
lt;QString, int
&
gt; map;
...
foreach (int
value, map)
cout &
lt;&
lt; value &
lt;&
lt; endl;
Items can be removed from the map in several ways. One way is to call remove(); this will remove any item with the given key. Another way is to use QMutableMapIterator::remove(). In addition, you can clear the entire map using clear().
QMap's key and value data types must be assignable data types. This covers most data types you are likely to encounter, but the compiler won't let you, for example, store a QWidget as a value; instead, store a QWidget *. In addition, QMap's key type must provide operator<(). QMap uses it to keep its items sorted, and assumes that two keys x and y are equal if neither x < y nor y < x is true.
Example:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class
Employee
{
public
:
Employee() {}
Employee(const
QString &
amp;name, const
QDate &
amp;dateOfBirth);
...
private
:
QString myName;
QDate myDateOfBirth;
}
;
inline
bool
operator
&
lt;(const
Employee &
amp;e1, const
Employee &
amp;e2)
{
if
(e1.name() !=
e2.name())
return
e1.name() &
lt; e2.name();
return
e1.dateOfBirth() &
lt; e2.dateOfBirth();
}
#endif
// EMPLOYEE_H
In the example, we start by comparing the employees' names. If they're equal, we compare their dates of birth to break the tie.
See Also▲
See also QMapIterator, QMutableMapIterator, QHash, QSet
Member Type Documentation▲
QMap::ConstIterator▲
Qt-style synonym for QMap<Key, T>::const_iterator.
QMap::Iterator▲
Qt-style synonym for QMap<Key, T>::iterator.
[since 5.10] QMap::const_key_value_iterator▲
The QMap::const_key_value_iterator typedef provides an STL-style iterator for QMap and QMultiMap.
QMap::const_key_value_iterator is essentially the same as QMap::const_iterator with the difference that operator*() returns a key/value pair instead of a value.
This typedef was introduced in Qt 5.10.
See Also▲
See also QKeyValueIterator
QMap::difference_type▲
Typedef for ptrdiff_t. Provided for STL compatibility.
QMap::key_type▲
Typedef for Key. Provided for STL compatibility.
[since 5.10] QMap::key_value_iterator▲
The QMap::key_value_iterator typedef provides an STL-style iterator for QMap and QMultiMap.
QMap::key_value_iterator is essentially the same as QMap::iterator with the difference that operator*() returns a key/value pair instead of a value.
This typedef was introduced in Qt 5.10.
See Also▲
See also QKeyValueIterator
QMap::mapped_type▲
Typedef for T. Provided for STL compatibility.
QMap::size_type▲
Typedef for int. Provided for STL compatibility.
Member Function Documentation▲
QMap::QMap()▲
[since 5.2] QMap::QMap(QMap<Key, T> &&other)▲
Move-constructs a QMap instance, making it point at the same object that other was pointing to.
This function was introduced in Qt 5.2.
[default] QMap::QMap(const QMap<Key, T> &other)▲
Constructs a copy of other.
This operation occurs in constant time, because QMap is implicitly shared. This makes returning a QMap from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and this takes linear time.
See Also▲
See also operator=()