vector::clear

转载自:http://huycwork.blog.163.com/blog/static/136751999201052213532314/

clear

原型:

    #include <vector>
void clear();

函数clear()删除储存在vector中的所有元素. 如果vector的元素是一些object, 则它将为当前储存的每个元素调用它们各自的析构函数(destructor). 然而, 如果vector储存的是指向对象的指针, 此函数并不会调用到对应的析构函数. 在第二种情况下, 为了完全删除vector中的元素则应使用一个类似于下的循环:

    std::vector<SomeObject*> aVector;
[...] //The elements of the vector are created with the operand 'new' at some point in the program
for(int i=0 ; i<aVector.size() ; i++)
delete aVector[i];
aVector.clear();

调用clear之后, vector的尺寸(size)将变成zero. 但它的容量(capacity)却并不发生变化, vector本身并不释放任何内存.

如果你想同时做到清空vector的元素和释放vector的容量, 你可以使用swap技巧(此技巧并非在所有环境中都管用 e.g. not with Intel Compiler 10.0.69 and LINUX 2.6.9-89 x64):

    std::vector aVector;
[...]
aVector.swap( std::vector() );

这样做会创建一个临时的空vector, 它将替换希望清空的vector.

clear()以线性时间linear time运行.


posted on 2011-11-19 13:02  yang3wei  阅读(236)  评论(0编辑  收藏  举报