QMap Class
QMap 是一种模板类, 提供基于红黑树的字典类结构. 更多...
头文件: | #include <QMap> |
qmake: | QT += core |
派生类: |
Note: All functions in this class are reentrant.
公有类型
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 是一种模板类, 提供基于红黑树的字典类结构.
QMap<Key, T> 是一种 Qt 泛型 容器类. 该类存储键值对, 可以用相关联的键快速查找值.
QMap 的功能与 QHash 非常相似. 二者的区别在于:
- QHash 的平均查找速度比 QMap 快. (详见 Algorithmic Complexity.)
- 遍历 QHash 时, 元素的顺序是任意的. 而遍历 QMap 时, 元素总是按照键的顺序排好序的.
- QHash 的键类型必须提供 operator==() 运算符和全局的 qHash(Key) 函数. QMap 的键类型必须提供 operator<() 运算符来确定全序. 从 Qt 5.8.1 起,即使底层的 operator<() 运算符没有提供全序, 使用指针作为键类型也是安全的.
下面是一个键类型为 QString, 值类型为 int
的 QMap 的示例:
QMap<QString, int> map;
你可以使用 operator[]() 运算符将键值对插入到 QMap 中:
map["one"] = 1; map["three"] = 3; map["seven"] = 7;
上面的代码将3个键值对插入到 QMap 中: ("one", 1), ("three", 3), ("seven", 7). 另外一种向 map 中插入元素的方法是使用 insert():
map.insert("twelve", 12);
使用 operator[]() 运算符或 value() 查找值:
int num1 = map["thirteen"]; int num2 = map.value("thirteen");
如果 map 中不存在指定的键, 这些函数返回 默认构造的值.
如果想检查 map 中是否包含特定键, 使用 contains():
int timeout = 30; if (map.contains("TIMEOUT")) timeout = map.value("TIMEOUT");
还有一个 value() 的重载函数, 如果 map 中不存在指定键的元素, 该函数使用第2个参数作为默认值:
int timeout = map.value("TIMEOUT", 30);
一般推荐使用 contains() 和 value(), 而不是 operator[]() 运算符查找 map 中的键. 原因是如果 map 中不存在相同键的元素, operator[]() 运算符会默默地将一个元素插入到 map 中 (除非 map 是 const ). 例如, 下面的代码片段将在内存中创建1000个元素:
// 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]
替换为 map.value(i)
.
如果想遍历 QMap中存储的所有键值对, 可以使用迭代器. QMap 同时提供 Java 风格迭代器 (QMapIterator 和 QMutableMapIterator) 和 STL 风格迭代器 (QMap::const_iterator 和 QMap::iterator). 下面是使用 Java 风格迭代器遍历 QMap<QString, int> 的方法:
QMapIterator<QString, int> i(map); while (i.hasNext()) { i.next(); cout << i.key() << ": " << i.value() << endl; }
下面是相同的代码, 不过这次使用 STL 风格迭代器:
QMap<QString, int>::const_iterator i = map.constBegin(); while (i != map.constEnd()) { cout << i.key() << ": " << i.value() << endl; ++i; }
上面的代码按照键的升序遍历各元素.
通常, QMap 每个键只允许有一个值. 如果用已经存在的键调用 insert(), 先前的值将被删除. 例如:
map.insert("plenty", 100); map.insert("plenty", 2000); // map.value("plenty") == 2000
然而, 可以使用派生类 QMultiMap 在一个键中存储多个值. 使用 values(const Key &key)取得单个键关联的所有值, 该函数返回一个 QList<T>:
QList<int> values = map.values("plenty"); for (int i = 0; i < values.size(); ++i) cout << values.at(i) << endl;
共享同一键的多个元素按照从最新到最早插入的顺序返回. 另外一种方法是调用 find() 取得 STL 风格迭代器, 该迭代器指向共享同一键的多个元素中的第一个元素, 然后从该元素开始遍历:
QMap<QString, int>::iterator i = map.find("plenty"); while (i != map.end() && i.key() == "plenty") { cout << i.value() << endl; ++i; }
如果只想从 map 中获取值(而不是键), 也可以使用 foreach:
QMap<QString, int> map; ... foreach (int value, map) cout << value << endl;
移除元素有几种方法. 一种是调用 remove(); 该函数移除指定键的所有元素. 另一种方法是使用 QMutableMapIterator::remove(). 另外, 还可以使用 clear() 清除整个 map.
QMap 键和值的数据类型必须是 可赋值数据类型. 这涵盖了大多数可能会遇到的数据类型, 但是编译器不会存储 QWidget 这样的对象作为值; 应该存储 QWidget *. 另外, QMap的键类型必须提供 operator<()运算符. QMap 用它来保持元素有序, 并假定两个键 x
和 y
在 x < y
和 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
该例中, 先比较雇员名. 如果雇员名相等, 再比较二者的生日来分出大小.
参见 QMapIterator, QMutableMapIterator, QHash, QSet.
成员类型
typedef QMap::ConstIterator
Qt-style synonym for QMap::const_iterator.
typedef QMap::Iterator
Qt-style synonym for 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.
This function was introduced in Qt 5.1.
QMap::QMap(const QMap<Key, T> &other)
Constructs a copy of other.
This operation occurs in constant time, because QMap is implicitly shared. 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 linear time.
参见 operator=().
QMap::QMap(QMap<Key, T> &&other)
Move-constructs a QMap instance, making it point at the same object that other was pointing to.
This function was introduced in Qt 5.2.
QMap::QMap(const std::map<Key, T> &other)
Constructs a copy of 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()
Returns an STL-style iterator pointing to the first item in the map.
参见 constBegin() and end().
const_iterator QMap::begin() const
This is an overloaded function.
const_iterator QMap::cbegin() const
Returns a const STL-style iterator pointing to the first item in the map.
This function was introduced in Qt 5.0.
const_iterator QMap::cend() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the map.
This function was introduced in Qt 5.0.
void QMap::clear()
Removes all items from the map.
参见 remove().
const_iterator QMap::constBegin() const
Returns a const STL-style iterator pointing to the first item in the map.
const_iterator QMap::constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the map.
参见 constBegin() and 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().
This function was introduced in Qt 4.1.
参见 find() and QMultiMap::constFind().
bool QMap::contains(const Key &key) const
Returns true
if the map contains an item with key key; otherwise returns false
.
参见 count() and QMultiMap::contains().
int QMap::count(const Key &key) const
Returns the number of items associated with key key.
参见 contains(), insertMulti(), and QMultiMap::count().
int QMap::count() const
This is an overloaded function.
Same as size().
bool QMap::empty() const
This function is provided for STL compatibility. It is equivalent to isEmpty(), 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.
const_iterator QMap::end() const
This is an overloaded function.
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
This is an overloaded function.
This function was introduced in 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(), and QMultiMap::find().
const_iterator QMap::find(const Key &key) const
This is an overloaded function.
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 constant time.
This function was introduced in Qt 5.2.
参见 last(), firstKey(), and isEmpty().
const T &QMap::first() const
This is an overloaded function.
This function was introduced in 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 constant time.
This function was introduced in Qt 5.2.
参见 lastKey(), first(), keyBegin(), and 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)
This is an overloaded function.
Inserts a new item with the key key and value value and with hint pos suggesting where to do the insert.
If 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 constant time.
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.
Note: 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.
This function was introduced in 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.)
iterator QMap::insertMulti(const_iterator pos, const Key &key, const T &value)
This is an overloaded function.
Inserts a new item with the key key and value value and with hint pos suggesting where to do the insert.
If 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.
Note: 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.
This function was introduced in Qt 5.1.
参见 insert().
bool QMap::isEmpty() const
Returns true
if the map contains no items; otherwise returns false.
参见 size().
const Key QMap::key(const T &value, const Key &defaultKey = Key()) const
This is an overloaded function.
Returns the first key with value value, or 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 (linear time), because QMap's internal data structure is optimized for fast lookup by key, not by value.
This function was introduced in Qt 4.3.
key_iterator QMap::keyBegin() const
Returns a const STL-style iterator pointing to the first key in the map.
This function was introduced in Qt 5.6.
key_iterator QMap::keyEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last key in the map.
This function was introduced in Qt 5.6.
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(), or 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(), and key().
QList<Key> QMap::keys(const T &value) const
This is an overloaded function.
Returns a list containing all the keys associated with value value in ascending order.
This function can be slow (linear time), because 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.
This function was introduced in Qt 5.2.
参见 first(), lastKey(), and isEmpty().
const T &QMap::last() const
This is an overloaded function.
This function was introduced in 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.
This function was introduced in Qt 5.2.
参见 firstKey(), last(), keyEnd(), and 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.
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 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() and find().
const_iterator QMap::lowerBound(const Key &key) const
This is an overloaded function.
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(), and QMultiMap::remove().
int QMap::size() const
Returns the number of (key, value) pairs in the map.
void QMap::swap(QMap<Key, T> &other)
Swaps map other with this map. This operation is very fast and never fails.
This function was introduced in 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 default-constructed value. If there are multiple items for key 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.
参见 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(), or unite() was used) occur only once in the returned list.
This function was introduced in Qt 4.2.
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.
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()
参见 lowerBound() and find().
const_iterator QMap::upperBound(const Key &key) const
This is an overloaded function.
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 default-constructed value. If there are multiple items for key in the map, the value of the most recently inserted one is returned.
参见 key(), values(), contains(), and 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.
QList<T> QMap::values(const Key &key) const
This is an overloaded function.
Returns a list containing all the values associated with key key, from the most recently inserted to the least recently inserted one.
参见 count() and insertMulti().
bool QMap::operator!=(const QMap<Key, T> &other) const
Returns 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)
Assigns other to this map and returns a reference to this map.
QMap<Key, T> &QMap::operator=(QMap<Key, T> &&other)
Move-assigns other to this QMap instance.
This function was introduced in Qt 5.2.
bool QMap::operator==(const QMap<Key, T> &other) const
Returns 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 default-constructed value 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.
const T QMap::operator[](const Key &key) const
This is an overloaded function.
Same as value().
相关非成员
QDataStream &operator<<(QDataStream &out, const QMap<Key, T> &map)
Writes the map map to stream out.
This function requires the key and value types to implement operator<<()
.
参见 Format of the QDataStream operators.
QDataStream &operator>>(QDataStream &in, QMap<Key, T> &map)
Reads a map from stream in into map.
This function requires the key and value types to implement operator>>()
.