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

QHash< Key, T > Class Template Reference

Inheritance diagram for QHash< Key, T >:

QMultiHash< Key, T >

List of all members.


Detailed Description

template<class Key, class T>
class QHash< Key, T >

The QHash class is a template class that provides a hash-table-based dictionary.

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

QHash provides very similar functionality to QMap. The differences are:

QHash provides faster lookups than QMap. When iterating over a QMap, the items are always sorted by key. With QHash, the items are arbitrarily ordered. The key type of a QMap must provide operator<(). The key type of a QHash must provide operator==() and a global {qHash()}{qHash}(Key) function.

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

        QHash<QString, int> hash;

To insert a (key, value) pair into the hash, you can use operator[]():

        hash["one"] = 1;
        hash["three"] = 3;
        hash["seven"] = 7;

This inserts the following three (key, value) pairs into the QHash: ("one", 1), ("three", 3), and ("seven", 7). Another way to insert items into the hash is to use insert():

        hash.insert("twelve", 12);

To look up a value, use operator[]() or value():

        int num1 = hash["thirteen"];
        int num2 = hash.value("thirteen");

If there is no item with the specified key in the hash, these functions return a {default-constructed value}.

If you want to check whether the hash contains a particular key, use contains():

        int timeout = 30;
        if (hash.contains("TIMEOUT"))
            timeout = hash.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 = hash.value("TIMEOUT", 30);

In general, we recommend that you use contains() and value() rather than operator[]() for looking up a key in a hash. The reason is that operator[]() silently inserts an item into the hash if no item exists with the same key (unless the hash is const). For example, the following code snippet will create 1000 items in memory:

        // WRONG
        QHash<int, QWidget *> hash;
        ...
        for (int i = 0; i < 1000; ++i) {
            if (hash[i] == okButton)
                cout << "Found button at index " << i << endl;
        }

To avoid this problem, replace hash[i] with hash.value(i) in the code above.

If you want to navigate through all the (key, value) pairs stored in a QHash, you can use an iterator. QHash provides both {Java-style iterators} (QHashIterator and QMutableHashIterator) and {STL-style iterators} (QHash::const_iterator and QHash::iterator). Here's how to iterate over a QHash<QString, int> using a Java-style iterator:

        QHashIterator<QString, int> i(hash);
        while (i.hasNext()) {
            i.next();
            cout << i.key() << ": " << i.value() << endl;
        }

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

        QHash<QString, int>::const_iterator i = hash.constBegin();
        while (i != hash.constEnd()) {
            cout << i.key() << ": " << i.value() << endl;
            ++i;
        }

QHash is unordered, so an iterator's sequence cannot be assumed to be predictable. If ordering by key is required, use a QMap.

Normally, a QHash allows only one value per key. If you call insert() with a key that already exists in the QHash, the previous value is erased. For example:

        hash.insert("plenty", 100);
        hash.insert("plenty", 2000);
        // hash.value("plenty") == 2000

However, you can store multiple values per key by using insertMulti() instead of insert() (or using the convenience subclass QMultiHash). 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 = hash.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. A more efficient approach is to call find() to get the iterator for the first item with a key and iterate from there:

        QHash<QString, int>::iterator i = hash.find("plenty");
        while (i != hash.end() && i.key() == "plenty") {
            cout << i.value() << endl;
            ++i;
        }

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

        QHash<QString, int> hash;
        ...
        foreach (int value, hash)
            cout << value << endl;

Items can be removed from the hash in several ways. One way is to call remove(); this will remove any item with the given key. Another way is to use QMutableHashIterator::remove(). In addition, you can clear the entire hash using clear().

QHash's key and value data types must be {assignable data types}. You cannot, for example, store a QWidget as a value; instead, store a QWidget *. In addition, QHash's key type must provide operator==(), and there must also be a global qHash() function that returns a hash value for an argument of the key's type.

Here's a list of the C++ and Qt types that can serve as keys in a QHash: any integer type (char, unsigned long, etc.), any pointer type, QChar, QString, and QByteArray. For all of these, the <QHash> header defines a qHash() function that computes an adequate hash value. If you want to use other types as the key, make sure that you provide operator==() and a qHash() implementation.

Example:

        #ifndef EMPLOYEE_H
        #define EMPLOYEE_H

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

        private:
            QString myName;
            QDate myDateOfBirth;
        };

        inline bool operator==(const Employee &e1, const Employee &e2)
        {
            return e1.name() == e2.name()
                   && e1.dateOfBirth() == e2.dateOfBirth();
        }

        inline uint qHash(const Employee &key)
        {
            return qHash(key.name()) ^ key.dateOfBirth().day();
        }

        #endif // EMPLOYEE_H

The qHash() function computes a numeric value based on a key. It can use any algorithm imaginable, as long as it always returns the same value if given the same argument. In other words, if {e1 == e2}, then {qHash(e1) == qHash(e2)} must hold as well. However, to obtain good performance, the qHash() function should attempt to return different hash values for different keys to the largest extent possible.

In the example above, we've relied on Qt's global qHash(const QString &) to give us a hash value for the employee's name, and XOR'ed this with the day they were born to help produce unique hashes for people with the same name.

Internally, QHash uses a hash table to perform lookups. Unlike Qt 3's QDict class, which needed to be initialized with a prime number, QHash's hash table automatically grows and shrinks to provide fast lookups without wasting too much memory. You can still control the size of the hash table by calling reserve() if you already know approximately how many items the QHash will contain, but this isn't necessary to obtain good performance. You can also call capacity() to retrieve the hash table's size.

See also:
QHashIterator, QMutableHashIterator, QMap, QSet

Definition at line 195 of file qhash.h.


Public Types

typedef const_iterator ConstIterator
typedef iterator Iterator

Public Member Functions

const_iterator begin () const
iterator begin ()
int capacity () const
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
QList< Key > keys (const T &value) const
QList< Key > keys () const
bool operator!= (const QHash< Key, T > &other) const
QHash< Key, T > & operator= (const QHash< Key, T > &other)
bool operator== (const QHash< Key, T > &other) const
const T operator[] (const Key &key) const
T & operator[] (const Key &key)
 QHash (const QHash< Key, T > &other)
 QHash ()
int remove (const Key &key)
void reserve (int size)
void setSharable (bool sharable)
int size () const
void squeeze ()
take (const Key &key)
QHash< Key, T > & unite (const QHash< Key, T > &other)
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
 ~QHash ()

Private Types

typedef QHashDummyNode< Key, T > DummyNode
typedef QHashNode< Key, T > Node

Private Member Functions

Node * createNode (uint h, const Key &key, const T &value, Node **nextNode)
void deleteNode (Node *node)
void detach_helper ()
Node ** findNode (const Key &key, uint *hp=0) const
void freeData (QHashData *d)

Static Private Member Functions

static Node * concrete (QHashData::Node *node)
static void duplicateNode (QHashData::Node *originalNode, void *newNode)

Private Attributes

union {
   QHashData *   d
   QHashNode< Key, T > *   e
}; 

Friends

class const_iterator
class iterator

Related Functions

(Note that these are not member functions.)

QDataStreamoperator<< (QDataStream &out, const QHash< Key, T > &hash)
QDataStreamoperator>> (QDataStream &in, QHash< Key, T > &hash)
uint qHash (const T *key)
uint qHash (const QString &key)
uint qHash (const QByteArray &key)
uint qHash (QChar key)
uint qHash (qint64 key)
uint qHash (quint64 key)
uint qHash (long key)
uint qHash (ulong key)
uint qHash (int key)
uint qHash (uint key)
uint qHash (short key)
uint qHash (ushort key)
uint qHash (signed char key)
uint qHash (uchar key)
uint qHash (char key)

Classes

class  const_iterator
 The QHash::const_iterator class provides an STL-style const iterator for QHash and QMultiHash. More...
class  iterator
 The QHash::iterator class provides an STL-style non-const iterator for QHash and QMultiHash. More...

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

Generated by  Doxygen 1.6.0   Back to index