如何通过指针从容器中删除 unique_ptr?
使用 unique_ptr 创建对象并赋予容器所有权是没有问题的。如何通过原始指针删除元素?
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
Creating an object and giving ownership to a container using a unique_ptr is no problem. How would one remove an element by raw pointer?
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要找到与
myClass
元素对应的迭代器,然后将该迭代器传递给mySet.erase()
。可以使用std::find_if
算法和自定义Predicate
函子来找到迭代器,该函子了解如何取消引用unique_ptr
并将其与原始值进行比较指针myClass
。您不能使用重载的
size_t set::erase ( const key_type& x );
,因为在以下位置找不到原始指针(即使包装在临时unique_ptr
中)mySet
。You will need to find the iterator corresponding to the
myClass
element and then pass that iterator tomySet.erase()
. The iterator may be found using thestd::find_if
algorithm with a customPredicate
functor that understands how to dereferenceunique_ptr
and compare it to the raw pointermyClass
.You can not use the overloaded
size_t set::erase ( const key_type& x );
since the raw pointer (even if wrapped in a temporaryunique_ptr
) will not be found inmySet
.没有我想要的那么漂亮。但以下内容可以完成这项工作:
Not as pretty as I would've liked. But the following does the job:
看来我能够使用带有 lower_bound 的自定义谓词来检索迭代器。由于 std::set 是一个有序容器,因此 lower_bound 应该以对数方式执行。
It seems i am able to retrieve an iterator using a custom Predicate with lower_bound. Since std::set is an ordered container, lower_bound should perform logarithmically.
仍然不是最好的解决方案,但目前我选择:
标题是:
Still not the best solution but for the moment i go with:
The header is:
您可能喜欢这里的答案:有效擦除a unique_ptr from an unordered_set
这适用于 C++14,但我认为也适用于 C++11。
它并不漂亮,但效率很高——不扫描容器,而是使用适当的基于哈希的查找。
You might like the answer over here: Efficiently erase a unique_ptr from an unordered_set
That's for C++14, but I think applies to C++11 as well.
It is not pretty, but does the efficient thing — no scanning the container, but using proper hash-based lookup.
异常安全的解决方案,具有基于哈希的高效查找(因此消除了 std::find_if 或 std::lower_bound 的线性时间复杂度)并且没有透明度限制(这是我对类似问题的回答的副本):
用法:
以便您得到
Exception-safe solution with efficient hash-based lookup (so the linear time complexity of
std::find_if
orstd::lower_bound
is eliminated) and no transparency restrictions (this is a copy of my answer to a similar question):Usage:
So that you get