You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

两层嵌套std::map有没有简化双键查找的无异常语法糖?

嵌套std::map多级查找简化方案

核心思路是封装通用的多级查找模板函数,把重复的迭代器判断逻辑下沉到工具层,业务侧无需重复编写多层if判断,所有实现均使用find接口,不会额外插入空节点,也不会抛出异常。

C++17及以上版本(支持任意层级嵌套map)

借助std::optional和折叠表达式实现支持任意层数嵌套map的通用查找:

#include <optional>
#include <map>

// 单层查找终止逻辑
template <typename Map, typename Key>
auto nested_find(const Map& map, const Key& key) -> std::optional<typename Map::mapped_type> {
    auto it = map.find(key);
    return it != map.end() ? std::make_optional(it->second) : std::nullopt;
}

// 多层递归查找逻辑
template <typename Map, typename FirstKey, typename... RestKeys>
auto nested_find(const Map& map, const FirstKey& first_key, RestKeys... rest_keys) {
    auto it = map.find(first_key);
    if (it != map.end()) {
        return nested_find(it->second, rest_keys...);
    }
    using TargetType = std::decay_t<decltype(nested_find(it->second, rest_keys...))>::value_type;
    return std::optional<TargetType>(std::nullopt);
}

业务侧调用方式:

std::map<int, std::map<int, std::string>> nested_map;
nested_map[1][3] = "toto";
int key1 = 1, key2 = 3;

// 一行完成多层查找
auto opt_val = nested_find(nested_map, key1, key2);
if (opt_val.has_value()) {
    std::string val = *opt_val;
    // 查找成功后业务逻辑
}

C++11/14兼容版本

如果项目使用旧标准,可以用输出参数+bool返回值的实现,适配两层嵌套场景(可自行扩展到更多层):

template <typename OuterMap, typename Key1, typename Key2, typename ValueType>
bool nested_find(const OuterMap& outer_map, const Key1& k1, const Key2& k2, ValueType& out_val) {
    auto it_outer = outer_map.find(k1);
    if (it_outer == outer_map.end()) return false;
    auto it_inner = it_outer->second.find(k2);
    if (it_inner == it_outer->second.end()) return false;
    out_val = it_inner->second;
    return true;
}

业务侧调用方式:

std::string val;
if (nested_find(nested_map, key1, key2, val)) {
    // 查找成功直接使用val
}

带默认值的快捷实现

如果查找失败时需要返回默认值,可以直接使用下面的实现,无需额外判断:

template <typename OuterMap, typename Key1, typename Key2, typename ValueType>
ValueType nested_get(const OuterMap& outer_map, const Key1& k1, const Key2& k2, const ValueType& default_val = ValueType()) {
    auto it_outer = outer_map.find(k1);
    if (it_outer == outer_map.end()) return default_val;
    auto it_inner = it_outer->second.find(k2);
    if (it_inner == it_outer->second.end()) return default_val;
    return it_inner->second;
}

业务侧调用方式:

// 查找失败直接返回指定的默认值,这里是空字符串
std::string val = nested_get(nested_map, key1, key2, "");

内容的提问来源于stack exchange,提问作者BlueTrin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:36:04