【发布时间】: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<std::string> &了吗?它只需要 1 次间接。 -
你能不能像这样写一个
std::set<std::unique_ptr<std::string>>:godbolt.org/z/3redfW ?? -
@JeJo You can't.
标签: c++ algorithm c++17 smart-pointers stdset