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

QMap Class

TheQMap class is a template class that provides a skip-list-based dictionary.More...

Header:#include <QMap>
Inherited By:

QMultiMap

Note: All functions in this class arereentrant.

Public Types

classconst_iterator
classiterator
typedefConstIterator
typedefIterator
typedefdifference_type
typedefkey_type
typedefmapped_type
typedefsize_type

Public Functions

QMap()
QMap(const QMap<Key, T> & other)
QMap(const std::map<Key, T> & other)
~QMap()
iteratorbegin()
const_iteratorbegin() 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
iteratorlowerBound(const Key & key)
const_iteratorlowerBound(const Key & key) const
intremove(const Key & key)
intsize() const
voidswap(QMap<Key, T> & other)
Ttake(const Key & key)
std::map<Key, T>toStdMap() const
QList<Key>uniqueKeys() const
QMap<Key, T> &unite(const QMap<Key, T> & other)
iteratorupperBound(const Key & key)
const_iteratorupperBound(const Key & key) const
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 QMap<Key, T> & other) const
QMap<Key, T> &operator=(const QMap<Key, T> & other)
QMap<Key, T> &operator=(QMap<Key, T> && other)
booloperator==(const QMap<Key, T> & other) const
T &operator[](const Key & key)
const Toperator[](const Key & key) const

Related Non-Members

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

Detailed Description

TheQMap class is a template class that provides a skip-list-based dictionary.

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

QMap andQHash provide very similar functionality. The differences are:

  • QHash provides faster lookups thanQMap. (SeeAlgorithmic Complexity for details.)
  • When iterating over aQHash, the items are arbitrarily ordered. WithQMap, the items are always sorted by key.
  • The key type of aQHash must provide operator==() and a globalqHash(Key) function. The key type of aQMap must provide operator<() specifying a total order.

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

map.insert("twelve",12);

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

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

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

In general, we recommend that you usecontains() andvalue() 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:

// WRONGQMap<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, replacemap[i] withmap.value(i) in the code above.

If you want to navigate through all the (key, value) pairs stored in aQMap, you can use an iterator.QMap provides bothJava-style iterators (QMapIterator andQMutableMapIterator) andSTL-style iterators (QMap::const_iterator andQMap::iterator). Here's how to iterate over aQMap<QString, int> using a Java-style iterator:

QMapIterator<QString,int> i(map);while (i.hasNext()) {    i.next();    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;++i;}

The items are traversed in ascending key order.

Normally, aQMap allows only one value per key. If you callinsert() with a key that already exists in theQMap, 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 usinginsertMulti() instead ofinsert() (or using the convenience subclassQMultiMap). 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= 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 callfind() 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;++i;}

If you only need to extract the values from a map (not the keys), you can also useforeach:

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

QMap's key and value data types must beassignable data types. This covers most data types you are likely to encounter, but the compiler won't let you, for example, store aQWidget as a value; instead, store aQWidget *. In addition,QMap's key type must provide operator<().QMap uses it to keep its items sorted, and assumes that two keysx andy are equal if neitherx < y nory < x is true.

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){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 alsoQMapIterator,QMutableMapIterator,QHash, andQSet.

Member Type Documentation

typedef QMap::ConstIterator

Qt-style synonym forQMap::const_iterator.

typedef QMap::Iterator

Qt-style synonym forQMap::iterator.

typedef QMap::difference_type

Typedef for ptrdiff_t. Provided for STL compatibility.

typedef QMap::key_type

Typedef for Key. Provided for STL compatibility.

typedef QMap::mapped_type

Typedef for T. Provided for STL compatibility.

typedef QMap::size_type

Typedef for int. Provided for STL compatibility.

Member Function Documentation

QMap::QMap()

Constructs an empty map.

See alsoclear().

QMap::QMap(constQMap<Key,T> & other)

Constructs a copy ofother.

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

See alsooperator=().

QMap::QMap(conststd::map<Key,T> & other)

Constructs a copy ofother.

This function is only available if Qt is configured with STL compatibility enabled.

See alsotoStdMap().

QMap::~QMap()

Destroys the map. References to the values in the map, and all iterators over this map, become invalid.

iterator QMap::begin()

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

See alsoconstBegin() andend().

const_iterator QMap::begin() const

This is an overloaded function.

void QMap::clear()

Removes all items from the map.

See alsoremove().

const_iterator QMap::constBegin() const

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

See alsobegin() andconstEnd().

const_iterator QMap::constEnd() const

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

See alsoconstBegin() andend().

const_iterator QMap::constFind(constKey & key) const

Returns an const iterator pointing to the item with keykey in the map.

If the map contains no item with keykey, the function returnsconstEnd().

This function was introduced in Qt 4.1.

See alsofind() andQMultiMap::constFind().

bool QMap::contains(constKey & key) const

Returns true if the map contains an item with keykey; otherwise returns false.

See alsocount() andQMultiMap::contains().

int QMap::count(constKey & key) const

Returns the number of items associated with keykey.

See alsocontains(),insertMulti(), andQMultiMap::count().

int QMap::count() const

This is an overloaded function.

Same assize().

bool QMap::empty() const

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

iterator QMap::end()

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

See alsobegin() andconstEnd().

const_iterator QMap::end() const

This is an overloaded function.

iterator QMap::erase(iterator pos)

Removes the (key, value) pair pointed to by the iteratorpos from the map, and returns an iterator to the next item in the map.

See alsoremove().

iterator QMap::find(constKey & key)

Returns an iterator pointing to the item with keykey in the map.

If the map contains no item with keykey, the function returnsend().

If the map contains multiple items with keykey, 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:

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

See alsoconstFind(),value(),values(),lowerBound(),upperBound(), andQMultiMap::find().

const_iterator QMap::find(constKey & key) const

This is an overloaded function.

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

Inserts a new item with the keykey and a value ofvalue.

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

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

See alsoinsertMulti().

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

Inserts a new item with the keykey and a value ofvalue.

If there is already an item with the same key in the map, 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 QMap::isEmpty() const

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

See alsosize().

constKey QMap::key(constT & value) const

Returns the first key with valuevalue.

If the map contains no item with valuevalue, the function returns a default-constructed key.

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

See alsovalue() andkeys().

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

This is an overloaded function.

Returns the first key with valuevalue, ordefaultKey if the map contains no item with valuevalue.

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

This function was introduced in Qt 4.3.

QList<Key> QMap::keys() const

Returns a list containing all the keys in the map in ascending order. Keys that occur multiple times in the map (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> QMap::keys(constT & value) const

This is an overloaded function.

Returns a list containing all the keys associated with valuevalue in ascending order.

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

iterator QMap::lowerBound(constKey & key)

Returns an iterator pointing to the first item with keykey in the map. If the map contains no item with keykey, the function returns an iterator to the nearest item with a greater key.

Example:

QMap<int,QString> map;map.insert(1,"one");map.insert(5,"five");map.insert(10,"ten");map.lowerBound(0);// returns iterator to (1, "one")map.lowerBound(1);// returns iterator to (1, "one")map.lowerBound(2);// returns iterator to (5, "five")map.lowerBound(10);// returns iterator to (10, "ten")map.lowerBound(999);// returns end()

If the map contains multiple items with keykey, 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:

QMap<QString,int> map;...QMap<QString,int>::const_iterator i= map.lowerBound("HDR");QMap<QString,int>::const_iterator upperBound= map.upperBound("HDR");while (i!= upperBound) {    cout<< i.value()<< endl;++i;}

See alsoqLowerBound(),upperBound(), andfind().

const_iterator QMap::lowerBound(constKey & key) const

This is an overloaded function.

int QMap::remove(constKey & key)

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

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

int QMap::size() const

Returns the number of (key, value) pairs in the map.

See alsoisEmpty() andcount().

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

Swaps mapother with this map. This operation is very fast and never fails.

This function was introduced in Qt 4.8.

T QMap::take(constKey & key)

Removes the item with the keykey from the map and returns the value associated with it.

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

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

See alsoremove().

std::map<Key,T> QMap::toStdMap() const

Returns an STL map equivalent to thisQMap.

This function is only available if Qt is configured with STL compatibility enabled.

QList<Key> QMap::uniqueKeys() const

Returns a list containing all the keys in the map in ascending order. 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().

QMap<Key,T> & QMap::unite(constQMap<Key,T> & other)

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

See alsoinsertMulti().

iterator QMap::upperBound(constKey & key)

Returns an iterator pointing to the item that immediately follows the last item with keykey in the map. If the map contains no item with keykey, the function returns an iterator to the nearest item with a greater key.

Example:

QMap<int,QString> map;map.insert(1,"one");map.insert(5,"five");map.insert(10,"ten");map.upperBound(0);// returns iterator to (1, "one")map.upperBound(1);// returns iterator to (5, "five")map.upperBound(2);// returns iterator to (5, "five")map.upperBound(10);// returns end()map.upperBound(999);// returns end()

See alsoqUpperBound(),lowerBound(), andfind().

const_iterator QMap::upperBound(constKey & key) const

This is an overloaded function.

constT QMap::value(constKey & key) const

Returns the value associated with the keykey.

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

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

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

This is an overloaded function.

If the map contains no item with keykey, the function returnsdefaultValue.

QList<T> QMap::values() const

Returns a list containing all the values in the map, in ascending order of their keys. If a key is associated with multiple values, all of its values will be in the list, and not just the most recently inserted one.

See alsokeys() andvalue().

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

This is an overloaded function.

Returns a list containing all the values associated with keykey, from the most recently inserted to the least recently inserted one.

See alsocount() andinsertMulti().

bool QMap::operator!=(constQMap<Key,T> & other) const

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

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

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

See alsooperator==().

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

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

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

bool QMap::operator==(constQMap<Key,T> & other) const

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

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

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

See alsooperator!=().

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

Returns the value associated with the keykey as a modifiable reference.

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

See alsoinsert() andvalue().

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

This is an overloaded function.

Same asvalue().

Related Non-Members

QDataStream &operator<<(QDataStream & out, constQMap<Key,T> & map)

Writes the mapmap to streamout.

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

See alsoFormat of the QDataStream operators.

QDataStream &operator>>(QDataStream & in,QMap<Key,T> & map)

Reads a map from streamin intomap.

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

See alsoFormat of the QDataStream operators.

© 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