在Qt 6.7中,遍历QMap的键(key)可以通过多种方式实现。以下是一些常用的遍历QMap键的方法:
使用迭代器遍历键
你可以使用QMap的迭代器来遍历所有的键。
QMap<QString, int> map;
// 假设map已经填充了数据
QMap<QString, int>::iterator it;
for (it = map.begin(); it != map.end(); ++it) {
qDebug() << "Key:" << it.key();
}
或者使用const_iterator,如果你不需要修改map中的值:
QMap<QString, int>::const_iterator cit;
for (cit = map.constBegin(); cit != map.constEnd(); ++cit) {
qDebug() << "Key:" << cit.key();
}
使用范围for循环遍历键
如果你使用的是C++11或更高版本,你可以使用范围for循环更简洁地遍历键。
QMap<QString, int>::const_iterator cit;
for (cit = map.constBegin(); cit != map.constEnd(); ++cit) {
qDebug() << "Key:" << cit.key();
}
在这个例子中,pair.first代表键,pair.second代表值。
使用QMap的keys()方法
你还可以使用QMap的keys()方法来获取所有键的列表,并遍历这个列表。
QList<QString> keys = map.keys();
for (const QString& key : keys) {
qDebug() << "Key:" << key;
}
这种方法会先生成一个包含所有键的QList,然后你可以遍历这个列表。这种方法可能不如直接使用迭代器或范围for循环高效,特别是在QMap很大的情况下。
总的来说,在Qt 6.7中遍历QMap的键,你可以选择使用迭代器、范围for循环或先获取键列表再遍历的方法。选择哪种方法取决于你的具体需求和偏好。
Qt 6.7中遍历QMap键的方法
4868

被折叠的 条评论
为什么被折叠?



