QMap
是 Qt 框架中用于存储键值对的数据结构,按照键的顺序自动排序。以下是常用的 QMap
使用方法:
1. 插入键值对
QMap<QString, int> map;
map.insert("apple", 10); // 插入键值对
2. 访问值
int value = map.value("apple"); // 获取键为 "apple" 的值
3. 检查键是否存在
if (map.contains("apple")) { // 检查键是否存在
qDebug() << "Key exists";
}
4. 修改值
map["apple"] = 20; // 修改键为 "apple" 的值
5. 删除键值对
map.remove("apple"); // 删除键为 "apple" 的键值对
6. 获取所有键
QList<QString> keys = map.keys(); // 获取所有键的列表
7. 获取所有值
QList<int> values = map.values(); // 获取所有值的列表
8. 清空容器
map.clear(); // 清空所有键值对
9. 遍历 QMap
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
qDebug() << "Key:" << it.key() << ", Value:" << it.value();
}
10. 根据值排序
QVector<std::pair<QString, int>> items;
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
items.push_back(*it);
}
std::sort(items.begin(), items.end(), [](const std::pair<QString, int>& a,
const std::pair<QString, int>& b) {
return a.second > b.second; // 按值降序排序
});
11. 查找排在第 N 位的键
QVector<std::pair<double, int>> items;
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
items.push_back(*it);
}
std::sort(items.begin(), items.end(), [](const std::pair<double, int>& a,
const std::pair<double, int>& b) {
return a.second > b.second; // 按值降序排序
});
int index = static_cast<int>(0.3 * items.size()); // 第30%位置
double key30Percent = items[index].first;
注意事项
-
QMap
按键的顺序自动排序,键不需要明确排序。 -
如果需要按值排序,需使用额外容器(如
QVector
)并自定义比较函数。 -
在遍历时,如果需要修改数据,请使用非 const 迭代器。