QMap的说明和简单使用_qmap detach

QMap的说明和简单使用_qmap detach

编码文章call10242025-02-18 10:37:0510A+A-

QMap 是 Qt 库中的一个映射容器,用于存储键/值对。它是 STL 中的 std::map 的替代品,并且具有更好的性能和可读性。

使用 QMap 可以方便地对键/值对进行插入、删除和查找操作,同时保证了键的唯一性。

语法:

QMap map;

其中,Key 为键的数据类型,T 为值的数据类型。

以下是 QMap 的常用操作:

  1. 插入键/值对:
map.insert(key, value);
  1. 删除键/值对:
 map.remove(key);
  1. 查找键/值对:
T value = map[key];
  1. 判断键是否存在:
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 库中一个非常方便的映射容器,能够实现简单易用的键/值对操作。

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4