从不同来源返回范围

huangapple go评论70阅读模式
英文:

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&amp; mic)
{
  auto it = some_map.find(mic);
  return it != some_map.end() ?
    std::optional{it-&gt;second  | std::views::transform(
                                  [](auto id) -&gt; const Security&amp; { return ...; })} :
    std::nullopt;
}

Then you can use it like this

if (auto opt = get_securities_by_mic(&quot;key&quot;); 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&amp; mic)
{
  auto it = some_map.find(mic);
  return (it != some_map.end() ? std::span{it-&gt;second} :
                                 std::span&lt;const std::int64_t&gt;{})
    | std::views::transform([](auto id) -&gt; const Security&amp; { return ...; });
}

huangapple
  • 本文由 发表于 2023年7月3日 10:48:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定