QMap 的常用操作

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 迭代器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值