首页 > 解决方案 > 查找对的匹配键范围

问题描述

假设我有一张地图:

std::map<std::pair<string,int>,int> map_example;

如何在我的地图中找到具有以下属性的键的所有元素: 对中的字符串是“A”,int 介于 5 和 10 之间,包括 5 和 10。或者,将我的地图制作成如下图会更好吗?

std::map<string,std::map<int,int> map_example2;

标签: c++dictionary

解决方案


result变量将为您提供一个map包含map_example符合您条件的所有元素:

decltype(map_example) result;
for (const auto& item : map_example) {
    const auto& key = item.first;
    if (key.first == "A" && key.second >= 5 && key.second <= 10)
        result.insert(item);
}

它遍历整个map并检查每个元素是否满足条件,如果是,则将元素插入到result map.


推荐阅读