c++ - 我可以将 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() 的迭代器,并“破解”自定义点以基于此执行可选逻辑,当我无法控制时,我要求提供一般用例容器。
解决方案
您可以添加一个辅助函数,例如
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;
推荐阅读
- ios - 如何检查 fileURL(withPath:) 的返回值是否失败?
- kubernetes - 使用 Helm Chart 和 Kubernetes,在 postStart 期间将文件传递给容器
- javascript - 在创建 cookie 以保持当前背景和文本颜色时需要帮助
- git - 如何在错误提交之前立即获取提交的哈希?
- javascript - 如何加快 Vue.js 命令行进程并优化 webpack 构建
- pyspark - pySpark 数据帧数据插入 Hive 表
- python - 在字典键中搜索模式
- python - 将 QChartView 插入 ui
- jenkins - 在 Jenkins Groovy 管道中合并两个 yaml 文件
- reactjs - react.js-same 组件传递了不同的 props