首页 > 解决方案 > 如何在 c++11 中使用 lamda 表达式过滤 std::map 键

问题描述

我在 std::map<std::string, std::string> 中有包含日期​​作为键和一些字节作为值的映射。例如

std::map<std::string , std::string> mapval = {{"2020-09-24", "1024"}, {"2020-09-25", "1024"},{"2020-09-26", "1024"},
    {"2020-09-27", "1024"},{"2020-09-28", "1024"}};

我是否可以仅从给定的日期范围内检索密钥,例如如果我想要从当前日期起三天的数据,那么我将只获取“2020-09-24”、“2020-09-25”和 {“2020-09 -26”,“1024”}。我想要一个通用的,其中我有开始日期和结束日期,我将过滤该范围内的值和我将删除的其他值。可能吗 ?

标签: c++c++11

解决方案


我不确定我是否完全理解这个问题,但也许这会很接近:

mapval = std::map<std::string , std::string>(
    mapval.lower_bound(start_date),
    mapval.upper_bound(end_date));

这将保留mapval其键落在start_dateend_date(包括)之间的范围内的元素,并删除所有其他元素。


推荐阅读