从 STL 容器中删除某些内容而不解构它
好的,我正在使用 C++ STL 容器(当前为 vector
)。 现在我需要从容器中删除元素, 但是使用擦除会解构该对象,这很糟糕,因为我将其从一个对象上取下,然后将其放入一个变量上进行一些处理,然后放入另一个对象上。
目前我的代码非常糟糕,我只是在读完它后将 NULL 放入我的变量中,然后放入 if (Q[ii]NULL) continue 。 但这并不是那么好。
Ok, I'm using C++ STL containers (currently vector<customType*>
).
Now I need to remove elements from the container,
but using erase deconstructs the object, which is bad, since I'm taking it off one, and putting it onto a variable doing some processing then onto another one.
At the moment my code is quite nasty, and I'm just putting NULL in its place after I've read it, into my variable, and then putting a if (Q[ii]NULL) continue.
But this is not so great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有一个指针容器(这听起来像是您所做的,因为您将
NULL
分配给“已删除”元素),那么从容器中删除元素不会删除所指向的对象。您有责任自己做这件事。如果您有一个对象容器(好吧,非指针对象),那么您需要在删除元素之前将其复制出容器。
If you have a container of pointers (which it sounds like you do since you are assigning
NULL
to "erased" elements), then erasing an element from the container does not delete the pointed-to object. You are responsible for doing that yourself.If you have a container of objects (well, non-pointer objects), then you need to copy the element out of the container before you erase it.
您无法真正从向量中删除元素而不破坏它。如果您的向量存储指针,您可以删除指向元素的指针,这实际上不会破坏元素本身。
You can't really remove the element from the vector without destroying it. If your vector stores pointers, you can remove the pointer to the element, which won't actually destroy the element itself.
STL容器操作具有复制语义。因此,每当您添加或删除元素时,构造函数或析构函数都会相应地被调用(假设是非原始类型)。如果在此过程中调整向量的大小,则所有对象都将被复制构造,并且原始对象将被破坏。没有办法避免所有这些复制。
避免开销的唯一方法是使用(智能)指针向量而不是对象。
STL container operations have copy semantics. So any time you add or remove elements, the constructor or destructor will get called accordingly (assuming a non-primitive type). And if the vector gets resized in the process, all objects will be copy-constructed and the originals destructed. There's no way to avoid all this copying.
The only way to avoid the overhead is to have a vector of (smart) pointers instead of objects.