首页 > 解决方案 > 我可以将 std::map 迭代器解包到可选的结构化绑定吗?

问题描述

考虑以下代码:

#include<functional>
#include<iostream>
#include<map>

const std::map<int, std::string> numberToStr{{1, "one"}, {2,"two"}};
int main() {
    auto it = numberToStr.find(2);
    if (it ==numberToStr.end()){
        return 1;
    }
    const auto&[_, str] = *it;
    std::cout << str;
}

我有什么办法可以解开可能被取消引用it到 2 个选项(_ 和 str),这样我就可以写:

const auto&[_, str] = // some magic;
// _ is std::optional<int>, str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;
}

我认为不是,因为结构化绑定是语言级别的东西,而 std::optional 是一个库功能,afaik 没有办法自定义交互。

注意:我假设我可以实现自己的映射,该映射返回知道它们是否指向 .end() 的迭代器,并“破解”自定义点以基于此执行可选逻辑,当我无法控制时,我要求提供一般用例容器。

标签: c++c++17c++20structured-bindings

解决方案


您可以添加一个辅助函数,例如

template <typename Key, typename Value, typename... Rest>
std::pair<std::optional<Key>, std::optional<Value>> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find)
{
    auto it = map.find(to_find);
    if (it == map.end())
        return {};
    else
        return {it->first, it->second};
}

然后你会像使用它一样

const auto&[_, str] = my_find(numberToStr, 2);
// _ is std::optional<int>, str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;

如果您只关心该值,则可以通过将其返回来稍微缩短代码

template <typename Key, typename Value, typename... Rest>
std::optional<Value> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find)
{
    auto it = map.find(to_find);
    if (it == map.end())
        return {};
    else
        return {it->second};
}

然后你会像这样使用它

auto str = my_find(numberToStr, 2);
// str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;

推荐阅读