如果我们无法从C ++容器中删除元素,我们该怎么办?

时间:2014-01-14 16:14:44

标签: c++ stl

我现在正在使用我的同事的一些代码,他们用C ++创建了一个不可取的容器。容器看起来像:

NoDeleteContainer<MyObject> objList;  

使用他的容器,我现在在内部objList创建一些对象。我现在正在做的是分析每个对象内部人员objList的特征,如果对象的特征符合某些标准,我会保留它们。那么我现在的问题是我不知道保留它们的最佳做法是什么,我可以找出几种解决方案:

解决方案1:

NoDeleteContainer<MyObject*> selObjPointerList;
//selObjPointerList will then keeps the pointer to the selected objects.

解决方案2:

std::vector indictorVec(objList.size(),false);
   // change the indictor's value to true if its corresponding MyObject fulfill the requirements.

解决方案3:

std::vector<MyObject*> selObjPointerList;
   // similar to Solution 1

然后我的问题是哪种解决方案最好,或者如果你有新的解决方案,请随时讨论它们。

1 个答案:

答案 0 :(得分:2)

在不可变容器上进行变体的通常方法是创建容器的新实例,只包含所选项。

在过滤过程中使用可变容器可能会有所帮助。

在某些多线程编程风格中通常会遇到不可变容器。