Qt 命名空间中声明并使用 QMap

在 Qt 中,可以在命名空间中声明 QMap 并赋值。下面是一个示例代码:

#include <QMap>
#include <QDebug>

namespace MyNamespace {
    void example() {
        QMap<QString, int> map;
        map.insert('Alice', 25);
        map.insert('Bob', 30);
        map.insert('Charlie', 35);
        
        // 输出 map 中的所有键值对
        QMapIterator<QString, int> i(map);
        while (i.hasNext()) {
            i.next();
            qDebug() << i.key() << ': ' << i.value();
        }
    }
}

int main() {
    MyNamespace::example();
    return 0;
}

在上面的示例中,我们在 MyNamespace 命名空间中声明了一个 QMap<QString, int> 类型的 map 变量,并且使用 insert 函数向其中插入了一些键值对。然后,我们使用 QMapIterator 遍历了 map 中的所有键值对,并通过 qDebug() 函数输出了它们。

注意,在使用 QMapIterator 遍历 map 时,需要包含 <QMapIterator> 头文件。

运行上面的代码,输出将会是:

Alice :  25
Bob :  30
Charlie :  35

这样就完成了在命名空间里面声明 QMap 并赋值的操作。

Qt 命名空间中声明并使用 QMap

原文地址: https://www.cveoy.top/t/topic/p2hg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录