英文:
Return range from different sources
问题
你是否可以以某种更好的方式编写它?
英文:
I'm wondering how to make same type for return value? Consider an example:
auto get_securities_by_mic(const std::string& mic)
{
auto it = some_map.find(mic);
// I want to write like this:
if (it == some_map.end()) return std::views::empty<const Security&>;
return it->second | std::views::transform([](id)->const Security&{...});
}
But it code cannot be compiled(
I came up with solution:
auto get_securities_by_mic(const std::string& mic)
{
auto it = some_map.find(mic);
static const std::vector<std::int64_t> empty;
auto source = it != some_map.end() ? std::views::all(it->second) : std::views::all(empty);
return source | std::views::transform([](id) -> const Security&{...});
}
Can I write somehow better?
答案1
得分: 2
而不是返回一个空范围,您可以返回一个 optional
来指示是否找到了一个值。
auto get_securities_by_mic(const std::string& mic)
{
auto it = some_map.find(mic);
return it != some_map.end() ?
std::optional{it->second | std::views::transform(
[](auto id) -> const Security& { return ...; })} :
std::nullopt;
}
然后您可以像这样使用它:
if (auto opt = get_securities_by_mic("key"); opt)
for (auto x : *opt)
use(x);
如果您仍然想返回一个范围,您也可以使用一个空的 span
来处理未找到的情况:
auto get_securities_by_mic(const std::string& mic)
{
auto it = some_map.find(mic);
return (it != some_map.end() ? std::span{it->second} :
std::span<const std::int64_t>{})
| std::views::transform([](auto id) -> const Security& { return ...; });
}
英文:
Instead of returning an empty range, you can return an optional
to indicate whether a value was found
auto get_securities_by_mic(const std::string& mic)
{
auto it = some_map.find(mic);
return it != some_map.end() ?
std::optional{it->second | std::views::transform(
[](auto id) -> const Security& { return ...; })} :
std::nullopt;
}
Then you can use it like this
if (auto opt = get_securities_by_mic("key"); opt)
for (auto x : *opt);
use(x);
If you still want to return a range, you can also use an empty span
to handle not found cases:
auto get_securities_by_mic(const std::string& mic)
{
auto it = some_map.find(mic);
return (it != some_map.end() ? std::span{it->second} :
std::span<const std::int64_t>{})
| std::views::transform([](auto id) -> const Security& { return ...; });
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论