实现在Map中移除键2、3、4,在while中实现 QMap<int,QString>tMap; tMap.insert(1,“11”); tMap.insert(2,“12”); tMap.insert(3,“13”); tMap.insert(4,“14”); tMap.insert(5,“15”); QMap<int,QString>::lteratoritor=tMapbegin();
时间: 2023-06-15 13:05:22 浏览: 74
您可以使用QMap的remove函数来移除指定的键,如下所示:
```c++
QMap<int, QString> tMap;
tMap.insert(1, "11");
tMap.insert(2, "12");
tMap.insert(3, "13");
tMap.insert(4, "14");
tMap.insert(5, "15");
tMap.remove(2);
tMap.remove(3);
tMap.remove(4);
QMap<int, QString>::iterator iter = tMap.begin();
while (iter != tMap.end()) {
qDebug() << iter.key() << iter.value();
iter++;
}
```
上述代码将移除键2、3、4,然后使用迭代器遍历Map并输出结果。
相关问题
打印QMap<int,QString>
你可以使用以下代码打印QMap<int, QString>:
```cpp
QMap<int, QString> myMap;
// 添加元素到 QMap
myMap.insert(1, "Hello");
myMap.insert(2, "World");
// 打印 QMap
for(auto iter = myMap.begin(); iter != myMap.end(); ++iter)
{
qDebug() << iter.key() << ":" << iter.value();
}
```
输出结果为:
```
1 : "Hello"
2 : "World"
```
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的迭代器的起始和终止位置。