QMap 类

QMap class is a template class that provides a red-black-tree-based dictionary. 更多...

头: #include <QMap>
qmake: QT += core
继承者:

QMultiMap

注意: 此类的所有函数 可重入 .

公共类型

class const_iterator
class iterator
class key_iterator
typedef ConstIterator
typedef Iterator
typedef difference_type
typedef key_type
typedef mapped_type
typedef size_type

公共函数

QMap ()
QMap (std::initializer_list<std::pair<Key, T> > list )
QMap (const QMap<Key, T> & other )
QMap (QMap<Key, T> && other )
QMap (const std::map<Key, T> & other )
~QMap ()
iterator begin ()
const_iterator begin () const
const_iterator cbegin () const
const_iterator cend () 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 Key & key ) const
int count () const
bool empty () const
iterator end ()
const_iterator end () const
QPair<iterator, iterator> equal_range (const Key & key )
QPair<const_iterator, const_iterator> equal_range (const Key & key ) const
iterator erase (iterator pos )
iterator find (const Key & key )
const_iterator find (const Key & key ) const
T & first ()
const T & first () const
const Key & firstKey () const
iterator insert (const Key & key , const T & value )
iterator insert (const_iterator pos , const Key & key , const T & value )
iterator insertMulti (const Key & key , const T & value )
iterator insertMulti (const_iterator pos , const Key & key , const T & value )
bool isEmpty () const
const Key key (const T & value , const Key & defaultKey = Key()) const
key_iterator keyBegin () const
key_iterator keyEnd () const
QList<Key> keys () const
QList<Key> keys (const T & value ) const
T & last ()
const T & last () const
const Key & lastKey () const
iterator lowerBound (const Key & key )
const_iterator lowerBound (const Key & key ) const
int remove (const Key & key )
int size () const
void swap (QMap<Key, T> & other )
T take (const Key & key )
std::map<Key, T> toStdMap () const
QList<Key> uniqueKeys () const
QMap<Key, T> & unite (const QMap<Key, T> & other )
iterator upperBound (const Key & key )
const_iterator upperBound (const Key & key ) const
const T value (const Key & key , const T & defaultValue = T()) const
QList<T> values () const
QList<T> values (const Key & key ) const
bool operator!= (const QMap<Key, T> & other ) const
QMap<Key, T> & operator= (const QMap<Key, T> & other )
QMap<Key, T> & operator= (QMap<Key, T> && other )
bool operator== (const QMap<Key, T> & other ) const
T & operator[] (const Key & key )
const T operator[] (const Key & key ) const
QDataStream & operator<< (QDataStream & out , const QMap<Key, T> & map )
QDataStream & operator>> (QDataStream & in , QMap<Key, T> & map )

详细描述

QMap class is a template class that provides a red-black-tree-based dictionary.

QMap <Key, T> is one of Qt's generic 容器类 。它存储 (键, 值) 对并提供键关联值的快速查找。

QMap and QHash 提供非常类似的功能。差异是:

  • QHash provides average faster lookups than QMap . (See 算法的复杂性 了解细节。)
  • 当遍历 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.

这里是范例 QMap with QString 键和 int 值:

QMap<QString, int> map;
					

要将 (key, value) 对插入映射,可以使用 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);
					

要查找值,使用 operator[]() 或 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 默认构造值 .

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 () 和 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;
}
					

要避免此问题,替换 map[i] with map.value(i) 在以上代码中。

If you want to navigate through all the (key, value) pairs stored in a QMap , you can use an iterator. QMap provides both Java 样式迭代器 ( QMapIterator and QMutableMapIterator ) and STL 样式迭代器 ( 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()) {
    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, 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 () 而不是 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;
    ++i;
}
					

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 为 true。

范例:

#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)
{
    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.

另请参阅 QMapIterator , QMutableMapIterator , QHash ,和 QSet .

成员类型文档编制

typedef QMap:: ConstIterator

Qt 样式同义词 QMap::const_iterator .

typedef QMap:: Iterator

Qt 样式同义词 QMap::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.

成员函数文档编制

QMap:: QMap ()

Constructs an empty map.

另请参阅 clear ().

QMap:: QMap ( std::initializer_list < std::pair < Key , T > > list )

Constructs a map with a copy of each of the elements in the initializer list list .

This function is only available if the program is being compiled in C++11 mode.

该函数在 Qt 5.1 引入。

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

构造副本为 other .

This operation occurs in 常量时间 ,因为 QMap is 隐式共享 . 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 线性时间 .

另请参阅 operator= ().

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

移动构造 QMap instance, making it point at the same object that other 所指向的。

该函数在 Qt 5.2 引入。

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

构造副本为 other .

另请参阅 toStdMap ().

QMap:: ~QMap ()

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

iterator QMap:: begin ()

返回 STL 样式迭代器 pointing to the first item in the map.

另请参阅 constBegin () 和 end ().

const_iterator QMap:: begin () const

这是重载函数。

const_iterator QMap:: cbegin () const

返回常量 STL 样式迭代器 pointing to the first item in the map.

该函数在 Qt 5.0 引入。

另请参阅 begin () 和 cend ().

const_iterator QMap:: cend () const

返回常量 STL 样式迭代器 pointing to the imaginary item after the last item in the map.

该函数在 Qt 5.0 引入。

另请参阅 cbegin () 和 end ().

void QMap:: clear ()

Removes all items from the map.

另请参阅 remove ().

const_iterator QMap:: constBegin () const

返回常量 STL 样式迭代器 pointing to the first item in the map.

另请参阅 begin () 和 constEnd ().

const_iterator QMap:: constEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary item after the last item in the map.

另请参阅 constBegin () 和 end ().

const_iterator QMap:: constFind (const Key & key ) const

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

If the map contains no item with key key , the function returns constEnd ().

该函数在 Qt 4.1 引入。

另请参阅 find () 和 QMultiMap::constFind ().

bool QMap:: contains (const Key & key ) const

返回 true if the map contains an item with key key ;否则返回 false .

另请参阅 count () 和 QMultiMap::contains ().

int QMap:: count (const Key & key ) const

Returns the number of items associated with key key .

另请参阅 contains (), insertMulti (),和 QMultiMap::count ().

int QMap:: count () const

这是重载函数。

如同 size ().

bool QMap:: empty () const

此函数是为兼容 STL 而提供的。它相当于 isEmpty (), returning true if the map is empty; otherwise returning false.

iterator QMap:: end ()

返回 STL 样式迭代器 pointing to the imaginary item after the last item in the map.

另请参阅 begin () 和 constEnd ().

const_iterator QMap:: end () const

这是重载函数。

QPair < iterator , iterator > QMap:: equal_range (const Key & key )

Returns a pair of iterators delimiting the range of values [first, second) , that are stored under key .

QPair < const_iterator , const_iterator > QMap:: equal_range (const Key & key ) const

这是重载函数。

该函数在 Qt 5.6 引入。

iterator QMap:: erase ( iterator pos )

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

另请参阅 remove ().

iterator QMap:: find (const Key & key )

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

If the map contains no item with key key , the function returns end ().

If the map contains multiple items with key key , 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;
}
					

另请参阅 constFind (), value (), values (), lowerBound (), upperBound (),和 QMultiMap::find ().

const_iterator QMap:: find (const Key & key ) const

这是重载函数。

T &QMap:: first ()

Returns a reference to the first value in the map, that is the value mapped to the smallest key. This function assumes that the map is not empty.

When unshared (or const version is called), this executes in 常量时间 .

该函数在 Qt 5.2 引入。

另请参阅 last (), firstKey (),和 isEmpty ().

const T &QMap:: first () const

这是重载函数。

该函数在 Qt 5.2 引入。

const Key &QMap:: firstKey () const

Returns a reference to the smallest key in the map. This function assumes that the map is not empty.

This executes in 常量时间 .

该函数在 Qt 5.2 引入。

另请参阅 lastKey (), first (), keyBegin (),和 isEmpty ().

iterator QMap:: insert (const Key & key , const T & value )

Inserts a new item with the key key and a value of value .

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

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

另请参阅 insertMulti ().

iterator QMap:: insert ( const_iterator pos , const Key & key , const T & value )

这是重载函数。

Inserts a new item with the key key and value value and with hint pos suggesting where to do the insert.

constBegin () is used as hint it indicates that the key is less than any key in the map while constEnd () suggests that the key is (strictly) larger than any key in the map. Otherwise the hint should meet the condition ( pos - 1). key () < key <= pos. key (). If the hint pos is wrong it is ignored and a regular insert is done.

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

If there are multiple items with the key key , then exactly one of them is replaced with value .

If the hint is correct and the map is unshared, the insert executes in amortized 常量时间 .

When creating a map from sorted data inserting the largest key first with constBegin () is faster than inserting in sorted order with constEnd (), since constEnd () - 1 (which is needed to check if the hint is valid) needs logarithmic time .

注意: Be careful with the hint. Providing an iterator from an older shared instance might crash but there is also a risk that it will silently corrupt both the map and the pos map.

该函数在 Qt 5.1 引入。

另请参阅 insertMulti ().

iterator QMap:: insertMulti (const Key & key , const T & value )

Inserts a new item with the key key and a value of value .

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 from insert (), which overwrites the value of an existing item.)

另请参阅 insert () 和 values ().

iterator QMap:: insertMulti ( const_iterator pos , const Key & key , const T & value )

这是重载函数。

Inserts a new item with the key key and value value and with hint pos suggesting where to do the insert.

constBegin () is used as hint it indicates that the key is less than any key in the map while constEnd () suggests that the key is larger than any key in the map. Otherwise the hint should meet the condition ( pos - 1). key () < key <= pos. key (). If the hint pos is wrong it is ignored and a regular insertMulti is done.

If there is already an item with the same key in the map, this function will simply create a new one.

注意: Be careful with the hint. Providing an iterator from an older shared instance might crash but there is also a risk that it will silently corrupt both the map and the pos map.

该函数在 Qt 5.1 引入。

另请参阅 insert ().

bool QMap:: isEmpty () const

返回 true 若映射不包含项;否则返回 false。

另请参阅 size ().

const Key QMap:: key (const T & value , const Key & defaultKey = Key()) const

这是重载函数。

返回第一个键具有值 value ,或 defaultKey if the map contains no item with value value . If no defaultKey is provided the function returns a default-constructed key .

This function can be slow ( 线性时间 ),因为 QMap 's internal data structure is optimized for fast lookup by key, not by value.

该函数在 Qt 4.3 引入。

另请参阅 value () 和 keys ().

key_iterator QMap:: keyBegin () const

返回常量 STL 样式迭代器 pointing to the first key in the map.

该函数在 Qt 5.6 引入。

另请参阅 keyEnd () 和 firstKey ().

key_iterator QMap:: keyEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary item after the last key in the map.

该函数在 Qt 5.6 引入。

另请参阅 keyBegin () 和 lastKey ().

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 with insertMulti (),或 unite () 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, use uniqueKeys ().

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

另请参阅 uniqueKeys (), values (),和 key ().

QList < Key > QMap:: keys (const T & value ) const

这是重载函数。

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

This function can be slow ( 线性时间 ),因为 QMap 's internal data structure is optimized for fast lookup by key, not by value.

T &QMap:: last ()

Returns a reference to the last value in the map, that is the value mapped to the largest key. This function assumes that the map is not empty.

When unshared (or const version is called), this executes in logarithmic time .

该函数在 Qt 5.2 引入。

另请参阅 first (), lastKey (),和 isEmpty ().

const T &QMap:: last () const

这是重载函数。

该函数在 Qt 5.2 引入。

const Key &QMap:: lastKey () const

Returns a reference to the largest key in the map. This function assumes that the map is not empty.

This executes in logarithmic time .

该函数在 Qt 5.2 引入。

另请参阅 firstKey (), last (), keyEnd (),和 isEmpty ().

iterator QMap:: lowerBound (const Key & key )

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

范例:

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 key key , 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;
}
					

另请参阅 upperBound () 和 find ().

const_iterator QMap:: lowerBound (const Key & key ) const

这是重载函数。

int QMap:: remove (const Key & key )

Removes all the items that have the key key 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 if insertMulti () has been used with the key .

另请参阅 clear (), take (),和 QMultiMap::remove ().

int QMap:: size () const

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

另请参阅 isEmpty () 和 count ().

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

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

该函数在 Qt 4.8 引入。

T QMap:: take (const Key & key )

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

If the item does not exist in the map, the function simply returns a 默认构造值 . If there are multiple items for key in the map, only the most recently inserted one is removed and returned.

若不使用返回值, remove () 效率更高。

另请参阅 remove ().

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

Returns an STL map equivalent to this QMap .

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 with insertMulti (),或 unite () was used) occur only once in the returned list.

该函数在 Qt 4.2 引入。

另请参阅 keys () 和 values ().

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

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

另请参阅 insertMulti ().

iterator QMap:: upperBound (const Key & key )

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

范例:

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()
					

另请参阅 lowerBound () 和 find ().

const_iterator QMap:: upperBound (const Key & key ) const

这是重载函数。

const T QMap:: value (const Key & key , const T & defaultValue = T()) const

Returns the value associated with the key key .

If the map contains no item with key key , the function returns defaultValue . If no defaultValue is specified, the function returns a 默认构造值 . If there are multiple items for key in the map, the value of the most recently inserted one is returned.

另请参阅 key (), values (), contains (),和 operator[] ().

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.

另请参阅 keys () 和 value ().

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

这是重载函数。

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

另请参阅 count () 和 insertMulti ().

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

返回 true if other 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 implement operator==() .

另请参阅 operator== ().

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

赋值 other to this map and returns a reference to this map.

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

移动赋值 other 到此 QMap 实例。

该函数在 Qt 5.2 引入。

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

返回 true if other 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 implement operator==() .

另请参阅 operator!= ().

T &QMap:: operator[] (const Key & key )

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

If the map contains no item with key key , the function inserts a 默认构造值 into the map with key key , and returns a reference to it. If the map contains multiple items with key key , this function returns a reference to the most recently inserted value.

另请参阅 insert () 和 value ().

const T QMap:: operator[] (const Key & key ) const

这是重载函数。

如同 value ().

相关非成员

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

写入映射 map 到流 out .

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

另请参阅 QDataStream 运算符格式 .

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

读取映射从流 in into map .

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

另请参阅 QDataStream 运算符格式 .