【问题标题】:How to get the first element in a std::set of pointers, where the pointer points to a specific value?如何获取 std::set 指针中的第一个元素,其中指针指向特定值?
【发布时间】:2023-03-17 18:53:01
【问题描述】:

假设你有一个 C++ std::set 的唯一指针,例如

auto my_set = std::set<std::unique_ptr<std::string>> 
{ 
    std::make_unique<std::string>("monkey"),
    std::make_unique<std::string>("banana"),
    std::make_unique<std::string>("orange") 
};

使用std::find_if 函数,您将如何找到该集合中的第一个元素,使得指针指向“orange”?

到目前为止,我得到了:

auto food = "orange";
auto find_orange
   = std::find_if(my_set.begin(), my_set.end(), [&food](const auto& ptr) -> bool {
        return *(*ptr) == food;
    }
);

但这不会编译。关于问题的任何想法?

在这些函数中,ptr 到底是什么? 即谓词中的参数?是指向容器每个元素的指针吗?

【问题讨论】:

  • 为什么要使用指向字符串的唯一指针?
  • 是不是因为第一行的“orange”后面忘记了分号而导致编译失败?
  • ptr 不是已经是const std::unique_ptr&lt;std::string&gt; &amp; 了吗?它只需要 1 次间接。
  • 你能不能像这样写一个std::set&lt;std::unique_ptr&lt;std::string&gt;&gt;:godbolt.org/z/3redfW ??
  • @JeJo You can't.

标签: c++ algorithm c++17 smart-pointers stdset


【解决方案1】:

该问题缺少适当的最小可重现示例。当我们制作一个 MCVC 时:https://godbolt.org/z/bfYx39

问题来自于 lambda return

return *(*ptr) == food;

作为auto,有std::unique_ptr&lt;std::string&gt;。因此,您只需取消引用一次:

auto find_orange = std::find_if(my_set.begin(), my_set.end(),
      [&food](const auto& ptr) {
         return *ptr == food;
         //     ^^^^^^^^^^^^
      }
   );

你不需要在那里双重取消引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    相关资源
    最近更新 更多