简体   繁体   English

c中的类向量存在哪些非破坏性替代方案

[英]What non-destructive alternatives exist to class vectors in c

I'm using a vector to hold pointers to a class. 我正在使用向量来保存指向类的指针。

class fooContainer{
private:
    vector <Foo *> foos;
public:
    void processFoo(int fooIndex);
};

The problem I face is that pop_back() drops the element, I only want to remove it from the vector but not touch the object in question. 我面临的问题是pop_back()删除元素,我只想从向量中删除它,但不要触摸有问题的对象。 I also need to remove all elements from a vector in preparation for restarting the main cycle (but keeping the same vector, which is a class attribute). 我还需要从向量中删除所有元素以准备重新启动主循环(但保持相同的向量,这是一个类属性)。

I need a structure that has dynamic sizing but does not copy or delete its elements, being content to hold pointers to them. 我需要一个具有动态大小调整但不复制或删除其元素的结构,是保存指针的内容。

Is there a better alternative structure, or am I using them all wrong? 是否有更好的替代结构,或者我使用它们都错了?

Vector does copy and destroy its contents, but in your case the content is pointer to object and not the object. Vector会复制并销毁其内容,但在您的情况下,内容是指向对象而不是对象的指针。
The specific pointer to the object will be destroyed, but other pointers to that object, and the object itself, won't be destroyed. 将破坏指向该对象的特定指针,但不会销毁该对象的其他指针和对象本身。

What you have does exactly that. 你所拥有的就是那个。 The object elements in the vector point to won't be destroyed unless you explicitly delete them. 除非您明确delete它们,否则不会销毁向量中指向的对象元素。

Alternatively, if you want to use the same pointers in multiple places with shared ownership, I suggest using std::shared_ptr . 或者,如果你想在拥有共享所有权的多个地方使用相同的指针,我建议使用std::shared_ptr

pop doesn't "drop" the element, it just removes it from the vector. pop不会“删除”元素,只是将其从向量中删除。 As your vector contains pointers, you are responsible for deleting them appropriately. 由于向量包含指针,因此您有责任正确删除它们。

Vector does exactly what you ask for. Vector完全符合您的要求。

To remove the elements, just call vector.clear() 要删除元素,只需调用vector.clear()

If you just want to get a copy of your pointer from your vector, then you can use Foo* pfoo = v[0] or the at(index) function for checked access. 如果您只想从向量中获取指针的副本,则可以使用Foo* pfoo = v[0]at(index)函数进行检查访问。

Also you want to clear all your pointers, you can loop through them and delete them all and call v.clear() to remove all elements. 此外,您想要清除所有指针,您可以遍历它们并将它们全部删除,并调用v.clear()来删除所有元素。

If you want a vector that already does the deleting of pointers for you correctly, use a boost::vector_ptr 如果你想要一个已经正确删除指针的向量,请使用boost::vector_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM