vector.erase();vector.clear();map.erase();

时间:2021-05-07 05:23:11

vector::erase()返回下一个iter:

vector.erase();vector.clear();map.erase();

STL中的源码:

//清除[first, last)中的所有元素
iterator erase(iterator first, iterator last)
{
iterator i = copy(last, finish, first);  //[last, finish)拷贝到first
destroy(i, finish);
finish = finish - (last - first);
return first;
}
//清除某个位置上的元素
iterator erase(iterator position)
{
if(position + 1 != end())
copy(position + 1, finish, position);
--finish;
destroy(finish);
return position;
}

用法:

for(vector<int>::iterator it = vecInt.begin(); it != vecInt.end();)
{
if(*it == 0)
{
it = vecInt.erase(it);
}
else
{
it++;
}
}

vector.clear()

  vector中存储了对象的指针,调用clear后,并不会调用这些指针所指对象析构函数,因此要在clear之前调用delete;   

  如果vector存储的是对象,调用clear后,自建类型的对象(int之类的)直接删除,若是外部类型,则调用析构函数。

看个vector内存分配的例子:

class Test
{
public:
Test(int x1): x(x1) { cout << "Test cons" << x << endl; }
~Test() { cout << "Test des" << x << endl; }
int x;
};
int main()
{
vector<Test> vec;
Test* p1 = new Test(1);
Test* p2 = new Test(2);
Test* p3 = new Test(3);
vec.push_back(*p1);
vec.push_back(*p2);
vec.push_back(*p3); vec.clear();
system("pause");
return 0;
}

输出:

vector.erase();vector.clear();map.erase();

这里析构了6次,原因是vector的容量永远是大于或者等于size。而当内存不够的时候,会重新allocate新的内存,拷贝数据,deallocate当前内存,;

这里内存变化是1->2->4,所以析构次数是1+2+3=6次。

map::erase()没有返回下一个iter:

(1) void erase (iterator position) { t.erase(position); }
(2) size_type erase (const key_type& x) { return t.erase(x); }
(3) void erase (iterator first, iterator last) { t.erase(first, last); }

vector.erase();vector.clear();map.erase();

用法:

for(map<int,int>::iterator it = mapInt.begin(); it != mapInt.end();)
{
if(it->second == 0)
{
mapInt.erase(it++);
}
else
{
it++;
}
}