通过unique_ptr值的指针从列表中删除该
Removing a unique_ptr from a list, by its value's pointer
给定一个指向对象的指针,我试图从unique_ptrs
列表中删除相同的对象。我通过匹配更大的unique_ptr
列表的原始指针list
子集的每个元素来做到这一点,该列表肯定包含子集list
中的所有元素。代码:
编辑:为了清晰起见,rawlist子集是std::list<MyObj>
和smartListSet为std::list< unique_ptr<MyObj> >
.
for (auto& deleteThis : rawListSubset)
{
// Find the matching unique_ptr
for (auto& smartPtrElement : smartListSet)
{
if (deleteThis == smartPtrElement.get())
{
unique_ptr<Entity> local = move(smartPtrElement);
// Hence deleting the object when out of scope of this conditional
}
}
}
或者,这不起作用,但它让我明白了我想做的事情。
for (auto& deleteThis : rawListSubset)
{
// Find the matching unique_ptr
for (auto& smartPtrElement : smartListSet)
{
if (deleteThis == smartPtrElement.get())
{
smartListSet.remove(smartPtrElement);
// After this, the API tries to erroneously copy the unique_ptr
}
}
}
如何既可以删除指针指向的对象,又可以安全地从其列表中删除它?
要安全地从循环中的std::list
中删除元素,必须使用迭代器。std::list::erase()
删除迭代器指定的元素,并返回列表中下一个元素的迭代器:
for (auto& deleteThis : rawListSubset)
{
// Find the matching unique_ptr
auto i = smartListSet.begin();
auto e = smartListSet.end();
while (i != e)
{
if (deleteThis == i->get())
i = smartListSet.erase(i);
else
++i;
}
}
可以使用迭代器遍历list来删除元素,而不是使用范围循环:
for (auto& deleteThis : rawListSubset)
{
// Find the matching unique_ptr
for (auto smartPtrIter = smartListSet.begin(); smartPtrIter != smartListSet.end(); )
{
if (deleteThis == smartPtrIter->get())
{
smartListSet.erase(smartPtrIter++);
} else
++smartPtrIter;
}
}
当你从列表中删除智能指针所指向的元素时,智能指针所指向的对象将被删除。
相关文章:
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- 删除列表 c++ 中的最后 3 个元素
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- C++ 从具有开始位置和结束位置的列表中删除
- 从列表向量中删除无法按预期工作
- 从列表C++中删除对象
- 简单的链接列表删除失败
- C++循环链接列表 - 删除所有节点
- 链接列表删除节点C
- 链接列表删除
- 矢量与来自 STL 的列表 - 删除方法
- 运算符== 和列表::删除()