从 c++ std::vector 中删除所有项目

2021-12-21 00:00:00 vector c++ stl

我正在尝试使用以下代码从 std::vector 中删除所有内容

I'm trying to delete everything from a std::vector by using the following code

vector.erase( vector.begin(), vector.end() );

但它不起作用.

更新:不清除破坏向量持有的元素?我不想那样,因为我还在使用对象,我只想清空容器

Update: Doesn't clear destruct the elements held by the vector? I don't want that, as I'm still using the objects, I just want to empty the container

推荐答案

我认为你应该使用 std::vector::clear:

I think you should use std::vector::clear:

vec.clear();

<小时>

不清除破坏元素由向量持有?

Doesn't clear destruct the elements held by the vector?

是的.它在返回内存之前调用向量中每个元素的析构函数.这取决于您在向量中存储的元素".在以下示例中,我将对象本身存储在向量中:

Yes it does. It calls the destructor of every element in the vector before returning the memory. That depends on what "elements" you are storing in the vector. In the following example, I am storing the objects them selves inside the vector:

class myclass
{
public:
    ~myclass()
    {

    }
...
};

std::vector<myclass> myvector;
...
myvector.clear(); // calling clear will do the following:
// 1) invoke the deconstrutor for every myclass
// 2) size == 0 (the vector contained the actual objects).

例如,如果您想在不同容器之间共享对象,则可以存储指向它们的指针.在这种情况下,当调用 clear 时,只释放指针内存,不接触实际对象:

If you want to share objects between different containers for example, you could store pointers to them. In this case, when clear is called, only pointers memory is released, the actual objects are not touched:

std::vector<myclass*> myvector;
...
myvector.clear(); // calling clear will do:
// 1) ---------------
// 2) size == 0 (the vector contained "pointers" not the actual objects).

对于评论中的问题,我认为getVector()是这样定义的:

For the question in the comment, I think getVector() is defined like this:

std::vector<myclass> getVector();

也许你想返回一个引用:

Maybe you want to return a reference:

// vector.getVector().clear() clears m_vector in this case
std::vector<myclass>& getVector(); 

相关文章