Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QHash Class

TheQHash class is a template class that provides a hash-table-based dictionary.More...

Header:#include <QHash>
Inherited By:

QMultiHash

Note: All functions in this class arereentrant.

Public Types

classconst_iterator
classiterator
typedefConstIterator
typedefIterator
typedefdifference_type
typedefkey_type
typedefmapped_type
typedefsize_type

Public Functions

QHash()
QHash(const QHash<Key, T> & other)
~QHash()
iteratorbegin()
const_iteratorbegin() const
intcapacity() const
voidclear()
const_iteratorconstBegin() const
const_iteratorconstEnd() const
const_iteratorconstFind(const Key & key) const
boolcontains(const Key & key) const
intcount(const Key & key) const
intcount() const
boolempty() const
iteratorend()
const_iteratorend() const
iteratorerase(iterator pos)
iteratorfind(const Key & key)
const_iteratorfind(const Key & key) const
iteratorinsert(const Key & key, const T & value)
iteratorinsertMulti(const Key & key, const T & value)
boolisEmpty() const
const Keykey(const T & value) const
const Keykey(const T & value, const Key & defaultKey) const
QList<Key>keys() const
QList<Key>keys(const T & value) const
intremove(const Key & key)
voidreserve(int size)
intsize() const
voidsqueeze()
voidswap(QHash<Key, T> & other)
Ttake(const Key & key)
QList<Key>uniqueKeys() const
QHash<Key, T> &unite(const QHash<Key, T> & other)
const Tvalue(const Key & key) const
const Tvalue(const Key & key, const T & defaultValue) const
QList<T>values() const
QList<T>values(const Key & key) const
booloperator!=(const QHash<Key, T> & other) const
QHash<Key, T> &operator=(const QHash<Key, T> & other)
QHash<Key, T> &operator=(QHash<Key, T> && other)
booloperator==(const QHash<Key, T> & other) const
T &operator[](const Key & key)
const Toperator[](const Key & key) const

Related Non-Members

uintqHash(const QXmlNodeModelIndex & index)
uintqHash(char key)
uintqHash(uchar key)
uintqHash(signed char key)
uintqHash(ushort key)
uintqHash(short key)
uintqHash(uint key)
uintqHash(int key)
uintqHash(ulong key)
uintqHash(long key)
uintqHash(quint64 key)
uintqHash(qint64 key)
uintqHash(QChar key)
uintqHash(const QByteArray & key)
uintqHash(const QString & key)
uintqHash(const QBitArray & key)
uintqHash(const T * key)
uintqHash(const QPair<T1, T2> & key)
QDataStream &operator<<(QDataStream & out, const QHash<Key, T> & hash)
QDataStream &operator>>(QDataStream & in, QHash<Key, T> & hash)

Detailed Description

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

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

QHash provides very similar functionality toQMap. The differences are:

  • QHash provides faster lookups thanQMap. (SeeAlgorithmic Complexity for details.)
  • When iterating over aQMap, the items are always sorted by key. WithQHash, the items are arbitrarily ordered.
  • The key type of aQMap must provide operator<(). The key type of aQHash must provide operator==() and a global hash function calledqHash() (see the related non-member functions).

Here's an exampleQHash withQString keys andint 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 theQHash: ("one", 1), ("three", 3), and ("seven", 7). Another way to insert items into the hash is to useinsert():

hash.insert("twelve",12);

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

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, usecontains():

int timeout=30;if (hash.contains("TIMEOUT"))    timeout= hash.value("TIMEOUT");

There is also avalue() 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 usecontains() andvalue() 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:

// WRONGQHash<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, replacehash[i] withhash.value(i) in the code above.

If you want to navigate through all the (key, value) pairs stored in aQHash, you can use an iterator.QHash provides bothJava-style iterators (QHashIterator andQMutableHashIterator) andSTL-style iterators (QHash::const_iterator andQHash::iterator). Here's how to iterate over aQHash<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 aQMap.

Normally, aQHash allows only one value per key. If you callinsert() with a key that already exists in theQHash, 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 usinginsertMulti() instead ofinsert() (or using the convenience subclassQMultiHash). If you want to retrieve all the values for a single key, you can use values(const Key &key), which returns aQList<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 callfind() 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 useforeach:

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 callremove(); this will remove any item with the given key. Another way is to useQMutableHashIterator::remove(). In addition, you can clear the entire hash usingclear().

QHash's key and value data types must beassignable data types. You cannot, for example, store aQWidget as a value; instead, store aQWidget *. In addition,QHash's key type must provide operator==(), and there must also be a globalqHash() 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 aQHash: any integer type (char, unsigned long, etc.), any pointer type,QChar,QString, andQByteArray. For all of these, the<QHash> header defines aqHash() function that computes an adequate hash value. If you want to use other types as the key, make sure that you provide operator==() and aqHash() implementation.

Example:

#ifndef EMPLOYEE_H#define EMPLOYEE_Hclass Employee{public:    Employee() {}    Employee(constQString&name,constQDate&dateOfBirth);...private:QString myName;QDate myDateOfBirth;};inline booloperator==(const Employee&e1,const Employee&e2){return e1.name()== e2.name()&& e1.dateOfBirth()== e2.dateOfBirth();}inlineuintqHash(const Employee&key){returnqHash(key.name())^ key.dateOfBirth().day();}#endif // EMPLOYEE_H

TheqHash() 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, ife1 == e2, thenqHash(e1) == qHash(e2) must hold as well. However, to obtain good performance, theqHash() 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 globalqHash(constQString &) 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'sQDict 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 callingreserve() if you already know approximately how many items theQHash will contain, but this isn't necessary to obtain good performance. You can also callcapacity() to retrieve the hash table's size.

See alsoQHashIterator,QMutableHashIterator,QMap, andQSet.

Member Type Documentation

typedef QHash::ConstIterator

Qt-style synonym forQHash::const_iterator.

typedef QHash::Iterator

Qt-style synonym forQHash::iterator.

typedef QHash::difference_type

Typedef for ptrdiff_t. Provided for STL compatibility.

typedef QHash::key_type

Typedef for Key. Provided for STL compatibility.

typedef QHash::mapped_type

Typedef for T. Provided for STL compatibility.

typedef QHash::size_type

Typedef for int. Provided for STL compatibility.

Member Function Documentation

QHash::QHash()

Constructs an empty hash.

See alsoclear().

QHash::QHash(constQHash<Key,T> & other)

Constructs a copy ofother.

This operation occurs inconstant time, becauseQHash isimplicitly shared. This makes returning aQHash from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and this takeslinear time.

See alsooperator=().

QHash::~QHash()

Destroys the hash. References to the values in the hash and all iterators of this hash become invalid.

iterator QHash::begin()

Returns an STL-style iterator pointing to the first item in the hash.

See alsoconstBegin() andend().

const_iterator QHash::begin() const

This is an overloaded function.

int QHash::capacity() const

Returns the number of buckets in theQHash's internal hash table.

The sole purpose of this function is to provide a means of fine tuningQHash's memory usage. In general, you will rarely ever need to call this function. If you want to know how many items are in the hash, callsize().

See alsoreserve() andsqueeze().

void QHash::clear()

Removes all items from the hash.

See alsoremove().

const_iterator QHash::constBegin() const

Returns a const STL-style iterator pointing to the first item in the hash.

See alsobegin() andconstEnd().

const_iterator QHash::constEnd() const

Returns a const STL-style iterator pointing to the imaginary item after the last item in the hash.

See alsoconstBegin() andend().

const_iterator QHash::constFind(constKey & key) const

Returns an iterator pointing to the item with thekey in the hash.

If the hash contains no item with thekey, the function returnsconstEnd().

This function was introduced in Qt 4.1.

See alsofind() andQMultiHash::constFind().

bool QHash::contains(constKey & key) const

Returns true if the hash contains an item with thekey; otherwise returns false.

See alsocount() andQMultiHash::contains().

int QHash::count(constKey & key) const

Returns the number of items associated with thekey.

See alsocontains() andinsertMulti().

int QHash::count() const

This is an overloaded function.

Same assize().

bool QHash::empty() const

This function is provided for STL compatibility. It is equivalent toisEmpty(), returning true if the hash is empty; otherwise returns false.

iterator QHash::end()

Returns an STL-style iterator pointing to the imaginary item after the last item in the hash.

See alsobegin() andconstEnd().

const_iterator QHash::end() const

This is an overloaded function.

iterator QHash::erase(iterator pos)

Removes the (key, value) pair associated with the iteratorpos from the hash, and returns an iterator to the next item in the hash.

Unlikeremove() andtake(), this function never causesQHash to rehash its internal data structure. This means that it can safely be called while iterating, and won't affect the order of items in the hash. For example:

QHash<QObject*,int> objectHash;...QHash<QObject*,int>::iterator i= objectHash.find(obj);while (i!= objectHash.end()&& i.key()== obj) {if (i.value()==0) {        i= objectHash.erase(i);    }else {++i;    }}

See alsoremove(),take(), andfind().

iterator QHash::find(constKey & key)

Returns an iterator pointing to the item with thekey in the hash.

If the hash contains no item with thekey, the function returnsend().

If the hash contains multiple items with thekey, this function returns an iterator that points to the most recently inserted value. The other values are accessible by incrementing the iterator. For example, here's some code that iterates over all the items with the same key:

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

See alsovalue(),values(), andQMultiHash::find().

const_iterator QHash::find(constKey & key) const

This is an overloaded function.

iterator QHash::insert(constKey & key, constT & value)

Inserts a new item with thekey and a value ofvalue.

If there is already an item with thekey, that item's value is replaced withvalue.

If there are multiple items with thekey, the most recently inserted item's value is replaced withvalue.

See alsoinsertMulti().

iterator QHash::insertMulti(constKey & key, constT & value)

Inserts a new item with thekey and a value ofvalue.

If there is already an item with the same key in the hash, this function will simply create a new one. (This behavior is different frominsert(), which overwrites the value of an existing item.)

See alsoinsert() andvalues().

bool QHash::isEmpty() const

Returns true if the hash contains no items; otherwise returns false.

See alsosize().

constKey QHash::key(constT & value) const

Returns the first key mapped tovalue.

If the hash contains no item with thevalue, the function returns a default-constructed key.

This function can be slow (linear time), becauseQHash's internal data structure is optimized for fast lookup by key, not by value.

See alsovalue() andkeys().

constKey QHash::key(constT & value, constKey & defaultKey) const

This is an overloaded function.

Returns the first key mapped tovalue, ordefaultKey if the hash contains no item mapped tovalue.

This function can be slow (linear time), becauseQHash's internal data structure is optimized for fast lookup by key, not by value.

This function was introduced in Qt 4.3.

QList<Key> QHash::keys() const

Returns a list containing all the keys in the hash, in an arbitrary order. Keys that occur multiple times in the hash (because items were inserted withinsertMulti(), orunite() was used) also occur multiple times in the list.

To obtain a list of unique keys, where each key from the map only occurs once, useuniqueKeys().

The order is guaranteed to be the same as that used byvalues().

See alsouniqueKeys(),values(), andkey().

QList<Key> QHash::keys(constT & value) const

This is an overloaded function.

Returns a list containing all the keys associated with valuevalue, in an arbitrary order.

This function can be slow (linear time), becauseQHash's internal data structure is optimized for fast lookup by key, not by value.

int QHash::remove(constKey & key)

Removes all the items that have thekey from the hash. Returns the number of items removed which is usually 1 but will be 0 if the key isn't in the hash, or greater than 1 ifinsertMulti() has been used with thekey.

See alsoclear(),take(), andQMultiHash::remove().

void QHash::reserve(int size)

Ensures that theQHash's internal hash table consists of at leastsize buckets.

This function is useful for code that needs to build a huge hash and wants to avoid repeated reallocation. For example:

QHash<QString,int> hash;hash.reserve(20000);for (int i=0; i<20000;++i)    hash.insert(keys[i], values[i]);

Ideally,size should be slightly more than the maximum number of items expected in the hash.size doesn't have to be prime, becauseQHash will use a prime number internally anyway. Ifsize is an underestimate, the worst that will happen is that theQHash will be a bit slower.

In general, you will rarely ever need to call this function.QHash's internal hash table automatically shrinks or grows to provide good performance without wasting too much memory.

See alsosqueeze() andcapacity().

int QHash::size() const

Returns the number of items in the hash.

See alsoisEmpty() andcount().

void QHash::squeeze()

Reduces the size of theQHash's internal hash table to save memory.

The sole purpose of this function is to provide a means of fine tuningQHash's memory usage. In general, you will rarely ever need to call this function.

See alsoreserve() andcapacity().

void QHash::swap(QHash<Key,T> & other)

Swaps hashother with this hash. This operation is very fast and never fails.

This function was introduced in Qt 4.8.

T QHash::take(constKey & key)

Removes the item with thekey from the hash and returns the value associated with it.

If the item does not exist in the hash, the function simply returns a default-constructed value. If there are multiple items forkey in the hash, only the most recently inserted one is removed.

If you don't use the return value,remove() is more efficient.

See alsoremove().

QList<Key> QHash::uniqueKeys() const

Returns a list containing all the keys in the map. Keys that occur multiple times in the map (because items were inserted withinsertMulti(), orunite() was used) occur only once in the returned list.

This function was introduced in Qt 4.2.

See alsokeys() andvalues().

QHash<Key,T> & QHash::unite(constQHash<Key,T> & other)

Inserts all the items in theother hash into this hash. If a key is common to both hashes, the resulting hash will contain the key multiple times.

See alsoinsertMulti().

constT QHash::value(constKey & key) const

Returns the value associated with thekey.

If the hash contains no item with thekey, the function returns a default-constructed value. If there are multiple items for thekey in the hash, the value of the most recently inserted one is returned.

See alsokey(),values(),contains(), andoperator[]().

constT QHash::value(constKey & key, constT & defaultValue) const

This is an overloaded function.

If the hash contains no item with the givenkey, the function returnsdefaultValue.

QList<T> QHash::values() const

Returns a list containing all the values in the hash, in an arbitrary order. If a key is associated multiple values, all of its values will be in the list, and not just the most recently inserted one.

The order is guaranteed to be the same as that used bykeys().

See alsokeys() andvalue().

QList<T> QHash::values(constKey & key) const

This is an overloaded function.

Returns a list of all the values associated with thekey, from the most recently inserted to the least recently inserted.

See alsocount() andinsertMulti().

bool QHash::operator!=(constQHash<Key,T> & other) const

Returns true ifother is not equal to this hash; otherwise returns false.

Two hashes are considered equal if they contain the same (key, value) pairs.

This function requires the value type to implementoperator==().

See alsooperator==().

QHash<Key,T> & QHash::operator=(constQHash<Key,T> & other)

Assignsother to this hash and returns a reference to this hash.

QHash<Key,T> & QHash::operator=(QHash<Key,T> && other)

bool QHash::operator==(constQHash<Key,T> & other) const

Returns true ifother is equal to this hash; otherwise returns false.

Two hashes are considered equal if they contain the same (key, value) pairs.

This function requires the value type to implementoperator==().

See alsooperator!=().

T & QHash::operator[](constKey & key)

Returns the value associated with thekey as a modifiable reference.

If the hash contains no item with thekey, the function inserts a default-constructed value into the hash with thekey, and returns a reference to it. If the hash contains multiple items with thekey, this function returns a reference to the most recently inserted value.

See alsoinsert() andvalue().

constT QHash::operator[](constKey & key) const

This is an overloaded function.

Same asvalue().

Related Non-Members

uintqHash(constQXmlNodeModelIndex & index)

Computes a hash key from theQXmlNodeModelIndexindex, and returns it. This function would be used byQHash if you wanted to build a hash table for instances ofQXmlNodeModelIndex.

The hash is computed onQXmlNodeModelIndex::data(),QXmlNodeModelIndex::additionalData(), andQXmlNodeModelIndex::model(). This means the hash key can be used for node indexes from different node models.

This function was introduced in Qt 4.4.

uintqHash(char key)

Returns the hash value for thekey.

uintqHash(uchar key)

Returns the hash value for thekey.

uintqHash(signedchar key)

Returns the hash value for thekey.

uintqHash(ushort key)

Returns the hash value for thekey.

uintqHash(short key)

Returns the hash value for thekey.

uintqHash(uint key)

Returns the hash value for thekey.

uintqHash(int key)

Returns the hash value for thekey.

uintqHash(ulong key)

Returns the hash value for thekey.

uintqHash(long key)

Returns the hash value for thekey.

uintqHash(quint64 key)

Returns the hash value for thekey.

uintqHash(qint64 key)

Returns the hash value for thekey.

uintqHash(QChar key)

Returns the hash value for thekey.

uintqHash(constQByteArray & key)

Returns the hash value for thekey.

uintqHash(constQString & key)

Returns the hash value for thekey.

uintqHash(constQBitArray & key)

Returns the hash value for thekey.

uintqHash(constT * key)

Returns the hash value for thekey.

uintqHash(constQPair<T1,T2> & key)

Returns the hash value for thekey.

TypesT1 andT2 must be supported byqHash().

This function was introduced in Qt 4.3.

QDataStream &operator<<(QDataStream & out, constQHash<Key,T> & hash)

Writes the hashhash to streamout.

This function requires the key and value types to implementoperator<<().

See alsoSerializing Qt Data Types.

QDataStream &operator>>(QDataStream & in,QHash<Key,T> & hash)

Reads a hash from streamin intohash.

This function requires the key and value types to implementoperator>>().

See alsoSerializing Qt Data Types.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp