QT 中 如何遍历 QMAP
时间: 2024-02-24 18:58:14 浏览: 32
要遍历 QMap,可以使用迭代器来遍历其中的键值对。下面是一个示例代码:
```
QMap<QString, int> myMap;
myMap.insert("apple", 3);
myMap.insert("banana", 2);
myMap.insert("orange", 5);
QMap<QString, int>::const_iterator i = myMap.constBegin();
while (i != myMap.constEnd()) {
qDebug() << i.key() << ": " << i.value();
++i;
}
```
在上面的代码中,使用了 `const_iterator` 来遍历 QMap,`constBegin()` 和 `constEnd()` 分别返回 QMap 的起始和结束迭代器。然后,使用 `key()` 和 `value()` 函数获取键和值。在循环中,使用 `++i` 将迭代器移动到下一个键值对。
相关问题
QT中遍历QMap<QString, int>集合
可以使用QMap的迭代器iterator来遍历QMap<QString, int>集合,代码如下所示:
```cpp
QMap<QString, int> myMap;
myMap.insert("apple", 10);
myMap.insert("banana", 20);
myMap.insert("orange", 30);
// 使用迭代器遍历QMap
QMap<QString, int>::const_iterator iter;
for (iter = myMap.constBegin(); iter != myMap.constEnd(); ++iter)
{
QString key = iter.key(); // 获取键值
int value = iter.value(); // 获取对应的值
qDebug() << key << ":" << value;
}
```
在上述代码中,使用const_iterator遍历QMap,通过`iter.key()`和`iter.value()`分别获取键和值。使用`constBegin()`和`constEnd()`方法返回QMap的迭代器的起始和终止位置。
QT中遍历QMap<QString, int>集合,请给我完整代码
好的,这是遍历QMap<QString, int>集合的完整代码:
```cpp
#include <QMap>
#include <QString>
#include <QDebug>
int main()
{
QMap<QString, int> myMap;
myMap.insert("apple", 10);
myMap.insert("banana", 20);
myMap.insert("orange", 30);
// 使用迭代器遍历QMap
QMap<QString, int>::const_iterator iter;
for (iter = myMap.constBegin(); iter != myMap.constEnd(); ++iter)
{
QString key = iter.key(); // 获取键值
int value = iter.value(); // 获取对应的值
qDebug() << key << ":" << value;
}
return 0;
}
```
在这个例子中,我们定义了一个QMap<QString, int>类型的对象`myMap`,并向其中插入了三个键值对。然后,我们使用迭代器遍历`myMap`对象,输出每个键值对的键和值。