Logo Search packages:      
Sourcecode: qt4-x11 version File versions  Download package

QMap< Key, T > Class Template Reference

Inheritance diagram for QMap< Key, T >:

QMultiMap< Key, T >

List of all members.

Detailed Description

template<class Key, class T>
class QMap< Key, T >

The QMap class is a template class that provides a skip-list-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.

Here's an example QMap with QString keys and int values:

        QMap<QString, int> 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<int, QWidget *> map;
        for (int i = 0; i < 1000; ++i) {
            if (map[i] == okButton)
                cout << "Found button at index " << i << 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<QString, int> i(map);
        while (i.hasNext()) {
            cout << i.key() << ": " << i.value() << endl;

Here's the same code, but using an STL-style iterator this time:

        QMap<QString, int>::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            cout << i.key() << ": " << i.value() << endl;

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<int> values = map.values("plenty");
        for (int i = 0; i < values.size(); ++i)
            cout << values.at(i) << 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<QString, int>::iterator i = map.find("plenty");
        while (i != map.end() && i.key() == "plenty") {
            cout << i.value() << endl;

If you only need to extract the values from a map (not the keys), you can also use {foreach}:

        QMap<QString, int> map;
        foreach (int value, map)
            cout << value << 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.


        #ifndef EMPLOYEE_H
        #define EMPLOYEE_H

        class Employee
            Employee() {}
            Employee(const QString &name, const QDate &dateOfBirth);

            QString myName;
            QDate myDateOfBirth;

        inline bool operator<(const Employee &e1, const Employee &e2)
            if (e1.name() != e2.name())
                return e1.name() < e2.name();
            return e1.dateOfBirth() < 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:
QMapIterator, QMutableMapIterator, QHash, QSet

Definition at line 122 of file qmap.h.

Public Types

typedef const_iterator ConstIterator
typedef ptrdiff_t difference_type
typedef iterator Iterator
typedef Key key_type
typedef T mapped_type
typedef int size_type

Public Member Functions

const_iterator begin () const
iterator begin ()
void clear ()
const_iterator constBegin () const
const_iterator constEnd () const
const_iterator constFind (const Key &key) const
bool contains (const Key &key) const
int count () const
int count (const Key &key) const
void detach ()
bool empty () const
const_iterator end () const
iterator end ()
iterator erase (iterator it)
const_iterator find (const Key &key) const
iterator find (const Key &key)
iterator insert (const Key &key, const T &value)
iterator insertMulti (const Key &key, const T &value)
bool isDetached () const
bool isEmpty () const
const Key key (const T &value, const Key &defaultKey) const
const Key key (const T &value) const
QList< Key > keys (const T &value) const
QList< Key > keys () const
const_iterator lowerBound (const Key &key) const
iterator lowerBound (const Key &key)
bool operator!= (const QMap< Key, T > &other) const
QMap< Key, T > & operator= (const QMap< Key, T > &other)
bool operator== (const QMap< Key, T > &other) const
const T operator[] (const Key &key) const
T & operator[] (const Key &key)
 QMap (const typename std::map< Key, T > &other)
 QMap (const QMap< Key, T > &other)
 QMap ()
int remove (const Key &key)
void setInsertInOrder (bool ordered)
void setSharable (bool sharable)
int size () const
take (const Key &key)
std::map< Key, T > toStdMap () const
QList< Key > uniqueKeys () const
QMap< Key, T > & unite (const QMap< Key, T > &other)
const_iterator upperBound (const Key &key) const
iterator upperBound (const Key &key)
const T value (const Key &key, const T &defaultValue) const
const T value (const Key &key) const
QList< T > values (const Key &key) const
QList< T > values () const
 ~QMap ()

Private Member Functions

void detach_helper ()
QMapData::Node * findNode (const Key &key) const
void freeData (QMapData *d)
QMapData::Node * mutableFindNode (QMapData::Node *update[], const Key &key) const
QMapData::Node * node_create (QMapData *d, QMapData::Node *update[], const Key &key, const T &value)

Static Private Member Functions

static Node * concrete (QMapData::Node *node)
static int payload ()

Private Attributes

union {
   QMapData *   d
   QMapData::Node *   e


class const_iterator
class iterator

Related Functions

(Note that these are not member functions.)

QDataStreamoperator<< (QDataStream &out, const QMap< Key, T > &map)
QDataStreamoperator>> (QDataStream &in, QMap< Key, T > &map)


class  const_iterator
 The QMap::const_iterator class provides an STL-style const iterator for QMap and QMultiMap. More...
class  iterator
 The QMap::iterator class provides an STL-style non-const iterator for QMap and QMultiMap. More...
struct  Node
struct  PayloadNode

The documentation for this class was generated from the following files:

Generated by  Doxygen 1.6.0   Back to index