2013-03-11 106 views
2

我使用一个共享指针向量来包含一些名为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 
    }  
} 

我已经使用过矢量来保存对象,所以我习惯于在矢量上调用擦除和传入迭代器。我的问题是有没有在上面的代码片段中删除矢量指针的方法?我希望不要在这里使用迭代器来简化代码。我还需要删除指针,因为我是客户一旦离开屏幕就被从游戏中删除。

非常感谢

+1

道歉,我已更新原始帖子以显示此内容。谢谢 – Chris 2013-03-11 16:55:10

+2

这只是乞求错别字。我可能会建议'typedef std :: shared_ptr CustomerPtr;'或类似的? – BoBTFish 2013-03-11 17:01:21

+0

非常正确@BoBTFish。它确实更有意义。已经更新了我的程序以反映这一点。谢谢 – Chris 2013-03-11 17:04:54

回答

3

考虑使用迭代器,坦率地说会更容易对付。我不确定你对他们的厌恶,但看到如下:

std::vector<customer>::iterator it = customers.begin(); 
while (it != customers.end()) 
{ 
    if(it->hasLeftScreen()) 
    { 
     if(!it->itemRecieved()) 
      outOfStocks++; 
     it = customers.erase(it); 
     continue; 
    } 
    ++it; 
} 

这将从矢量中删除共享指针实例。如果实例是对共享指针的引用,它也将释放所述客户的相关内存,释放它的析构函数等等(有些时候首先使用智能共享指针,以及使用道具顺便说一句,智能指针)。

+0

谢谢你。我真的不喜欢使用迭代器。我只是因为在那个时候,for循环更快打字。我让自己感到困惑,因为这是第一次使用共享指针,我仍然试图习惯它们的工作方式,而不是仅仅使用一个普通的旧矢量存储对象。谢谢您的帮助。 – Chris 2013-03-11 17:04:15

+0

@Chris没问题。花一些时间用迭代器,研究不同的类型(一个好的扩展可以在这里找到)(http://en.cppreference.com/w/cpp/iterator))。随着您越来越多地使用标准容器和算法工作,与他们一起流利地付出巨大代价。 – WhozCraig 2013-03-11 17:09:33

+0

辉煌,感谢您的链接。总是希望扩展我的C++知识! – Chris 2013-03-11 17:13:07

2

你应该总是使用迭代器;这是一个C++习惯用法。这将改变代码...

for(auto i = customers.begin(); i != customers.end(); ++i) 
{ 
    if((*i)->hasLeftScreen()) 
    { 
     if(!(*i)->itemRecieved()) 
      outOfStocks++; 
     // Kill Character Here 
    }  
} 

现在,很明显,我们使用erase-remove idiom来代替。

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()); 
0

您也可以利用“迭代算法”的:

 // Kill Character Here 
     customers.erase(customers.begin() + i); 

...但有一个问题,即customers.size()和当前索引就会无效的容器会收缩。

此外,您不需要明确delete您要删除的客户,因为智能指针会处理该问题。