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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1525535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:17:15  来源:igfitidea点击:

Delete all items from a c++ std::vector

c++stlvector

提问by michael

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

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

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

but it doesn't work.

但它不起作用。



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

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

回答by AraK

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

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

vec.clear();


EDIT:

编辑:

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).

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

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

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

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

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

std::vector<myclass> getVector();

Maybe you want to return a reference:

也许你想返回一个引用:

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

回答by aJ.

vector.clear()should work for you. In case you want to shrink the capacity of the vectoralong with clear then

vector.clear()应该为你工作。如果您想缩小容量vector并清除,那么

std::vector<T>(v).swap(v);

回答by DevSolar

vector.clear() is effectively the same as vector.erase( vector.begin(), vector.end() ).

vector.clear() 实际上与 vector.erase( vector.begin(), vector.end() ) 相同。

If your problem is about calling deletefor each pointercontained in your vector, try this:

如果您的问题是关于调用向量中包含的delete每个指针,请尝试以下操作:

#include <algorithm>

template< typename T >
struct delete_pointer_element
{
    void operator()( T element ) const
    {
        delete element;
    }
};

// ...
std::for_each( vector.begin(), vector.end(), delete_pointer_element<int*>() );

Edit:Code rendered obsolete by C++11 range-for.

编辑:C++11 range-for 使代码过时。

回答by Alex B

Use v.clear()to empty the vector.

使用v.clear()清空向量。

If your vector contains pointers, clear calls the destructor for the object but does not delete the memory referenced by the pointer.

如果您的向量包含指针,clear 会调用对象的析构函数,但不会删除指针引用的内存。

vector<SomeClass*> v(0);

v.push_back( new SomeClass("one") );

v.clear();  //Memory leak where "one" instance of SomeClass is lost

回答by Rob

Is v.clear()not working for some reason?

v.clear()不是因为某种原因不工作?

回答by Dominic.wig

If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)

如果您将指针保存在容器中并且不想手动销毁它们,那么使用boost shared_ptr。这是 std::vector 的示例,但您可以将它用于任何其他 STL 容器(set、map、queue...)

#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct foo
{
    foo( const int i_x ) : d_x( i_x )
    {
        std::cout << "foo::foo " << d_x << std::endl;
    }

    ~foo()
    {
        std::cout << "foo::~foo " << d_x << std::endl;
    }

    int d_x;
};

typedef boost::shared_ptr< foo > smart_foo_t;

int main()
{
    std::vector< smart_foo_t > foos;
    for ( int i = 0; i < 10; ++i )
    {
        smart_foo_t f( new foo( i ) );
        foos.push_back( f );
    }

    foos.clear();

    return 0;
}

回答by Samer

Adding to the above mentioned benefits of swap().That clear()does not guarantee deallocation of memory. You can use swap()as follows:

添加到上面提到的swap().That 的好处clear()并不能保证内存的释放。您可以swap()按如下方式使用:

std::vector<T>().swap(myvector);

回答by Sinipelto

class Class;
std::vector<Class*> vec = some_data;

for (unsigned int i=vec.size(); i>0;) {
    --i;
    delete vec[i];
    vec.pop_back();
}
// Free memory, efficient for large sized vector
vec.shrink_to_fit();

Performance: theta(n)

性能:theta(n)

If pure objects (not recommended for large data types, then just vec.clear();

如果是纯对象(不推荐用于大数据类型,则只需 vec.clear();

回答by Satbir

If your vector look like this std::vector<MyClass*> vecType_ptyou have to explicitly release memory ,Or if your vector look like : std::vector<MyClass> vecType_obj, constructor will be called by vector.Please execute example given below , and understand the difference :

如果你的向量看起来像这样std::vector<MyClass*> vecType_pt你必须显式释放内存,或者如果你的向量看起来像:std::vector<MyClass> vecType_obj,构造函数将被向量调用。请执行下面给出的例子,并理解区别:

  class MyClass
    {
    public:
        MyClass()
        {
            cout<<"MyClass"<<endl;
        }
        ~MyClass()
        {
            cout<<"~MyClass"<<endl;
        }
    };
    int main() 
    {
        typedef std::vector<MyClass*> vecType_ptr;
        typedef std::vector<MyClass> vecType_obj;
        vecType_ptr myVec_ptr;
        vecType_obj myVec_obj;
        MyClass obj;
        for(int i=0;i<5;i++)
        {
            MyClass *ptr=new MyClass();
            myVec_ptr.push_back(ptr);
            myVec_obj.push_back(obj);
        }
        cout<<"\n\n---------------------If pointer stored---------------------"<<endl;
        myVec_ptr.erase (myVec_ptr.begin(),myVec_ptr.end());
        cout<<"\n\n---------------------If object stored---------------------"<<endl;
        myVec_obj.erase (myVec_obj.begin(),myVec_obj.end());
        return 0;
    }