从vector对象中删除指针

Deleting a pointer from a vector

本文关键字:删除 指针 对象 vector      更新时间:2023-10-16

我使用一个共享指针向量来包含一些叫做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你要删除的客户,因为智能指针会照顾它。