如何获取指针指向特定值的std::set中的第一个元素?

How to get the first element in a std::set of pointers, where the pointer points to a specific value?

假设您有一个 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 即谓词中的参数?是指向容器每个元素的指针吗?

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

问题来自 lambda return

return *(*ptr) == food;

作为 autostd::unique_ptr<std::string>。因此,您只需要取消引用一次:

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

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