QMap 是 Qt 库中的一个映射容器,用于存储键/值对。它是 STL 中的 std::map 的替代品,并且具有更好的性能和可读性。
使用 QMap 可以方便地对键/值对进行插入、删除和查找操作,同时保证了键的唯一性。
语法:
QMap map;
其中,Key 为键的数据类型,T 为值的数据类型。
以下是 QMap 的常用操作:
- 插入键/值对:
map.insert(key, value);
- 删除键/值对:
map.remove(key);
- 查找键/值对:
T value = map[key];
- 判断键是否存在:
if (map.contains(key)) {
// 键存在
}
示例代码:
#include
#include
int main() {
QMap map;
// 插入键/值对
map.insert("John", 25);
map.insert("Jane", 30);
map.insert("Jim", 35);
// 查找键/值对
int age = map["John"];
qDebug() << "John's age is" << age;
// 判断键是否存在
if (map.contains("Jane")) {
qDebug() << "Jane exists in the map.";
}
return 0;
}
输出结果:
John's age is 25
Jane exists in the map.
总结:QMap 是 Qt 库中一个非常方便的映射容器,能够实现简单易用的键/值对操作。