大家好,又见面了,我是你们的朋友全栈君。
QMap是一个模板类,提供了一个红黑树结构的查找字典。 注:红黑树结构是自平衡二叉树
QMap<key,T>是一个QT常用的容器类,它存储键值队,并且可以很快的根据键查找值。
QMap 和QHash提供很类似的功能,他们的区别如下:
1. QHash 的查找性能更好;
2. 在遍历QHash时,里面是已经按字母排序好的,但是对于QMap,里面的东西都是按键分类的。
3. QHash的键类型必须提供一个==()的运算符重载并且提供一个通用的qHash(key)函数;QMap要提供一个<运算符重载以排序,
例子:
QMap<QString,int> map;
插入操作,
方式一 : 使用操作符[]():
map[“one”]=1;
map[“three”]=3;
map[“seven”]=7;
方式二: 使用函数insert():
map.insert(“twelve”,12);
查找操作:
使用operator[]() 或者 value():
代码语言:javascript复制 int num1 = map["thirteen"];
代码语言:javascript复制 int num2 = map.value("thirteen");
使用contains()函数检查是否包含该键
代码语言:javascript复制int timeout = 30;
代码语言:javascript复制 if (map.contains("TIMEOUT"))
代码语言:javascript复制 timeout = map.value("TIMEOUT");
使用value()的重载函数,如果没有该键值则会返回一个默认值
代码语言:javascript复制 int timeout = map.value("TIMEOUT", 30); //有timeout返回timeout'的值,没有返回30
总的来说,推荐使用contains()和value()来查找,而不是用[]()来查找,原因是[]()会在map没有改键值的时候插入一个键值对,比如如下代码,实际上在内存中会生成1000个键值对。
代码语言:javascript复制// WRONG
代码语言:javascript复制 QMap<int, QWidget *> map;
代码语言:javascript复制 ...
代码语言:javascript复制 for (int i = 0; i < 1000; i) {
代码语言:javascript复制 if (map[i] == okButton)
代码语言:javascript复制 cout << "Found button at index " << i << endl;
代码语言:javascript复制 }
想避免上述情况,要将map[i]改成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-style iterators (QMapIterator and QMutableMapIterator) and STL-style iterators (QMap::const_iterator and QMap::iterator). Here’s how to iterate over a QMap<QString, int> using a Java-style iterator:
代码语言:javascript复制
代码语言:javascript复制 QMapIterator<QString, int> i(map);
代码语言:javascript复制 while (i.hasNext()) {
代码语言:javascript复制 i.next();
代码语言:javascript复制 cout << i.key() << ": " << i.value() << endl;
代码语言:javascript复制 }
代码语言:javascript复制
Here’s the same code, but using an STL-style iterator this time:
代码语言:javascript复制
代码语言:javascript复制 QMap<QString, int>::const_iterator i = map.constBegin();
代码语言:javascript复制 while (i != map.constEnd()) {
代码语言:javascript复制 cout << i.key() << ": " << i.value() << endl;
代码语言:javascript复制 i;
代码语言:javascript复制 }
代码语言:javascript复制
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:
代码语言:javascript复制
代码语言:javascript复制 map.insert("plenty", 100);
代码语言:javascript复制 map.insert("plenty", 2000);
代码语言:javascript复制 // map.value("plenty") == 2000
代码语言:javascript复制
However, you can store multiple values per key by using insertMulti() instead of 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>:
代码语言:javascript复制
代码语言:javascript复制 QList<int> values = map.values("plenty");
代码语言:javascript复制 for (int i = 0; i < values.size(); i)
代码语言:javascript复制 cout << values.at(i) << endl;
代码语言:javascript复制
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:
代码语言:javascript复制
代码语言:javascript复制 QMap<QString, int>::iterator i = map.find("plenty");
代码语言:javascript复制 while (i != map.end() && i.key() == "plenty") {
代码语言:javascript复制 cout << i.value() << endl;
代码语言:javascript复制 i;
代码语言:javascript复制 }
代码语言:javascript复制
If you only need to extract the values from a map (not the keys), you can also use foreach:
代码语言:javascript复制
代码语言:javascript复制 QMap<QString, int> map;
代码语言:javascript复制 ...
代码语言:javascript复制 foreach (int value, map)
代码语言:javascript复制 cout << value << endl;
代码语言:javascript复制
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 is true.
Example:
代码语言:javascript复制
代码语言:javascript复制 #ifndef EMPLOYEE_H
代码语言:javascript复制 #define EMPLOYEE_H
代码语言:javascript复制
代码语言:javascript复制 class Employee
代码语言:javascript复制 {
代码语言:javascript复制 public:
代码语言:javascript复制 Employee() {}
代码语言:javascript复制 Employee(const QString &name, const QDate &dateOfBirth);
代码语言:javascript复制 ...
代码语言:javascript复制
代码语言:javascript复制 private:
代码语言:javascript复制 QString myName;
代码语言:javascript复制 QDate myDateOfBirth;
代码语言:javascript复制 };
代码语言:javascript复制
代码语言:javascript复制 inline bool operator<(const Employee &e1, const Employee &e2)
代码语言:javascript复制 {
代码语言:javascript复制 if (e1.name() != e2.name())
代码语言:javascript复制 return e1.name() < e2.name();
代码语言:javascript复制 return e1.dateOfBirth() < e2.dateOfBirth();
代码语言:javascript复制 }
代码语言:javascript复制
代码语言:javascript复制 #endif // EMPLOYEE_H
代码语言:javascript复制
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 also QMapIterator, QMutableMapIterator, QHash, and QSet.
Member Type Documentation
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.
Member Function Documentation
QMap::QMap()
Constructs an empty map.
See also 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.
See also 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.
This function is only available if Qt is configured with STL compatibility enabled.
See also 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.
See also 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.
See also begin() and cend().
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.
See also cbegin() and end().
void QMap::clear()
Removes all items from the map.
See also remove().
const_iterator QMap::constBegin() const
Returns a const STL-style iterator pointing to the first item in the map.
See also begin() and constEnd().
const_iterator QMap::constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the map.
See also 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.
See also 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.
See also count() and QMultiMap::contains().
int QMap::count(const Key &key) const
Returns the number of items associated with key key.
See also 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.
See also begin() and constEnd().
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.
See also 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:
代码语言:javascript复制
代码语言:javascript复制 QMap<QString, int> map;
代码语言:javascript复制 ...
代码语言:javascript复制 QMap<QString, int>::const_iterator i = map.find("HDR");
代码语言:javascript复制 while (i != map.end() && i.key() == "HDR") {
代码语言:javascript复制 cout << i.value() << endl;
代码语言:javascript复制 i;
代码语言:javascript复制 }
代码语言:javascript复制
See also 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.
See also 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.
See also 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.
See also 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.
See also 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.)
See also insert() and values().
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.
See also insert().
bool QMap::isEmpty() const
Returns true if the map contains no items; otherwise returns false.
See also 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.
See also value() and keys().
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.
See also keyEnd() and firstKey().
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.
See also keyBegin() and 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(), 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().
See also 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.
See also 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.
See also 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:
代码语言:javascript复制
代码语言:javascript复制 QMap<int, QString> map;
代码语言:javascript复制 map.insert(1, "one");
代码语言:javascript复制 map.insert(5, "five");
代码语言:javascript复制 map.insert(10, "ten");
代码语言:javascript复制
代码语言:javascript复制 map.lowerBound(0); // returns iterator to (1, "one")
代码语言:javascript复制 map.lowerBound(1); // returns iterator to (1, "one")
代码语言:javascript复制 map.lowerBound(2); // returns iterator to (5, "five")
代码语言:javascript复制 map.lowerBound(10); // returns iterator to (10, "ten")
代码语言:javascript复制 map.lowerBound(999); // returns end()
代码语言:javascript复制
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:
代码语言:javascript复制
代码语言:javascript复制 QMap<QString, int> map;
代码语言:javascript复制 ...
代码语言:javascript复制 QMap<QString, int>::const_iterator i = map.lowerBound("HDR");
代码语言:javascript复制 QMap<QString, int>::const_iterator upperBound = map.upperBound("HDR");
代码语言:javascript复制 while (i != upperBound) {
代码语言:javascript复制 cout << i.value() << endl;
代码语言:javascript复制 i;
代码语言:javascript复制 }
代码语言:javascript复制
See also 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.
See also clear(), take(), and QMultiMap::remove().
int QMap::size() const
Returns the number of (key, value) pairs in the map.
See also isEmpty() and count().
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.
See also remove().
std::map<Key, T> QMap::toStdMap() const
Returns an STL map equivalent to this QMap.
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 with insertMulti(), or unite() was used) occur only once in the returned list.
This function was introduced in Qt 4.2.
See also keys() and 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.
See also 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:
代码语言:javascript复制
代码语言:javascript复制 QMap<int, QString> map;
代码语言:javascript复制 map.insert(1, "one");
代码语言:javascript复制 map.insert(5, "five");
代码语言:javascript复制 map.insert(10, "ten");
代码语言:javascript复制
代码语言:javascript复制 map.upperBound(0); // returns iterator to (1, "one")
代码语言:javascript复制 map.upperBound(1); // returns iterator to (5, "five")
代码语言:javascript复制 map.upperBound(2); // returns iterator to (5, "five")
代码语言:javascript复制 map.upperBound(10); // returns end()
代码语言:javascript复制 map.upperBound(999); // returns end()
代码语言:javascript复制
See also 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.
See also 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.
See also keys() and value().
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.
See also 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==().
See also 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==().
See also 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.
See also insert() and value().
const T QMap::operator[](const Key &key) const
This is an overloaded function.
Same as value().
Related Non-Members
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<<().
See also 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>>().
See also Format of the QDataStream operators.
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139399.html原文链接:https://javaforall.cn