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

时间:2009-10-06 13:19:00

标签: c++ stl vector

我正在尝试使用以下代码

删除std::vector中的所有内容
vector.erase( vector.begin(), vector.end() );

但它不起作用。


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

9 个答案:

答案 0 :(得分:99)

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

vec.clear();

编辑:

  

不清除破坏元素   矢量持有?

是的。它在返回内存之前调用向量中每个元素的析构函数。这取决于您在矢量中存储的“元素”。在下面的例子中,我将它们自己存储在向量中的对象:

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时,只释放指针内存,不触及实际对象:

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

对于评论中的问题,我认为getVector()的定义如下:

std::vector<myclass> getVector();

也许你想要返回一个引用:

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

答案 1 :(得分:33)

vector.clear()应该适合你。如果你想缩小vector的容量以及清除

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

答案 2 :(得分:10)

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

如果您的问题是关于向量中包含的每个指针调用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 );

标准免责声明:使用浏览器编写的代码,未经测试。

答案 3 :(得分:9)

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

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

vector<SomeClass*> v(0);

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

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

答案 4 :(得分:4)

v.clear()因某种原因无效吗?

答案 5 :(得分:3)

如果您将指针保留在容器中并且不想手动销毁它们,请使用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;
}

答案 6 :(得分:2)

增加swap().的上述好处clear()并不能保证释放内存。您可以按如下方式使用swap()

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

答案 7 :(得分:-1)

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

  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;
    }

答案 8 :(得分:-1)

$users = $curl->request('GET_USERS'); // Makes an external call and returns an Array of Users (Avg 600+). The response size of the json object is around 380 kB
foreach($users as $user){
    // Fetch User Information 
    $user_info = $curl->request('GET_USER_INFO'); // Response Size of the jSON Object is 21.54 kB
    // Update External Service with this Info
    $external_service = $curl->request('UPDATE_USER',$user_info);
} // Loop will happen for around 600+ iterations on average.

表现:theta(n)

如果是纯对象(不推荐用于大数据类型,那么就是     vec.clear();

相关问题