2011-12-29 53 views
0

我正在将矢量更改为列表,而我遇到了一些问题。从std :: list中随机擦除?

此代码是不正确现在:

privateChildren.erase(privateChildren.begin() + 
      getPrivateChildIndex(widget)); 

如何来解决。用户给出他们想要擦除的小部件的索引。

谢谢

getPrivateChildIndex返回私有子的索引。所以,如果我推3个孩子,getPrivateChildIndex(thirdElem)将返回2.

+0

你必须解释更多:什么是getPrivateChildIndex()。什么是回报类型和价值。 – 2011-12-29 02:58:32

回答

0

理想地,对于任一载体或列表版本,你不能获取索引但是从getPrivateChildIndex(widget)(例如,使用std::find()std::find_if())的迭代器。如果您绝对需要返回索引,则可以使用std::advance()移动到您可能在getPrivateChildIndex()中找到的位置。

1

首先,如果您必须通过索引访问容器,那么首先使用std::list可能是个坏主意。事实上,很少有这样的情况,它是适当的容器选择。

二,getPrivateChildIndex如何发现索引?如果它遍历列表,那么它可以返回一个迭代器,而不是索引。然后,你就可以简单地做:

privateChildren.erase(getPrivateChild(widget)); 

最后,如果你确信你想用一个链表,你必须使用一个索引,那么你需要什么std::advance功能:

#include <iterator> 
int index(getPrivateChildIndex(widget)); 
privateChildren.erase(std::advance(privateChildren.begin(), index));