从vector对象中删除指针
Deleting a pointer from a vector
我使用一个共享指针向量来包含一些叫做customer的游戏角色。
typedef std::shared_ptr<Customer> customer;
std::vector<customer> customers;
customers.push_back(customer(new Customer()));
for(int i = 0; i < customers.size(); i++)
{
if(customers[i]->hasLeftScreen())
{
if(!customers[i]->itemRecieved())
outOfStocks++;
// Kill Character Here
}
}
我以前使用vector来保存对象,所以我习惯在vector上调用erase并将其传递给迭代器。我的问题是有一种方法删除一个指针从矢量在上述代码片段?我不希望在这里使用迭代器来简化代码。我还需要删除指针,因为我是客户被从游戏中删除,一旦它已经离开屏幕。
多谢
考虑使用迭代器,坦率地说,这将更容易处理。我不确定你是否讨厌它们,但请参阅以下内容:
std::vector<customer>::iterator it = customers.begin();
while (it != customers.end())
{
if(it->hasLeftScreen())
{
if(!it->itemRecieved())
outOfStocks++;
it = customers.erase(it);
continue;
}
++it;
}
这将从vector对象中移除共享指针实例。如果该实例是对共享指针的最后一个引用,它还将释放所述Customer的关联内存,触发其析构函数,等等。(从某种程度上讲,这是首先使用智能共享指针的要点,顺便说一下,使用智能指针的道具)。
应该始终使用迭代器;这是c++的习惯用法。这会将代码更改为…
for(auto i = customers.begin(); i != customers.end(); ++i)
{
if((*i)->hasLeftScreen())
{
if(!(*i)->itemRecieved())
outOfStocks++;
// Kill Character Here
}
}
现在,很明显,我们使用擦除-删除习语。
int outOfStocks = 0;
auto it = std::remove_if(customer.begin(), customers.end(), [&](Customer const& i) {
if(i->hasLeftScreen()) {
if(!i->itemRecieved()) {
outOfStocks++;
}
return true;
}
return false;
}
std::erase(it, customers.end());
你也可以利用"iterator arithmetic":
// Kill Character Here
customers.erase(customers.begin() + i);
…但这有一个问题,customers.size()
和当前索引将无效,因为容器将收缩。
同样,你不需要显式地delete
你要删除的客户,因为智能指针会照顾它。
相关文章:
- 无法删除指针,已触发断点
- 删除指针数组 (C++) 中的元素
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 为什么const_cast删除指针的恒常性,而不删除指向常量的指针的恒常性?
- 删除指针后内存泄漏
- 这是系统资源吗?(或者我怎么知道我是否需要删除指针) - 在 C++ 中使用 C
- C++ 从 2 组指针中删除指针
- 当删除 [] 指针工作时,为什么无法获得指向的数组大小?
- 在这种情况下,删除指针数组期间会发生什么?
- 在C++中删除指针数组时析构函数崩溃
- 何时/如何在使用指针后正确删除指针?
- 在C++库中,谁应该删除指针、用户或库?
- 删除指针后阻止对象使用 "this"
- 删除指针后C++尝试/捕获
- 删除指针内存分配以避免内存泄漏
- 删除指针时,未分配被释放的 C++ 指针错误
- 如何从抽象类中删除指针
- 我应该在 v8::外部手动删除指针吗?
- 删除指针
- C 如何删除指针的默认对象成员